<commit_before>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/

var CSS_UNITS = 96.0 / 72.0; //this is apparently a thing.
var xform = 'transform';
['','webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
    var e = prefix + (prefix ? 'T':'t') +  'ransform';
    if (typeof document.body.style[e] !== 'undefined') {
        xform = e;
        return false;
    }
    return true;
});

/*
!function (w) {

    function getOutputScale(ctx) {
        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                                ctx.mozBackingStorePixelRatio ||
                                ctx.msBackingStorePixelRatio ||
                                ctx.oBackingStorePixelRatio ||
                                ctx.backingStorePixelRatio || 1;
        var pixelRatio = devicePixelRatio / backingStoreRatio;
        return {
            sx: pixelRatio,
            sy: pixelRatio,
            scaled: pixelRatio !== 1
        };
    }

    PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
        var pageDivs = [];
        function createPage(n) {
            if (n > pdf.numPages) {
                return;
            }
            var div = document.createElement('div');
            pageDivs.push(div);
            pdf.getPage(n).then(function (page) {
                var scale = 0.6;
                var viewport = page.getViewport(scale * CSS_UNITS);

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');

                var outputScale = getOutputScale(canvas);
                canvas.height = viewport.height * outputScale.sy;
                canvas.width = viewport.width * outputScale.sx;

                div.appendChild(canvas);
                page.render({
                    canvasContext: context,
                    viewport: viewport
                });
            });
            createPage(n + 1);
        }
        createPage(1);
        pageDivs.forEach(function (div) {
            document.body.appendChild(div);
        });
    });
} (window);
*/

function getOutputScale(ctx) {
    var canvas;
    if (ctx === undefined) {
        if (canvas === undefined) {
            canvas = document.createElement('canvas');
        }
        ctx = canvas.getContext('2d');
    }
    var devicePixelRatio = window.devicePixelRatio || 1;
    var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                            ctx.mozBackingStorePixelRatio ||
                            ctx.msBackingStorePixelRatio ||
                            ctx.oBackingStorePixelRatio ||
                            ctx.backingStorePixelRatio || 1;
    var pixelRatio = devicePixelRatio / backingStoreRatio;
    return {
        sx: pixelRatio,
        sy: pixelRatio,
        scaled: pixelRatio !== 1
    };
}

window.pdfViewer = function pdfViewer(container, documentUri) {
    // todo:
    /// Creates a pdf viewer in the given container
    /// <param name="container" type="HTMLElement">The container to create the pdf viewer in.</param>
    'use strict';

    if (container === null) {
        throw 'can not create viewer in null container';
    }
    if (container === undefined) {
        throw 'can not create viewer in undefined container';
    }
    if (!(container instanceof HTMLElement)) {
        throw 'can not create viewer in container that is not HTMLElement';
    }
    /** @type HTMLElement */
    var _container = container;

    /** @type String */
    var _uri = documentUri;
    /** @type HTMLElement */
    var _inner;
    /** @type PDFPromise<PDFDocumentProxy> */
    var _loadingTask;
    /** @type PDFDocumentProxy */
    var _pdfDocument;

    var _pages = [];
    /** @type {number} */
    var _pageCount;
    /** @type {number} */
    var _scale = defaultScale();
    /** @type {number} */
    var _page_gap = 10; //pixel space between pages

    var _resizeEventTriggered = false;

    initialiseContainers();
    setPdf(_uri);

    var _viewer = {
        position: function (value) {
            if (value === undefined) {
                return _container.scrollLeft;
            }
            _container.scrollLeft = value;
        },
    };
    return _viewer;

    function renderViewer() {
        _pages.forEach(function (p) {
            redrawPage(p);
        });
        //set all widths of containers to max width of a container;
        var w= 0;
        _container.firstChild.childNodes.forEach(function (c) {
            if (c.firstChild && c.firstChild.width > w) {
                w= c.firstChild.width + _page_gap;
            }
        });
        _container.firstChild.childNodes.forEach(function (c) {
            c.style.minWidth = w + 'px';
        });
    }

    /**
     * @param {String} uri
     */
    function setPdf(uri) {
        _loadingTask = PDFJS.getDocument(uri);
        _loadingTask.then(pdfReady);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfReady(pdf) {
        _pdfDocument = pdf;
        _pageCount = pdf.numPages;
        addPageContainers();
        _pdfDocument.getDownloadInfo().then(pdfLoaded);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfLoaded() {
        //create pageViewObjects
        for (var n = 1; n <= _pageCount; ++n) {
            var pageView = {
                id: n,
                scale: _scale,
                rendered: false,
                loaded: false,
            };
            //todo: ? bind events
            _pages.push(pageView);
        }
        var pagePromises = [];
        _pages.forEach(function (pageView) {
            var pagePromise = _pdfDocument.getPage(pageView.id);
            pagePromises.push(pagePromise);
            var index = pageView.id - 1;
            /** @param {} page */
            pagePromise.then(function (page) {
                _pages[index].baseWidth = page.getViewport(1.0 * CSS_UNITS).width;
                _pages[index].defaultScale = defaultScale(_pages[index]);
                _pages[index].page = page;
                _pages[index].loaded = true;
            });
        });
        Promise.all(pagePromises).then(function () {
            _scale = _pages[0].defaultScale;
            renderViewer();
            registerEvents();
        });
    }

    function initialiseContainers() {
        _container.classList.add('pdfviewer-container');
        _inner = document.createElement('div');
        _inner.classList.add('pdfviewer-inner');
        _container.appendChild(_inner);
        //todo: add mini previews?
    }

    function addPageContainers() {
        for (var i = 0; i < _pageCount; ++i){
            var pageContainer = document.createElement('div');
            pageContainer.classList.add('pdfviewer-pagecontainer');
            pageContainer.classList.add('pdfviewer-loading');
            pageContainer.style.visibility = 'hidden';
            _inner.appendChild(pageContainer);
        }
    }

    function redrawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        if (pageContainer === undefined) {
            throw 'can not redraw, not properly initialised';
        }
        var inView = pageInView(index);
        var rendered = pageView.rendered;
        var loaded = pageView.loaded;
        //draw page if it is in view and not currently rendered or has changed scale since last render.
        if (loaded && inView && (!rendered || _scale != pageView.scale)) {
            drawPage(pageView);
        }
        //clear a page which is not in view, but is currently rendered;
        if (!inView && rendered) {
            clearPage(pageView);
        }
    }

    function drawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];

        var canvas = document.createElement('canvas');
        var outputScale = getOutputScale(canvas);
        var viewport = pageView.page.getViewport(_scale * CSS_UNITS * outputScale.sx);

        canvas.height = viewport.height;
        canvas.width = viewport.width;

        var context = canvas.getContext('2d');
        pageView.rendered = true;
        pageView.page.render({
            canvasContext: context,
            viewport: viewport
        }).then(function () {
            pageContainer.classList.remove('pdfviewer-loading');
            if (pageContainer.firstChild) {
                var hasChild = true;
            }
            pageContainer.appendChild(canvas);
            if (hasChild) {
                pageContainer.removeChild(pageContainer.firstChild);
            }
            pageContainer.style.visibility = 'visible';
        });
    }

    function clearPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        while (pageContainer.firstChild) {
            pageContainer.removeChild(pageContainer.firstChild);
        }
        pageContainer.classList.add('pdfviewer-loading');
        pageView.rendered = false;
    }

    function pageInView(index) {
        var pageWidth = _pages[0].baseWidth * _pages[0].defaultScale; //scroll positions are not scaled as the page is
        var viewerWidth = _container.clientWidth;
        var minIndex = Math.floor(_container.scrollLeft / (pageWidth + _page_gap)) - 1; //-1 to allow an extra page to be prerendered
        var maxIndex = Math.floor((_container.scrollLeft + viewerWidth) / (pageWidth + _page_gap)) + 1; //same for the + 1

        return index >= minIndex && index <= maxIndex;
    }

    function defaultScale(page) {
        ///Determine a reasonable default scale based on device
        if (page === undefined) {
            return 0.5;
        }
        return _container.clientWidth / (page.baseWidth * getOutputScale().sx);
    }

    function registerEvents() {
        window.addEventListener('resize', onResize);
        _container.addEventListener('scroll', onScroll);
    }

    function onResize() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }

    function onScroll() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }
};<commit_msg>more experimental fixes<commit_after>/*global PDFJS:false*/
/*eslint-env browser*/
/*eslint-env es6*/

var CSS_UNITS = 96.0 / 72.0; //this is apparently a thing.
var xform = 'transform';
['','webkit', 'Moz', 'O', 'ms'].every(function (prefix) {
    var e = prefix + (prefix ? 'T':'t') +  'ransform';
    if (typeof document.body.style[e] !== 'undefined') {
        xform = e;
        return false;
    }
    return true;
});

/*
!function (w) {

    function getOutputScale(ctx) {
        var devicePixelRatio = window.devicePixelRatio || 1;
        var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                                ctx.mozBackingStorePixelRatio ||
                                ctx.msBackingStorePixelRatio ||
                                ctx.oBackingStorePixelRatio ||
                                ctx.backingStorePixelRatio || 1;
        var pixelRatio = devicePixelRatio / backingStoreRatio;
        return {
            sx: pixelRatio,
            sy: pixelRatio,
            scaled: pixelRatio !== 1
        };
    }

    PDFJS.getDocument('1609.01714.pdf').then(function (pdf) {
        var pageDivs = [];
        function createPage(n) {
            if (n > pdf.numPages) {
                return;
            }
            var div = document.createElement('div');
            pageDivs.push(div);
            pdf.getPage(n).then(function (page) {
                var scale = 0.6;
                var viewport = page.getViewport(scale * CSS_UNITS);

                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');

                var outputScale = getOutputScale(canvas);
                canvas.height = viewport.height * outputScale.sy;
                canvas.width = viewport.width * outputScale.sx;

                div.appendChild(canvas);
                page.render({
                    canvasContext: context,
                    viewport: viewport
                });
            });
            createPage(n + 1);
        }
        createPage(1);
        pageDivs.forEach(function (div) {
            document.body.appendChild(div);
        });
    });
} (window);
*/

function getOutputScale(ctx) {
    var canvas;
    if (ctx === undefined) {
        if (canvas === undefined) {
            canvas = document.createElement('canvas');
        }
        ctx = canvas.getContext('2d');
    }
    var devicePixelRatio = window.devicePixelRatio || 1;
    var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
                            ctx.mozBackingStorePixelRatio ||
                            ctx.msBackingStorePixelRatio ||
                            ctx.oBackingStorePixelRatio ||
                            ctx.backingStorePixelRatio || 1;
    var pixelRatio = devicePixelRatio / backingStoreRatio;
    return {
        sx: pixelRatio,
        sy: pixelRatio,
        scaled: pixelRatio !== 1
    };
}

window.pdfViewer = function pdfViewer(container, documentUri) {
    // todo:
    /// Creates a pdf viewer in the given container
    /// <param name="container" type="HTMLElement">The container to create the pdf viewer in.</param>
    'use strict';

    if (container === null) {
        throw 'can not create viewer in null container';
    }
    if (container === undefined) {
        throw 'can not create viewer in undefined container';
    }
    if (!(container instanceof HTMLElement)) {
        throw 'can not create viewer in container that is not HTMLElement';
    }
    /** @type HTMLElement */
    var _container = container;

    /** @type String */
    var _uri = documentUri;
    /** @type HTMLElement */
    var _inner;
    /** @type PDFPromise<PDFDocumentProxy> */
    var _loadingTask;
    /** @type PDFDocumentProxy */
    var _pdfDocument;

    var _pages = [];
    /** @type {number} */
    var _pageCount;
    /** @type {number} */
    var _scale = defaultScale();
    /** @type {number} */
    var _page_gap = 10; //pixel space between pages

    var _resizeEventTriggered = false;
    var _pageWidth = 0;

    initialiseContainers();
    setPdf(_uri);

    var _viewer = {
        position: function (value) {
            if (value === undefined) {
                return _container.scrollLeft;
            }
            _container.scrollLeft = value;
        },
    };
    return _viewer;

    function renderViewer() {
        _pages.forEach(function (p) {
            redrawPage(p);
        });
        //set all widths of containers to max width of a container;
        var w= _pageWidth;
        _container.firstChild.childNodes.forEach(function (c) {
            c.style.minWidth = w + 'px';
        });
    }

    /**
     * @param {String} uri
     */
    function setPdf(uri) {
        _loadingTask = PDFJS.getDocument(uri);
        _loadingTask.then(pdfReady);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfReady(pdf) {
        _pdfDocument = pdf;
        _pageCount = pdf.numPages;
        addPageContainers();
        _pdfDocument.getDownloadInfo().then(pdfLoaded);
    }
    /**
     * @param {PDFDocumentProxy} pdf
     */
    function pdfLoaded() {
        //create pageViewObjects
        for (var n = 1; n <= _pageCount; ++n) {
            var pageView = {
                id: n,
                scale: _scale,
                rendered: false,
                loaded: false,
            };
            //todo: ? bind events
            _pages.push(pageView);
        }
        var pagePromises = [];
        _pages.forEach(function (pageView) {
            var pagePromise = _pdfDocument.getPage(pageView.id);
            pagePromises.push(pagePromise);
            var index = pageView.id - 1;
            /** @param {} page */
            pagePromise.then(function (page) {
                _pages[index].baseWidth = page.getViewport(1.0 * CSS_UNITS).width;
                _pages[index].defaultScale = defaultScale(_pages[index]);
                _pages[index].page = page;
                _pages[index].loaded = true;
            });
        });
        Promise.all(pagePromises).then(function () {
            _scale = _pages[0].defaultScale;
            renderViewer();
            registerEvents();
        });
    }

    function initialiseContainers() {
        _container.classList.add('pdfviewer-container');
        _inner = document.createElement('div');
        _inner.classList.add('pdfviewer-inner');
        _container.appendChild(_inner);
        //todo: add mini previews?
    }

    function addPageContainers() {
        for (var i = 0; i < _pageCount; ++i){
            var pageContainer = document.createElement('div');
            pageContainer.classList.add('pdfviewer-pagecontainer');
            pageContainer.classList.add('pdfviewer-loading');
            pageContainer.style.visibility = 'hidden';
            _inner.appendChild(pageContainer);
        }
    }

    function redrawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        if (pageContainer === undefined) {
            throw 'can not redraw, not properly initialised';
        }
        var inView = pageInView(index);
        var rendered = pageView.rendered;
        var loaded = pageView.loaded;
        //draw page if it is in view and not currently rendered or has changed scale since last render.
        if (loaded && inView && (!rendered || _scale != pageView.scale)) {
            drawPage(pageView);
        }else{
            clearPage(pageView);
        }
    }

    function drawPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];

        var canvas = document.createElement('canvas');
        var outputScale = getOutputScale(canvas);
        var viewport = pageView.page.getViewport(_scale * CSS_UNITS * outputScale.sx);

        canvas.height = viewport.height;
        canvas.width = viewport.width;
        _pageWidth = canvas.width;

        var context = canvas.getContext('2d');
        pageView.rendered = true;
        pageView.page.render({
            canvasContext: context,
            viewport: viewport
        }).then(function () {
            pageContainer.classList.remove('pdfviewer-loading');
            if (pageContainer.firstChild) {
                var hasChild = true;
            }
            pageContainer.appendChild(canvas);
            if (hasChild) {
                pageContainer.removeChild(pageContainer.firstChild);
            }
            pageContainer.style.visibility = 'visible';
        });
    }

    function clearPage(pageView) {
        var index = pageView.id - 1;
        var pageContainer = _inner.children[index];
        while (pageContainer.firstChild) {
            pageContainer.removeChild(pageContainer.firstChild);
        }
        pageContainer.classList.add('pdfviewer-loading');
        pageView.rendered = false;
    }

    function pageInView(index) {
        var pageWidth = _pageWidth; //scroll positions are not scaled as the page is
        var viewerWidth = _container.clientWidth;
        var minIndex = Math.floor(_container.scrollLeft / (pageWidth + _page_gap)) - 1; //-1 to allow an extra page to be prerendered
        var maxIndex = Math.floor((_container.scrollLeft + viewerWidth) / (pageWidth + _page_gap)) + 1; //same for the + 1

        return index >= minIndex && index <= maxIndex;
    }

    function defaultScale(page) {
        ///Determine a reasonable default scale based on device
        if (page === undefined) {
            return 0.5;
        }
        return _container.clientWidth / (page.baseWidth * getOutputScale().sx);
    }

    function registerEvents() {
        window.addEventListener('resize', onResize);
        _container.addEventListener('scroll', onScroll);
    }

    function onResize() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }

    function onScroll() {
        if (!_resizeEventTriggered) {
            window.requestAnimationFrame( function () {
                renderViewer();
                _resizeEventTriggered = false;
            });
        }
        _resizeEventTriggered = true;
    }
};<|endoftext|>


<commit_before>/*
 * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
 */

/**
 * @class Mobile.SalesLogix.Views.Activity.List
 *
 * @extends Sage.Platform.Mobile.List
 * @mixins Mobile.SalesLogix.Views._RightDrawerListMixin
 * @mixins Mobile.SalesLogix.Views._CardLayoutListMixin
 *
 * @requires Sage.Platform.Mobile.List
 * @requires Sage.Platform.Mobile.Utility
 * @requires Sage.Platform.Mobile.Convert
 * @requires Sage.Platform.Mobile.ErrorManager
 * @requires Mobile.SalesLogix.Action
 * @requires Mobile.SalesLogix.Environment
 * @requires Mobile.SalesLogix.Format
 * @requires Mobile.SalesLogix.Views._CardLayoutListMixin
 * @requires Mobile.SalesLogix.Views._RightDrawerListMixin
 *
 */
define('Mobile/SalesLogix/Views/Activity/List', [
    'dojo/_base/declare',
    'dojo/_base/connect',
    'dojo/string',
    'dojo/query',
    'dojo/dom-class',
    'Mobile/SalesLogix/Views/_RightDrawerListMixin',
    'Sage/Platform/Mobile/List',
    'Mobile/SalesLogix/Views/_CardLayoutListMixin',
    'Mobile/SalesLogix/Format',
    'Sage/Platform/Mobile/Utility',
    'Sage/Platform/Mobile/Convert',
    'Mobile/SalesLogix/Action',
    'Mobile/SalesLogix/Environment',
    'Sage/Platform/Mobile/ErrorManager',
    'moment'
], function(
    declare,
    connect,
    string,
    query,
    domClass,
    _RightDrawerListMixin,
    List,
    _CardLayoutListMixin,
    format,
    Utility,
    convert,
    action,
    environment,
    ErrorManager,
    moment
) {

    return declare('Mobile.SalesLogix.Views.Activity.List', [List, _RightDrawerListMixin, _CardLayoutListMixin], {
        // Localization
        allDayText: 'All-Day',
        completeActivityText: 'Complete',
        callText: 'Call',
        calledText: 'Called',
        addAttachmentActionText: 'Add Attachment',
        overdueText: 'overdue',
        alarmText: 'alarm',
        touchedText: 'touched',
        importantText: 'important',
        recurringText: 'recurring',

        //Card View
        itemIcon: 'content/images/icons/man_1.png',

        //Templates
        //Card View
        itemRowContainerTemplate: new Simplate([
            '
',
               '{%! $$.itemRowContentTemplate %}',
            '
'
        ]),
        activityTimeTemplate: new Simplate([
            '{%: Mobile.SalesLogix.Format.relativeDate($.StartDate, Sage.Platform.Mobile.Convert.toBoolean($.Timeless)) %}'
        ]),
        itemTemplate: new Simplate([
            '
',
                '{%: $.Description %}',
            '
',
            '
',
                '{%! $$.activityTimeTemplate %}',
            '
',
            '
{%! $$.nameTemplate %}
'
        ]),
        nameTemplate: new Simplate([
            '{% if ($.ContactName) { %}',
            '{%: $.ContactName %} | {%: $.AccountName %}',
            '{% } else if ($.AccountName) { %}',
            '{%: $.AccountName %}',
            '{% } else { %}',
            '{%: $.LeadName %}',
            '{% } %}'
        ]),
        activityIndicatorIconByType: {
            'atToDo': 'fa fa-list-ul',
            'atPhoneCall': 'fa fa-phone',
            'atAppointment': 'fa fa-users',
            'atLiterature': 'fa fa-book',
            'atPersonal': 'fa fa-check-square-o',
            'atQuestion': 'fa fa-question-circle',
            'atNote': 'fa fa-file-text-o',
            'atEMail': 'fa fa-envelope'
        },
        activityTypeText: {
            'atToDo': 'To-Do',
            'atPhoneCall': 'Phone Call',
            'atAppointment': 'Meeting',
            'atLiterature': 'Lit Request',
            'atPersonal': 'Personal',
            'atQuestion': 'Question',
            'atNote': 'Note',
            'atEMail': 'Email'
        },
        //Localization
        titleText: 'Activities',

        //View Properties
        id: 'activity_list',
        security: null, //'Entities/Activity/View',
        iconClass: 'fa fa-check-square-o fa-lg',
        detailView: 'activity_detail',
        insertView: 'activity_types_list',
        historyEditView: 'history_edit',
        enableActions: true,
        queryOrderBy: 'StartDate desc',
        querySelect: [
            'Description',
            'StartDate',
            'Type',
            'AccountId',
            'AccountName',
            'ContactId',
            'ContactName',
            'PhoneNumber',
            'LeadId',
            'LeadName',
            'TicketId',
            'OpportunityId',
            'Leader',
            'UserId',
            'Timeless',
            'Alarm',
            'Priority',
            'ModifyDate',
            'RecurrenceState',
            'Recurring'
        ],
        queryInclude: [
            '$descriptors'
        ],
        resourceKind: 'activities',
        contractName: 'system',
        pageSize: 105,

        hashTagQueries: {
            'alarm': 'Alarm eq true',
            'recurring': 'Recurring eq true',
            'timeless': 'Timeless eq true',
            'yesterday': function() {
                var now, yesterdayStart, yesterdayEnd, query;

                now = moment();

                yesterdayStart = now.clone().subtract(1, 'days').startOf('day');
                yesterdayEnd = yesterdayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(yesterdayStart.toDate()),
                        convert.toIsoStringFromDate(yesterdayEnd.toDate()),
                        yesterdayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        yesterdayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'today': function() {
                var now, todayStart, todayEnd, query;

                now = moment();

                todayStart = now.clone().startOf('day');
                todayEnd = todayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(todayStart.toDate()),
                        convert.toIsoStringFromDate(todayEnd.toDate()),
                        todayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        todayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'this-week': function() {
                var now, weekStartDate, weekEndDate, query;

                now = moment();

                weekStartDate = now.clone().startOf('week');
                weekEndDate = weekStartDate.clone().endOf('week');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(weekStartDate.toDate()),
                        convert.toIsoStringFromDate(weekEndDate.toDate()),
                        weekStartDate.format('YYYY-MM-DDT00:00:00[Z]'),
                        weekEndDate.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            }
        },
        hashTagQueriesText: {
            'alarm': 'alarm',
            'recurring': 'recurring',
            'timeless': 'timeless',
            'today': 'today',
            'this-week': 'this-week',
            'yesterday': 'yesterday'
        },
        defaultSearchTerm: function() {
            if (App.enableHashTags) {
                return '#' + this.hashTagQueriesText['this-week'];
            }

            return '';
        },
        formatSearchQuery: function(searchQuery) {
            return string.substitute('upper(Description) like "%${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
        },
        formatDateTime: function(dateTime) {
            return 'StartTime';
        },
        getItemActionKey: function(entry) {
            return entry.$key;
        },
        getItemDescriptor: function(entry) {
            return entry.$descriptor;
        },
        createIndicatorLayout: function() {
            return this.itemIndicators || (this.itemIndicators = [{
                id: 'alarm',
                cls: 'fa fa-bell-o fa-lg',
                label: this.alarmText,
                onApply: function(entry, parent) {
                    this.isEnabled = parent.hasAlarm(entry);
                }
                }, {
                    id: 'touched',
                    cls: 'fa fa-hand-o-up fa-lg',
                    label: this.touchedText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.hasBeenTouched(entry);
                    }
                }, {
                    id: 'important',
                    cls: 'fa fa-exclamation fa-lg',
                    label: this.importantText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isImportant(entry);
                    }
                }, {
                    id: 'overdue',
                    cls: 'indicator_Important',
                    label: this.overdueText,
                    valueText: this.overdueText,
                    showIcon: false,
                    location: 'top',
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isOverdue(entry);
                    }
                }, {
                    id: 'recurring',
                    cls: 'fa fa-refresh fa-lg',
                    label: this.recurringText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isRecurring(entry, this);
                    }
                }
            ]);
        },
        hasBeenTouched: function(entry) {
            var modifiedDate, currentDate, weekAgo;
            if (entry['ModifyDate']) {
                modifiedDate = moment(convert.toDateFromString(entry['ModifyDate']));
                currentDate = moment().endOf('day');
                weekAgo = moment().subtract(1, 'weeks');

                return modifiedDate.isAfter(weekAgo) &&
                    modifiedDate.isBefore(currentDate);
            }
            return false;
        },
        isImportant: function(entry) {
            if (entry['Priority']) {
                if (entry['Priority'] === 'High') {
                    return true;
                }
            }
            return false;
        },
        isOverdue: function(entry) {
            var startDate, currentDate, seconds, mins, days;
            if (entry['StartDate']) {
                startDate = convert.toDateFromString(entry['StartDate']);
                currentDate = new Date();
                seconds = Math.round((currentDate - startDate) / 1000);
                mins = seconds / 60;
                if (mins >= 1) {
                    return true;
                }
            }
            return false;
        },
        isRecurring: function(entry) {
            if (entry['RecurrenceState']) {
                if (entry['RecurrenceState'] === 'rstOccurrence') {
                    return true;
                }
            }
            return false;
        },
        hasAlarm: function(entry) {
            if (entry['Alarm'] === true) {
                return true;
            }
            return false;
        },
        getItemIconClass: function(entry) {
            var type = entry && entry.Type;
            return this._getItemIconClass(type);
        },
        _getItemIconClass: function(type) {
            var cls = this.activityIndicatorIconByType[type];
            if (cls) {
                cls = cls + ' fa-2x';
            }

            return cls;
        },
        createActionLayout: function() {
           return this.actions || (this.actions = [{
               id: 'complete',
               cls: 'fa fa-check-square fa-2x',
               label: this.completeActivityText,
               enabled: function(action, selection) {
                   var recur, entry = selection && selection.data;
                   if (!entry) {
                       return false;
                   }
                   recur = false;
                   if (entry['RecurrenceState'] === 'rstOccurrence') {
                       recur = true;
                   }

                   return entry['Leader']['$key'] === App.context['user']['$key'] && !recur;
               },
               fn: (function(action, selection) {
                   var entry;

                   entry = selection && selection.data && selection.data;

                   entry['CompletedDate'] = new Date();
                   entry['Result'] = 'Complete';

                   environment.refreshActivityLists();
                   this.completeActivity(entry);

               }).bindDelegate(this)
           }, {
               id: 'call',
               cls: 'fa fa-phone-square fa-2x',
               label: this.callText,
               enabled: function(action, selection) {
                   var entry;
                   entry = selection && selection.data;
                   return entry && entry.PhoneNumber;
               },
               fn: function(action, selection) {
                   var entry, phone;
                   entry = selection && selection.data;
                   phone = entry && entry.PhoneNumber;
                   if (phone) {
                       this.recordCallToHistory(function() {
                           App.initiateCall(phone);
                       }.bindDelegate(this), entry);
                   }
               }.bindDelegate(this)
           }, {
               id: 'addAttachment',
               cls: 'fa fa-paperclip fa-2x',
               label: this.addAttachmentActionText,
               fn: action.addAttachment.bindDelegate(this)
           }]
           );
        },
        recordCallToHistory: function(complete, entry) {
           var tempEntry = {
               '$name': 'History',
               'Type': 'atPhoneCall',
               'ContactName': entry['ContactName'],
               'ContactId': entry['ContactId'],
               'AccountName': entry['AccountName'],
               'AccountId': entry['AccountId'],
               'Description': string.substitute("${0} ${1}", [this.calledText, (entry['ContactName'] || '')]),
               'UserId': App.context && App.context.user['$key'],
               'UserName': App.context && App.context.user['UserName'],
               'Duration': 15,
               'CompletedDate': (new Date())
           };

           this.navigateToHistoryInsert('atPhoneCall', tempEntry, complete);
        },
        navigateToHistoryInsert: function(type, entry, complete) {
           var view = App.getView(this.historyEditView);
           if (view) {
               environment.refreshActivityLists();
               view.show({
                   title: this.activityTypeText[type],
                   template: {},
                   entry: entry,
                   insert: true
               }, {
                   complete: complete
               });
           }
        },
        completeActivity: function(entry) {
           var completeActivity, request, completeActivityEntry;

           completeActivityEntry = {
               "$name": "ActivityComplete",
               "request": {
                   "entity": { '$key': entry['$key'] },
                   "ActivityId": entry['$key'],
                   "userId": entry['Leader']['$key'],
                   "result": entry['Result'],
                   "completeDate": entry['CompletedDate']
               }
           };

           request = new Sage.SData.Client.SDataServiceOperationRequest(this.getService())
               .setResourceKind('activities')
               .setContractName('system')
               .setOperationName('Complete');

           request.execute(completeActivityEntry, {
               success: function() {
                   connect.publish('/app/refresh', [{
                       resourceKind: 'history'
                   }]);

                   this.clear();
                   this.refresh();
               },
               failure: this.onRequestFailure,
               scope: this
           });
        },
        onRequestFailure: function(response, o) {
           ErrorManager.addError(response, o, {}, 'failure');
        }
    });
});

<commit_msg>Added a overdue icon. #MBL-10425<commit_after>/*
 * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
 */

/**
 * @class Mobile.SalesLogix.Views.Activity.List
 *
 * @extends Sage.Platform.Mobile.List
 * @mixins Mobile.SalesLogix.Views._RightDrawerListMixin
 * @mixins Mobile.SalesLogix.Views._CardLayoutListMixin
 *
 * @requires Sage.Platform.Mobile.List
 * @requires Sage.Platform.Mobile.Utility
 * @requires Sage.Platform.Mobile.Convert
 * @requires Sage.Platform.Mobile.ErrorManager
 * @requires Mobile.SalesLogix.Action
 * @requires Mobile.SalesLogix.Environment
 * @requires Mobile.SalesLogix.Format
 * @requires Mobile.SalesLogix.Views._CardLayoutListMixin
 * @requires Mobile.SalesLogix.Views._RightDrawerListMixin
 *
 */
define('Mobile/SalesLogix/Views/Activity/List', [
    'dojo/_base/declare',
    'dojo/_base/connect',
    'dojo/string',
    'dojo/query',
    'dojo/dom-class',
    'Mobile/SalesLogix/Views/_RightDrawerListMixin',
    'Sage/Platform/Mobile/List',
    'Mobile/SalesLogix/Views/_CardLayoutListMixin',
    'Mobile/SalesLogix/Format',
    'Sage/Platform/Mobile/Utility',
    'Sage/Platform/Mobile/Convert',
    'Mobile/SalesLogix/Action',
    'Mobile/SalesLogix/Environment',
    'Sage/Platform/Mobile/ErrorManager',
    'moment'
], function(
    declare,
    connect,
    string,
    query,
    domClass,
    _RightDrawerListMixin,
    List,
    _CardLayoutListMixin,
    format,
    Utility,
    convert,
    action,
    environment,
    ErrorManager,
    moment
) {

    return declare('Mobile.SalesLogix.Views.Activity.List', [List, _RightDrawerListMixin, _CardLayoutListMixin], {
        // Localization
        allDayText: 'All-Day',
        completeActivityText: 'Complete',
        callText: 'Call',
        calledText: 'Called',
        addAttachmentActionText: 'Add Attachment',
        overdueText: 'overdue',
        alarmText: 'alarm',
        touchedText: 'touched',
        importantText: 'important',
        recurringText: 'recurring',

        //Card View
        itemIcon: 'content/images/icons/man_1.png',

        //Templates
        //Card View
        itemRowContainerTemplate: new Simplate([
            '
',
               '{%! $$.itemRowContentTemplate %}',
            '
'
        ]),
        activityTimeTemplate: new Simplate([
            '{%: Mobile.SalesLogix.Format.relativeDate($.StartDate, Sage.Platform.Mobile.Convert.toBoolean($.Timeless)) %}'
        ]),
        itemTemplate: new Simplate([
            '
',
                '{%: $.Description %}',
            '
',
            '
',
                '{%! $$.activityTimeTemplate %}',
            '
',
            '
{%! $$.nameTemplate %}
'
        ]),
        nameTemplate: new Simplate([
            '{% if ($.ContactName) { %}',
            '{%: $.ContactName %} | {%: $.AccountName %}',
            '{% } else if ($.AccountName) { %}',
            '{%: $.AccountName %}',
            '{% } else { %}',
            '{%: $.LeadName %}',
            '{% } %}'
        ]),
        activityIndicatorIconByType: {
            'atToDo': 'fa fa-list-ul',
            'atPhoneCall': 'fa fa-phone',
            'atAppointment': 'fa fa-users',
            'atLiterature': 'fa fa-book',
            'atPersonal': 'fa fa-check-square-o',
            'atQuestion': 'fa fa-question-circle',
            'atNote': 'fa fa-file-text-o',
            'atEMail': 'fa fa-envelope'
        },
        activityTypeText: {
            'atToDo': 'To-Do',
            'atPhoneCall': 'Phone Call',
            'atAppointment': 'Meeting',
            'atLiterature': 'Lit Request',
            'atPersonal': 'Personal',
            'atQuestion': 'Question',
            'atNote': 'Note',
            'atEMail': 'Email'
        },
        //Localization
        titleText: 'Activities',

        //View Properties
        id: 'activity_list',
        security: null, //'Entities/Activity/View',
        iconClass: 'fa fa-check-square-o fa-lg',
        detailView: 'activity_detail',
        insertView: 'activity_types_list',
        historyEditView: 'history_edit',
        enableActions: true,
        queryOrderBy: 'StartDate desc',
        querySelect: [
            'Description',
            'StartDate',
            'Type',
            'AccountId',
            'AccountName',
            'ContactId',
            'ContactName',
            'PhoneNumber',
            'LeadId',
            'LeadName',
            'TicketId',
            'OpportunityId',
            'Leader',
            'UserId',
            'Timeless',
            'Alarm',
            'Priority',
            'ModifyDate',
            'RecurrenceState',
            'Recurring'
        ],
        queryInclude: [
            '$descriptors'
        ],
        resourceKind: 'activities',
        contractName: 'system',
        pageSize: 105,

        hashTagQueries: {
            'alarm': 'Alarm eq true',
            'recurring': 'Recurring eq true',
            'timeless': 'Timeless eq true',
            'yesterday': function() {
                var now, yesterdayStart, yesterdayEnd, query;

                now = moment();

                yesterdayStart = now.clone().subtract(1, 'days').startOf('day');
                yesterdayEnd = yesterdayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(yesterdayStart.toDate()),
                        convert.toIsoStringFromDate(yesterdayEnd.toDate()),
                        yesterdayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        yesterdayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'today': function() {
                var now, todayStart, todayEnd, query;

                now = moment();

                todayStart = now.clone().startOf('day');
                todayEnd = todayStart.clone().endOf('day');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(todayStart.toDate()),
                        convert.toIsoStringFromDate(todayEnd.toDate()),
                        todayStart.format('YYYY-MM-DDT00:00:00[Z]'),
                        todayEnd.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            },
            'this-week': function() {
                var now, weekStartDate, weekEndDate, query;

                now = moment();

                weekStartDate = now.clone().startOf('week');
                weekEndDate = weekStartDate.clone().endOf('week');

                query = string.substitute(
                        '((Timeless eq false and StartDate between @${0}@ and @${1}@) or (Timeless eq true and StartDate between @${2}@ and @${3}@))',
                        [
                        convert.toIsoStringFromDate(weekStartDate.toDate()),
                        convert.toIsoStringFromDate(weekEndDate.toDate()),
                        weekStartDate.format('YYYY-MM-DDT00:00:00[Z]'),
                        weekEndDate.format('YYYY-MM-DDT23:59:59[Z]')
                        ]
                );
                return query;
            }
        },
        hashTagQueriesText: {
            'alarm': 'alarm',
            'recurring': 'recurring',
            'timeless': 'timeless',
            'today': 'today',
            'this-week': 'this-week',
            'yesterday': 'yesterday'
        },
        defaultSearchTerm: function() {
            if (App.enableHashTags) {
                return '#' + this.hashTagQueriesText['this-week'];
            }

            return '';
        },
        formatSearchQuery: function(searchQuery) {
            return string.substitute('upper(Description) like "%${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
        },
        formatDateTime: function(dateTime) {
            return 'StartTime';
        },
        getItemActionKey: function(entry) {
            return entry.$key;
        },
        getItemDescriptor: function(entry) {
            return entry.$descriptor;
        },
        createIndicatorLayout: function() {
            return this.itemIndicators || (this.itemIndicators = [{
                id: 'alarm',
                cls: 'fa fa-bell-o fa-lg',
                label: this.alarmText,
                onApply: function(entry, parent) {
                    this.isEnabled = parent.hasAlarm(entry);
                }
                }, {
                    id: 'touched',
                    cls: 'fa fa-hand-o-up fa-lg',
                    label: this.touchedText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.hasBeenTouched(entry);
                    }
                }, {
                    id: 'important',
                    cls: 'fa fa-exclamation fa-lg',
                    label: this.importantText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isImportant(entry);
                    }
                },  {
                    id: 'recurring',
                    cls: 'fa fa-refresh fa-lg',
                    label: this.recurringText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isRecurring(entry, this);
                    }
                }, {
                    id: 'overdue',
                    cls: 'fa fa-exclamation-circle fa-lg',
                    label: this.overdueText,
                    onApply: function(entry, parent) {
                        this.isEnabled = parent.isOverdue(entry);
                    }
                }
            ]);
        },
        hasBeenTouched: function(entry) {
            var modifiedDate, currentDate, weekAgo;
            if (entry['ModifyDate']) {
                modifiedDate = moment(convert.toDateFromString(entry['ModifyDate']));
                currentDate = moment().endOf('day');
                weekAgo = moment().subtract(1, 'weeks');

                return modifiedDate.isAfter(weekAgo) &&
                    modifiedDate.isBefore(currentDate);
            }
            return false;
        },
        isImportant: function(entry) {
            if (entry['Priority']) {
                if (entry['Priority'] === 'High') {
                    return true;
                }
            }
            return false;
        },
        isOverdue: function(entry) {
            var startDate, currentDate, seconds, mins, days;
            if (entry['StartDate']) {
                startDate = convert.toDateFromString(entry['StartDate']);
                currentDate = new Date();
                seconds = Math.round((currentDate - startDate) / 1000);
                mins = seconds / 60;
                if (mins >= 1) {
                    return true;
                }
            }
            return false;
        },
        isRecurring: function(entry) {
            if (entry['RecurrenceState']) {
                if (entry['RecurrenceState'] === 'rstOccurrence') {
                    return true;
                }
            }
            return false;
        },
        hasAlarm: function(entry) {
            if (entry['Alarm'] === true) {
                return true;
            }
            return false;
        },
        getItemIconClass: function(entry) {
            var type = entry && entry.Type;
            return this._getItemIconClass(type);
        },
        _getItemIconClass: function(type) {
            var cls = this.activityIndicatorIconByType[type];
            if (cls) {
                cls = cls + ' fa-2x';
            }

            return cls;
        },
        createActionLayout: function() {
           return this.actions || (this.actions = [{
               id: 'complete',
               cls: 'fa fa-check-square fa-2x',
               label: this.completeActivityText,
               enabled: function(action, selection) {
                   var recur, entry = selection && selection.data;
                   if (!entry) {
                       return false;
                   }
                   recur = false;
                   if (entry['RecurrenceState'] === 'rstOccurrence') {
                       recur = true;
                   }

                   return entry['Leader']['$key'] === App.context['user']['$key'] && !recur;
               },
               fn: (function(action, selection) {
                   var entry;

                   entry = selection && selection.data && selection.data;

                   entry['CompletedDate'] = new Date();
                   entry['Result'] = 'Complete';

                   environment.refreshActivityLists();
                   this.completeActivity(entry);

               }).bindDelegate(this)
           }, {
               id: 'call',
               cls: 'fa fa-phone-square fa-2x',
               label: this.callText,
               enabled: function(action, selection) {
                   var entry;
                   entry = selection && selection.data;
                   return entry && entry.PhoneNumber;
               },
               fn: function(action, selection) {
                   var entry, phone;
                   entry = selection && selection.data;
                   phone = entry && entry.PhoneNumber;
                   if (phone) {
                       this.recordCallToHistory(function() {
                           App.initiateCall(phone);
                       }.bindDelegate(this), entry);
                   }
               }.bindDelegate(this)
           }, {
               id: 'addAttachment',
               cls: 'fa fa-paperclip fa-2x',
               label: this.addAttachmentActionText,
               fn: action.addAttachment.bindDelegate(this)
           }]
           );
        },
        recordCallToHistory: function(complete, entry) {
           var tempEntry = {
               '$name': 'History',
               'Type': 'atPhoneCall',
               'ContactName': entry['ContactName'],
               'ContactId': entry['ContactId'],
               'AccountName': entry['AccountName'],
               'AccountId': entry['AccountId'],
               'Description': string.substitute("${0} ${1}", [this.calledText, (entry['ContactName'] || '')]),
               'UserId': App.context && App.context.user['$key'],
               'UserName': App.context && App.context.user['UserName'],
               'Duration': 15,
               'CompletedDate': (new Date())
           };

           this.navigateToHistoryInsert('atPhoneCall', tempEntry, complete);
        },
        navigateToHistoryInsert: function(type, entry, complete) {
           var view = App.getView(this.historyEditView);
           if (view) {
               environment.refreshActivityLists();
               view.show({
                   title: this.activityTypeText[type],
                   template: {},
                   entry: entry,
                   insert: true
               }, {
                   complete: complete
               });
           }
        },
        completeActivity: function(entry) {
           var completeActivity, request, completeActivityEntry;

           completeActivityEntry = {
               "$name": "ActivityComplete",
               "request": {
                   "entity": { '$key': entry['$key'] },
                   "ActivityId": entry['$key'],
                   "userId": entry['Leader']['$key'],
                   "result": entry['Result'],
                   "completeDate": entry['CompletedDate']
               }
           };

           request = new Sage.SData.Client.SDataServiceOperationRequest(this.getService())
               .setResourceKind('activities')
               .setContractName('system')
               .setOperationName('Complete');

           request.execute(completeActivityEntry, {
               success: function() {
                   connect.publish('/app/refresh', [{
                       resourceKind: 'history'
                   }]);

                   this.clear();
                   this.refresh();
               },
               failure: this.onRequestFailure,
               scope: this
           });
        },
        onRequestFailure: function(response, o) {
           ErrorManager.addError(response, o, {}, 'failure');
        }
    });
});

<|endoftext|>


<commit_before>import 'script!jquery/dist/jquery';
import angular from 'angular';
import {products} from './products.js';

describe('the products page', () => {
  let $scope;
  let $location;
  let $state;

  let element;
  let $ = window.$;

  let buildTemplate = () => {
    return angular.element('<products></products>');
  };

  beforeEach(window.module('ui.router'));
  beforeEach(window.module(products.name));

  beforeEach(window.inject((
  $rootScope, $compile, _$state_, _$location_) => {
    $scope = $rootScope.$new();
    $state = _$state_;
    $location = _$location_;

    element = $compile(buildTemplate())($scope);
    $scope.$digest();
  }));

  it('/#products in the url', () => {
    $location.path('/products');
    $scope.$apply();

    ($state.current.url).should.equal('/products');
    ($state.current.name).should.equal('products');
  });

});
<commit_msg>purge lint violations in products.spec.js<commit_after>import 'script!jquery/dist/jquery';
import {products} from './products.js';

describe('the products page', () => {
  let $scope;
  let $location;
  let $state;

  beforeEach(window.module('ui.router'));
  beforeEach(window.module(products.name));

  beforeEach(window.inject(($rootScope, _$state_, _$location_) => {
    $scope = $rootScope.$new();
    $state = _$state_;
    $location = _$location_;

    $scope.$digest();
  }));

  it('/#products in the url', () => {
    $location.path('/products');
    $scope.$apply();

    ($state.current.url).should.equal('/products');
    ($state.current.name).should.equal('products');
  });
});
<|endoftext|>


<commit_before>(function() {
  var extend = function(out) {
    out = out || {};
    for (var i = 1; i < arguments.length; i++) {
    if (!arguments[i])
      continue;
      for (var key in arguments[i]) {
        if (arguments[i].hasOwnProperty(key))
          out[key] = arguments[i][key];
      }
    }
    return out;
  };

  var map = function(arr, fn) {
    var results = [];
    for (var i = 0; i < arr.length; i++)
      results.push(fn(arr[i], i));
    return results;
  }

  window.INSTALL_RRSSB = {
    buttons: [],
    buildButtons: function() {
      var options = this.options
      return map(this.buttons, function(buttonTemplate) {
        return buttonTemplate(options);
      }).join('');
    },
    shareUri: function() {
      if (this.options.advancedOptions.keepUrlParameters) {
        return window.location.href;
      } else {
        return window.location.protocol + '//' + window.location.hostname + window.location.pathname;
      }
    },
    processOptions: function() {
      var shareUri = this.shareUri();
      return extend({}, this.options, {
        shareUri: shareUri,
        uriEncodedShareUri: encodeURIComponent(shareUri)
      });
    },
    register: function(name, template) {
      this.buttons.push(template);
    },
    init: function(element, options) {
      this.options = options;
      if (!element) {
        return;
      }
      options = this.processOptions(options);
      element.innerHTML = '
' + this.buildButtons() + '
';
    }
  }
}).call(this);
<commit_msg>minor fix<commit_after>(function() {
  var extend = function(out) {
    out = out || {};
    for (var i = 1; i < arguments.length; i++) {
    if (!arguments[i])
      continue;
      for (var key in arguments[i]) {
        if (arguments[i].hasOwnProperty(key))
          out[key] = arguments[i][key];
      }
    }
    return out;
  };

  var map = function(arr, fn) {
    var results = [];
    for (var i = 0; i < arr.length; i++)
      results.push(fn(arr[i], i));
    return results;
  }

  window.INSTALL_RRSSB = {
    buttons: [],
    buildButtons: function() {
      var options = this.options
      return map(this.buttons, function(buttonTemplate) {
        return buttonTemplate(options);
      }).join('');
    },
    shareUri: function() {
      if (this.options.advancedOptions &&
          this.options.advancedOptions.keepUrlParameters) {
        return window.location.href;
      } else {
        return window.location.protocol + '//' + window.location.hostname + window.location.pathname;
      }
    },
    processOptions: function() {
      var shareUri = this.shareUri();
      return extend({}, this.options, {
        shareUri: shareUri,
        uriEncodedShareUri: encodeURIComponent(shareUri)
      });
    },
    register: function(name, template) {
      this.buttons.push(template);
    },
    init: function(element, options) {
      this.options = options;
      if (!element) {
        return;
      }
      options = this.processOptions(options);
      element.innerHTML = '
' + this.buildButtons() + '
';
    }
  }
}).call(this);
<|endoftext|>


<commit_before>var _allTags;
var _currentRepo;
var _defaultRepo;
var _fileHistory = [];
var _hfmEnabled = false;
var _hfmTimeout;
var _nextFile;
var _siteTitle;

$(document).ready(function() {
    var hash = window.location.hash.substring(2);
    const mobileView = window.matchMedia( "(max-width: 480px)" );

    if(!mobileView.matches) {
        ToggleSidebar();
    }

    ClickEvents();
    RepositorySelectEvent();
    SidebarToggleEvent();

    ResizeTagsBox();

    SetupSite();
});

window.addEventListener('resize', function(event){
    ResizeTagsBox();
});

window.onpopstate = function (event) {
    var currentPath = document.location.pathname.split('/');

    if(currentPath.length === 2) {
        if(currentPath[1]) {
            // URL: /{repository}
            _currentRepo = currentPath[1];
            $("#repository-selector").val(_currentRepo);
            GetRandomFile();
        } else {
            // URL: /
            _currentRepo = _defaultRepo;
            $("#repository-selector").val(_currentRepo);
            GetRandomFile();
        }
    } else if(currentPath.length === 3) {
        // URL: /{repository}/{fileId}
        _currentRepo = currentPath[1];
        $("#repository-selector").val(_currentRepo);
        GetFile(currentPath[2]);
        PreloadFile(true);
    }
}

function ClickEvents() {
    $("#about-button").click(function(e) {
        e.preventDefault();
        ToggleHfm();
        TogglePanel("about");
    });

    $("#about-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("about");
    });

    $("#apps-button").click(function(e) {
        e.preventDefault(0);
        ToggleHfm();
        TogglePanel("apps");
    });

    $("#apps-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("apps");
    });

    $("#backward-button").click(function(e) {
        e.preventDefault();

        ToggleHfm();

        _fileHistory.pop();

        var lastItem = _fileHistory.pop();
        var lastPath = lastItem.split('/');

        $("#repository-selector").val(lastPath[1]);
        _currentRepo = lastPath[1];
        GetFile(lastPath[2]);
        PreloadFile(false);
    });

    $("#comment-button").click(function(e) {
        e.preventDefault(0);
        ToggleHfm();
        LoadComments();
        TogglePanel("comment");
    });

    $("#comment-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("comment");
    });

    $("#error-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("error");
    });

    $("#hfm-button").click(function(e) {
        e.preventDefault();

        if(_hfmEnabled) {
            ToggleHfm();
        } else {
            TogglePanel("hfm");
        }
    });

    $("#hfm-panel-close").click(function(e) {
        e.preventDefault();
        TogglePanel("hfm");
    });

    $("#random-button").click(function(e) {
        e.preventDefault();
        ToggleHfm();
        GetRandomFile();
    });

    $("#random-mini-button").click(function(e) {
        e.preventDefault();
        ToggleHfm();
        GetRandomFile();
    });

    $("#start-hfm-button").on("click", function() {
        var int = $("#hfm-interval-input").val();
        ToggleHfm(int);
        TogglePanel("hfm");
    });

    $("#upload-button").click(function(e) {
        e.preventDefault();
        TogglePanel("upload");
    });

    $("#upload-panel-close").click(function(e) {
        e.preventDefault();
        TogglePanel("upload");
    });

    $("#view").click(function() {
        ToggleHfm();
        GetRandomFile();
    });

    $("#upload-submit").click(function() {
        Upload_UploadFile();
    });

    $("#upload-tag-add").click(function() {
        Upload_AddTag();
    });
}

function Upload_AddTag() {
    $("#upload-tag-collection-placeholder").css("display", "none");
    if($("#upload-tag-custom").val()) {
        var tag = $("#upload-tag-custom").val().replace(/ /g, "-")
        if(!$("#upload-tag-selected-" + tag).length) {
            $("#upload-tag-collection").append("" + tag + " ×")
        }
    } else {
        var tag = $("#upload-tag-selector").val();
        if(!$("#upload-tag-selected-" + tag).length) {
            $("#upload-tag-collection").append("" + tag + " ×")
        }
    }

    $(".upload-tag-remove").click(function(e) {
        e.preventDefault();

        var tag = $(this).attr("id").replace("upload-tag-remove-", "");
        $("#upload-tag-selected-" + tag).remove();

        if(!$(".upload-tag-selected").length) {
            $("#upload-tag-collection-placeholder").css("display", "");
        }
    })
}

function Upload_UploadFile() {
    $("#upload-panel-close").css("display", "none");

    $.ajax({
        url: '/api/v2/files',
        type: 'POST',

        data: new FormData($('#upload-form')[0]),

        cache: false,
        contentType: false,
        processData: false,

        success: function(data)
        {
            console.log(data);
        }
    });
}

function GetFile(fileId) {
    $.ajax({
        url: '/api/v2/files/' + fileId,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            $("#direct-button").attr("href", data.location);
            $("#view").css("background-image", "url('" + data.location + "')");

            document.title = _siteTitle + ": " + data.file.originalFilename;
            history.pushState(null, null, '/' + _currentRepo + '/' + data.id);

            StoreHistory('/' + _currentRepo + '/' + data.id);
            TrackVisit(_siteTitle + ": " + data.file.originalFilename, '/' + _currentRepo + '/' + data.id);
        },
        error: function (data)
        {
            SetError("NotFound");
            TogglePanel("error");
        }
    });
};

function GetRandomFile() {
    if(_nextFile) {
        GetFile(_nextFile);
        PreloadFile(false);
    } else {
        $.ajax({
            url: '/api/v2/random/' + _currentRepo,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function (data)
            {
                GetFile(data.id);
                PreloadFile(false);
            },
            error: function (data)
            {
                SetError("Unknown");
                TogglePanel("error");
            }
        });
    }
}

function GetTags() {
    $.ajax({
        url: '/api/v2/tags',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            $.each(data, function(index) {
                $("#repository-selector").append("<option value='" + data[index].name + "'>" + data[index].name + " (" + data[index].fileCount + ")" + "</option>");
                $("#upload-tag-selector").append("<option value='" + data[index].name + "'>" + data[index].name + " (" + data[index].fileCount + ")" + "</option>");
            });

            _allTags = data;

            $("#repository-selector").val(_currentRepo);
        }
    });
}

function LoadComments() {
    var currentPath = document.location.pathname.split('/');
    $("#comment-frame").attr("src", "/frame/comment/" + currentPath[1] + '/' + currentPath[2]);
}

function PreloadFile(keepTrying) {
    $.ajax({
        url: '/api/v2/random/' + _currentRepo,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            if(data.location.endsWith(".png") ||
                data.location.endsWith(".jpg") ||
                data.location.endsWith(".gif")) {
                    $("#image-preload").attr("src", data.location);
                    _nextFile = data.id;
            } else {
                if(keepTrying) {
                    PreloadFile(true);
                } else {
                    _nextFile = "";
                }
            }
        },
        error: function (data)
        {
            SetError("Unknown");
            TogglePanel("error");
        }
    });
}

function RepositorySelectEvent() {
    $("#repository-selector").change(function() {
        _currentRepo = $("#repository-selector").val();
        _nextFile = "";
        GetRandomFile();
    });
}

function ResizeTagsBox() {
    $("#sidebar-tags-inner").css("height", "0");

    var requiredHeight = $("#sidebar-tags").height() + "px";

    $("#sidebar-tags-inner").css("height", requiredHeight);
};

function SetError(error) {
    if(error == "NotFound") {
        $("#error-title").html("Not Found");
        $("#error-message").html("This file could not be found. Sorry about that.")
    } else {
        $("#error-title").html("Oops");
        $("#error-message").html("Something has gone wrong. Try again.")
    }
}

function SetupSite() {
    $.ajax({
        url: '/api/v2/tags/default',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            _siteTitle = document.title;
            _defaultRepo = data.name;

            var currentPath = document.location.pathname.split('/');

            if(currentPath.length === 2) {
                if(currentPath[1]) {
                    // URL: /{repository}
                    _currentRepo = currentPath[1];
                    GetTags();
                    GetRandomFile();
                } else {
                    // URL: /
                    _currentRepo = _defaultRepo;
                    GetTags();
                    GetRandomFile();
                }
            } else if(currentPath.length === 3) {
                // URL: /{repository}/{fileId}
                _currentRepo = currentPath[1];
                GetTags();
                GetFile(currentPath[2]);
                PreloadFile(true);
            }
        },
        error: function (data)
        {
            SetError("Unknown");
            TogglePanel("error");
        }
    })
}

function SidebarToggleEvent() {
    $("#show-sidebar-button").click(function(e) {
        e.preventDefault(0);
        ToggleSidebar();
    })

    $("#hide-sidebar-button").click(function(e) {
        e.preventDefault(0);
        ToggleSidebar();
    });
};

function StoreHistory(file) {
    _fileHistory.push(file);

    if(_fileHistory.length === 1) {
        $(".backward-button-item").addClass("disabled");
    } else {
        $(".backward-button-item").removeClass("disabled");
    }

    // prunce history if there is 100 items, just so
    // we don't clutter up the user's memory
    if(_fileHistory.length === 101) {
        _fileHistory.shift();
    }
};

function ToggleHfm(interval) {
    if(interval) {
        if(_hfmEnabled) {
            $("#hfm-button .fa").css("color", "inherit");
            _hfmEnabled = false;
            clearInterval(_hfmTimeout);
        } else {
            $("#hfm-button .fa").css("color", "red");
            _hfmEnabled = true;
            _hfmTimeout = setInterval(function() {
                GetRandomFile();
            }, interval*1000);
        }
    } else {
        $("#hfm-button .fa").css("color", "inherit");
        _hfmEnabled = false;
        clearInterval(_hfmTimeout);
    }
}

function TogglePanel(name) {
    if($("#" + name + "-panel").css("display") === "block") {
        $("#panel-overlay").css("display", "");
        $("#" + name + "-panel").css("display", "");
    } else {
        $("#panel-overlay").css("display", "block");
        $("#" + name + "-panel").css("display", "block");
    }
}

function ToggleSidebar() {
    ResizeTagsBox();

    if($("#sidebar").hasClass("visible")) {
        $("#sidebar-mini").removeClass("hidden");
        $("#sidebar").removeClass("visible");
        $("#view").addClass("full");
    } else {
        $("#sidebar-mini").addClass("hidden");
        $("#sidebar").addClass("visible");
        $("#view").removeClass("full");
    }
};

function TrackVisit(pageTitle, pageUrl) {
    ga('set', {
        page: pageUrl,
        title: pageTitle
    });

    ga('send', 'pageview');
}
<commit_msg>Fix typo<commit_after>var _allTags;
var _currentRepo;
var _defaultRepo;
var _fileHistory = [];
var _hfmEnabled = false;
var _hfmTimeout;
var _nextFile;
var _siteTitle;

$(document).ready(function() {
    var hash = window.location.hash.substring(2);
    const mobileView = window.matchMedia( "(max-width: 480px)" );

    if(!mobileView.matches) {
        ToggleSidebar();
    }

    ClickEvents();
    RepositorySelectEvent();
    SidebarToggleEvent();

    ResizeTagsBox();

    SetupSite();
});

window.addEventListener('resize', function(event){
    ResizeTagsBox();
});

window.onpopstate = function (event) {
    var currentPath = document.location.pathname.split('/');

    if(currentPath.length === 2) {
        if(currentPath[1]) {
            // URL: /{repository}
            _currentRepo = currentPath[1];
            $("#repository-selector").val(_currentRepo);
            GetRandomFile();
        } else {
            // URL: /
            _currentRepo = _defaultRepo;
            $("#repository-selector").val(_currentRepo);
            GetRandomFile();
        }
    } else if(currentPath.length === 3) {
        // URL: /{repository}/{fileId}
        _currentRepo = currentPath[1];
        $("#repository-selector").val(_currentRepo);
        GetFile(currentPath[2]);
        PreloadFile(true);
    }
}

function ClickEvents() {
    $("#about-button").click(function(e) {
        e.preventDefault();
        ToggleHfm();
        TogglePanel("about");
    });

    $("#about-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("about");
    });

    $("#apps-button").click(function(e) {
        e.preventDefault(0);
        ToggleHfm();
        TogglePanel("apps");
    });

    $("#apps-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("apps");
    });

    $("#backward-button").click(function(e) {
        e.preventDefault();

        ToggleHfm();

        _fileHistory.pop();

        var lastItem = _fileHistory.pop();
        var lastPath = lastItem.split('/');

        $("#repository-selector").val(lastPath[1]);
        _currentRepo = lastPath[1];
        GetFile(lastPath[2]);
        PreloadFile(false);
    });

    $("#comment-button").click(function(e) {
        e.preventDefault(0);
        ToggleHfm();
        LoadComments();
        TogglePanel("comment");
    });

    $("#comment-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("comment");
    });

    $("#error-panel-close").click(function(e) {
        e.preventDefault(0);
        TogglePanel("error");
    });

    $("#hfm-button").click(function(e) {
        e.preventDefault();

        if(_hfmEnabled) {
            ToggleHfm();
        } else {
            TogglePanel("hfm");
        }
    });

    $("#hfm-panel-close").click(function(e) {
        e.preventDefault();
        TogglePanel("hfm");
    });

    $("#random-button").click(function(e) {
        e.preventDefault();
        ToggleHfm();
        GetRandomFile();
    });

    $("#random-mini-button").click(function(e) {
        e.preventDefault();
        ToggleHfm();
        GetRandomFile();
    });

    $("#start-hfm-button").on("click", function() {
        var int = $("#hfm-interval-input").val();
        ToggleHfm(int);
        TogglePanel("hfm");
    });

    $("#upload-button").click(function(e) {
        e.preventDefault();
        TogglePanel("upload");
    });

    $("#upload-panel-close").click(function(e) {
        e.preventDefault();
        TogglePanel("upload");
    });

    $("#view").click(function() {
        ToggleHfm();
        GetRandomFile();
    });

    $("#upload-submit").click(function() {
        Upload_UploadFile();
    });

    $("#upload-tag-add").click(function() {
        Upload_AddTag();
    });
}

function Upload_AddTag() {
    $("#upload-tag-collection-placeholder").css("display", "none");
    if($("#upload-tag-custom").val()) {
        var tag = $("#upload-tag-custom").val().replace(/ /g, "-")
        if(!$("#upload-tag-selected-" + tag).length) {
            $("#upload-tag-collection").append("" + tag + " ×")
        }
    } else {
        var tag = $("#upload-tag-selector").val();
        if(!$("#upload-tag-selected-" + tag).length) {
            $("#upload-tag-collection").append("" + tag + " ×")
        }
    }

    $(".upload-tag-remove").click(function(e) {
        e.preventDefault();

        var tag = $(this).attr("id").replace("upload-tag-remove-", "");
        $("#upload-tag-selected-" + tag).remove();

        if(!$(".upload-tag-selected").length) {
            $("#upload-tag-collection-placeholder").css("display", "");
        }
    })
}

function Upload_UploadFile() {
    $("#upload-panel-close").css("display", "none");

    $.ajax({
        url: '/api/v2/files',
        type: 'POST',

        data: new FormData($('#upload-form')[0]),

        cache: false,
        contentType: false,
        processData: false,

        success: function(data)
        {
            console.log(data);
        }
    });
}

function GetFile(fileId) {
    $.ajax({
        url: '/api/v2/files/' + fileId,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            $("#direct-button").attr("href", data.location);
            $("#view").css("background-image", "url('" + data.location + "')");

            document.title = _siteTitle + ": " + data.file.originalFilename;
            history.pushState(null, null, '/' + _currentRepo + '/' + data.id);

            StoreHistory('/' + _currentRepo + '/' + data.id);
            TrackVisit(_siteTitle + ": " + data.file.originalFilename, '/' + _currentRepo + '/' + data.id);
        },
        error: function (data)
        {
            SetError("NotFound");
            TogglePanel("error");
        }
    });
};

function GetRandomFile() {
    if(_nextFile) {
        GetFile(_nextFile);
        PreloadFile(false);
    } else {
        $.ajax({
            url: '/api/v2/random/' + _currentRepo,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: function (data)
            {
                GetFile(data.id);
                PreloadFile(false);
            },
            error: function (data)
            {
                SetError("Unknown");
                TogglePanel("error");
            }
        });
    }
}

function GetTags() {
    $.ajax({
        url: '/api/v2/tags',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            $.each(data, function(index) {
                $("#repository-selector").append("<option value='" + data[index].name + "'>" + data[index].name + " (" + data[index].fileCount + ")" + "</option>");
                $("#upload-tag-selector").append("<option value='" + data[index].name + "'>" + data[index].name + " (" + data[index].fileCount + ")" + "</option>");
            });

            _allTags = data;

            $("#repository-selector").val(_currentRepo);
        }
    });
}

function LoadComments() {
    var currentPath = document.location.pathname.split('/');
    $("#comment-frame").attr("src", "/frame/comment/" + currentPath[1] + '/' + currentPath[2]);
}

function PreloadFile(keepTrying) {
    $.ajax({
        url: '/api/v2/random/' + _currentRepo,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            if(data.location.endsWith(".png") ||
                data.location.endsWith(".jpg") ||
                data.location.endsWith(".gif")) {
                    $("#image-preload").attr("src", data.location);
                    _nextFile = data.id;
            } else {
                if(keepTrying) {
                    PreloadFile(true);
                } else {
                    _nextFile = "";
                }
            }
        },
        error: function (data)
        {
            SetError("Unknown");
            TogglePanel("error");
        }
    });
}

function RepositorySelectEvent() {
    $("#repository-selector").change(function() {
        _currentRepo = $("#repository-selector").val();
        _nextFile = "";
        GetRandomFile();
    });
}

function ResizeTagsBox() {
    $("#sidebar-tags-inner").css("height", "0");

    var requiredHeight = $("#sidebar-tags").height() + "px";

    $("#sidebar-tags-inner").css("height", requiredHeight);
};

function SetError(error) {
    if(error == "NotFound") {
        $("#error-title").html("Not Found");
        $("#error-message").html("This file could not be found. Sorry about that.")
    } else {
        $("#error-title").html("Oops");
        $("#error-message").html("Something has gone wrong. Try again.")
    }
}

function SetupSite() {
    $.ajax({
        url: '/api/v2/tags/default',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            _siteTitle = document.title;
            _defaultRepo = data.name;

            var currentPath = document.location.pathname.split('/');

            if(currentPath.length === 2) {
                if(currentPath[1]) {
                    // URL: /{repository}
                    _currentRepo = currentPath[1];
                    GetTags();
                    GetRandomFile();
                } else {
                    // URL: /
                    _currentRepo = _defaultRepo;
                    GetTags();
                    GetRandomFile();
                }
            } else if(currentPath.length === 3) {
                // URL: /{repository}/{fileId}
                _currentRepo = currentPath[1];
                GetTags();
                GetFile(currentPath[2]);
                PreloadFile(true);
            }
        },
        error: function (data)
        {
            SetError("Unknown");
            TogglePanel("error");
        }
    })
}

function SidebarToggleEvent() {
    $("#show-sidebar-button").click(function(e) {
        e.preventDefault(0);
        ToggleSidebar();
    })

    $("#hide-sidebar-button").click(function(e) {
        e.preventDefault(0);
        ToggleSidebar();
    });
};

function StoreHistory(file) {
    _fileHistory.push(file);

    if(_fileHistory.length === 1) {
        $(".backward-button-item").addClass("disabled");
    } else {
        $(".backward-button-item").removeClass("disabled");
    }

    // prune history if there is 100 items, just so
    // we don't clutter up the user's memory
    if(_fileHistory.length === 101) {
        _fileHistory.shift();
    }
};

function ToggleHfm(interval) {
    if(interval) {
        if(_hfmEnabled) {
            $("#hfm-button .fa").css("color", "inherit");
            _hfmEnabled = false;
            clearInterval(_hfmTimeout);
        } else {
            $("#hfm-button .fa").css("color", "red");
            _hfmEnabled = true;
            _hfmTimeout = setInterval(function() {
                GetRandomFile();
            }, interval*1000);
        }
    } else {
        $("#hfm-button .fa").css("color", "inherit");
        _hfmEnabled = false;
        clearInterval(_hfmTimeout);
    }
}

function TogglePanel(name) {
    if($("#" + name + "-panel").css("display") === "block") {
        $("#panel-overlay").css("display", "");
        $("#" + name + "-panel").css("display", "");
    } else {
        $("#panel-overlay").css("display", "block");
        $("#" + name + "-panel").css("display", "block");
    }
}

function ToggleSidebar() {
    ResizeTagsBox();

    if($("#sidebar").hasClass("visible")) {
        $("#sidebar-mini").removeClass("hidden");
        $("#sidebar").removeClass("visible");
        $("#view").addClass("full");
    } else {
        $("#sidebar-mini").addClass("hidden");
        $("#sidebar").addClass("visible");
        $("#view").removeClass("full");
    }
};

function TrackVisit(pageTitle, pageUrl) {
    ga('set', {
        page: pageUrl,
        title: pageTitle
    });

    ga('send', 'pageview');
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, 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 describe, it, expect*/

import fs from 'fs';
import path from 'path';

import * as docgen from '../main';
import { ERROR_MISSING_DEFINITION } from '../parse';

describe('main', () => {
  function test(source) {
    it('parses with default resolver/handlers', () => {
      const docs = docgen.parse(source);
      expect(docs).toEqual({
        displayName: 'ABC',
        description: 'Example component description',
        methods: [],
        props: {
          foo: {
            type: {
              name: 'bool',
            },
            defaultValue: {
              computed: false,
              value: 'true',
            },
            description: 'Example prop description',
            required: false,
          },
        },
      });
    });

    it('parses with custom handlers', () => {
      const docs = docgen.parse(source, null, [
        docgen.handlers.componentDocblockHandler,
      ]);
      expect(docs).toEqual({
        description: 'Example component description',
      });
    });
  }

  describe('React.createClass', () => {
    test(`
      var React = require("React");
      var PropTypes = React.PropTypes;

      var defaultProps = {
        foo: true,
      };
      var propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
       * Example component description
       */
      var Component = React.createClass({
        displayName: 'ABC',
        propTypes,
        getDefaultProps: function() {
          return defaultProps;
        }
      });
      module.exports = Component
    `);
  });

  describe('Class definition', () => {
    test(`
      const React = require("React");
      const PropTypes = React.PropTypes;

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
       * Example component description
       */
      export default class Component extends React.Component {
        static propTypes = propTypes;
        // ...
      }
      Component.defaultProps = defaultProps;
      Component.displayName = 'ABC';
    `);
  });

  describe('Stateless Component definition: ArrowFunctionExpression', () => {
    test(`
      import React, {PropTypes} from "React";

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
        * Example component description
        */
      let Component = props => <div />;
      Component.displayName = 'ABC';
      Component.defaultProps = defaultProps;
      Component.propTypes = propTypes;

      export default Component;
    `);
  });

  describe('Stateless Component definition: FunctionDeclaration', () => {
    test(`
      import React, {PropTypes} from "React";

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
      * Example component description
      */
      function Component (props) {
        return <div />;
      }

      Component.displayName = 'ABC';
      Component.defaultProps = defaultProps;
      Component.propTypes = propTypes;

      export default Component;
    `);
  });

  describe('Stateless Component definition: FunctionExpression', () => {
    test(`
      import React, {PropTypes} from "React";

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
      * Example component description
      */
      let Component = function(props) {
        return React.createElement('div', null);
      }

      Component.displayName = 'ABC';
      Component.defaultProps = defaultProps;
      Component.propTypes = propTypes;

      export default Component;
    `);
  });

  describe('Stateless Component definition', () => {
    it('is not so greedy', () => {
      const source = `
        import React, {PropTypes} from "React";

        /**
        * Example component description
        */
        let NotAComponent = function(props) {
          let HiddenComponent = () => React.createElement('div', null);

          return 7;
        }

        NotAComponent.displayName = 'ABC';
        NotAComponent.defaultProps = {
            foo: true
        };

        NotAComponent.propTypes = {
          /**
          * Example prop description
          */
          foo: PropTypes.bool
        };

        export default NotAComponent;
      `;

      expect(() => docgen.parse(source)).toThrowError(ERROR_MISSING_DEFINITION);
    });
  });

  describe('fixtures', () => {
    const fixturePath = path.join(__dirname, 'fixtures');
    const fileNames = fs.readdirSync(fixturePath);
    for (let i = 0; i < fileNames.length; i++) {
      const fileContent = fs.readFileSync(path.join(fixturePath, fileNames[i]));

      it(`processes component "${fileNames[i]}" without errors`, () => {
        expect(() => docgen.parse(fileContent)).not.toThrowError();
        expect(docgen.parse(fileContent)).toMatchSnapshot();
      });
    }
  });
});
<commit_msg>test: Only run parse once in fixture test<commit_after>/*
 *  Copyright (c) 2015, 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 describe, it, expect*/

import fs from 'fs';
import path from 'path';

import * as docgen from '../main';
import { ERROR_MISSING_DEFINITION } from '../parse';

describe('main', () => {
  function test(source) {
    it('parses with default resolver/handlers', () => {
      const docs = docgen.parse(source);
      expect(docs).toEqual({
        displayName: 'ABC',
        description: 'Example component description',
        methods: [],
        props: {
          foo: {
            type: {
              name: 'bool',
            },
            defaultValue: {
              computed: false,
              value: 'true',
            },
            description: 'Example prop description',
            required: false,
          },
        },
      });
    });

    it('parses with custom handlers', () => {
      const docs = docgen.parse(source, null, [
        docgen.handlers.componentDocblockHandler,
      ]);
      expect(docs).toEqual({
        description: 'Example component description',
      });
    });
  }

  describe('React.createClass', () => {
    test(`
      var React = require("React");
      var PropTypes = React.PropTypes;

      var defaultProps = {
        foo: true,
      };
      var propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
       * Example component description
       */
      var Component = React.createClass({
        displayName: 'ABC',
        propTypes,
        getDefaultProps: function() {
          return defaultProps;
        }
      });
      module.exports = Component
    `);
  });

  describe('Class definition', () => {
    test(`
      const React = require("React");
      const PropTypes = React.PropTypes;

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
       * Example component description
       */
      export default class Component extends React.Component {
        static propTypes = propTypes;
        // ...
      }
      Component.defaultProps = defaultProps;
      Component.displayName = 'ABC';
    `);
  });

  describe('Stateless Component definition: ArrowFunctionExpression', () => {
    test(`
      import React, {PropTypes} from "React";

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
        * Example component description
        */
      let Component = props => <div />;
      Component.displayName = 'ABC';
      Component.defaultProps = defaultProps;
      Component.propTypes = propTypes;

      export default Component;
    `);
  });

  describe('Stateless Component definition: FunctionDeclaration', () => {
    test(`
      import React, {PropTypes} from "React";

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
      * Example component description
      */
      function Component (props) {
        return <div />;
      }

      Component.displayName = 'ABC';
      Component.defaultProps = defaultProps;
      Component.propTypes = propTypes;

      export default Component;
    `);
  });

  describe('Stateless Component definition: FunctionExpression', () => {
    test(`
      import React, {PropTypes} from "React";

      const defaultProps = {
        foo: true,
      };
      const propTypes =  {
        /**
         * Example prop description
         */
        foo: PropTypes.bool
      };

      /**
      * Example component description
      */
      let Component = function(props) {
        return React.createElement('div', null);
      }

      Component.displayName = 'ABC';
      Component.defaultProps = defaultProps;
      Component.propTypes = propTypes;

      export default Component;
    `);
  });

  describe('Stateless Component definition', () => {
    it('is not so greedy', () => {
      const source = `
        import React, {PropTypes} from "React";

        /**
        * Example component description
        */
        let NotAComponent = function(props) {
          let HiddenComponent = () => React.createElement('div', null);

          return 7;
        }

        NotAComponent.displayName = 'ABC';
        NotAComponent.defaultProps = {
            foo: true
        };

        NotAComponent.propTypes = {
          /**
          * Example prop description
          */
          foo: PropTypes.bool
        };

        export default NotAComponent;
      `;

      expect(() => docgen.parse(source)).toThrowError(ERROR_MISSING_DEFINITION);
    });
  });

  describe('fixtures', () => {
    const fixturePath = path.join(__dirname, 'fixtures');
    const fileNames = fs.readdirSync(fixturePath);
    for (let i = 0; i < fileNames.length; i++) {
      const fileContent = fs.readFileSync(path.join(fixturePath, fileNames[i]));

      it(`processes component "${fileNames[i]}" without errors`, () => {
        let result;
        expect(() => {
          result = docgen.parse(fileContent);
        }).not.toThrowError();
        expect(result).toMatchSnapshot();
      });
    }
  });
});
<|endoftext|>


<commit_before>const path = require('path')
const gatsbyWebpack = require('gatsby/dist/utils/webpack.config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
const directory = path.resolve(__dirname, '../')
const suppliedStage = 'develop'
const program = {
  directory,
}

module.exports = function customiseStorybookConfig(storybookBaseConfig) {
  console.log(storybookBaseConfig)

  return {
    ...storybookBaseConfig,
    module: {
      rules: [
        ...storybookBaseConfig.module.rules,
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
            'postcss-loader',
          ],
        },
      ],
    },
  }
}
<commit_msg>fix: remove console.log<commit_after>const path = require('path')
const gatsbyWebpack = require('gatsby/dist/utils/webpack.config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
const directory = path.resolve(__dirname, '../')
const suppliedStage = 'develop'
const program = {
  directory,
}

module.exports = function customiseStorybookConfig(storybookBaseConfig) {
  return {
    ...storybookBaseConfig,
    module: {
      rules: [
        ...storybookBaseConfig.module.rules,
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
            'postcss-loader',
          ],
        },
      ],
    },
  }
}
<|endoftext|>