Example #1
0
const show = (): Promise<boolean> => {
    const $body = bonzo(document.body);
    const $breakingNews = bonzo(qwery('.js-breaking-news-placeholder'));

    // if its the first time we've seen this alert, we wait 3 secs to show it
    // otherwise we show it immediately
    const alertDelay = knownAlertIDs.hasOwnProperty(alertToShow.id)
        ? 0
        : DEFAULT_DELAY;

    // $breakingNews is hidden, so this won't trigger layout etc
    $breakingNews.append(renderAlert(alertToShow));

    // copy of breaking news banner (with blank content) used inline at the
    // bottom of the body, so the bottom of the body can visibly scroll
    // past the pinned alert
    const $spectre = renderSpectre($breakingNews);

    // inject the alerts into DOM
    setTimeout(() => {
        fastdom.write(() => {
            if (alertDelay === 0) {
                $breakingNews.removeClass('breaking-news--fade-in');
            }
            $body.append($spectre);
            $breakingNews.removeClass('breaking-news--hidden');
            markAlertAsSeen(alertToShow.id);
        });
    }, alertDelay);

    return Promise.resolve(true);
};
Example #2
0
        it('fades from one image to the other', function (done) {
            var imageOne = bonzo(qwery('.test-image-1')),
                imageTwo = bonzo(qwery('.test-image-2'));

            expect(opacity(imageOne)).toBe(1);
            expect(opacity(imageTwo)).toBe(0);

            slideshowDOM.duration = 20;
            slideshowDOM.transition({
                node: imageOne
            }, {
                node: imageTwo
            })
            .then(function () {
                expect(opacity(imageOne)).toBe(0);
                expect(opacity(imageTwo)).toBe(1);

                // Check that an image that was set hidden can be showed again
                return slideshowDOM.transition({
                    node: imageTwo
                }, {
                    node: imageOne
                });
            })
            .then(function () {
                expect(opacity(imageOne)).toBe(1);
                expect(opacity(imageTwo)).toBe(0);
            })
            .then(done);
        });
Example #3
0
    prerender(): void {
        const testEl = this.getElem('test');
        const testLabel = this.getElem('test-label');
        const captionTest = this.getElem('caption-test');
        const captionRange = this.getElem('caption-range');

        if (testLabel) {
            bonzo(testLabel).prepend(this.config.test.id);
        }

        // Set the width and absolute position to match the audience size and offset.
        const audience = this.config.test.audience * 100;
        const audienceOffset = this.config.test.audienceOffset * 100;
        const audienceEnd = audience + audienceOffset;

        if (testEl) {
            testEl.style.width = `${audience.toString()}%`;
            testEl.style.left = `${audienceOffset.toString()}%`;
        }

        if (captionTest) {
            bonzo(captionTest).append(this.config.test.id);
        }

        if (captionRange) {
            bonzo(captionRange).append(`${audienceOffset}% to ${audienceEnd}%`);
        }
    }
Example #4
0
    findValidTimestamps().each(el => {
        let targetEl;
        const $el = bonzo(el);

        const // Epoch dates are more reliable, fallback to datetime for liveblog blocks
            timestamp =
                parseInt($el.attr('data-timestamp'), 10) ||
                $el.attr('datetime');

        const datetime = new Date(timestamp);

        const relativeDate = makeRelativeDate(datetime.getTime(), {
            // NOTE: if this is in a block (blog), assume we want added time on > 1 day old dates
            showTime: bonzo($el.parent()).hasClass('block-time'),
            format: $el.attr('data-relativeformat'),
            notAfter: opts.notAfter,
        });

        if (relativeDate) {
            // If we find .timestamp__text (facia), use that instead
            targetEl = $el[0].querySelector('.timestamp__text') || $el[0];
            if (!targetEl.getAttribute('title')) {
                targetEl.setAttribute('title', bonzo(targetEl).text());
            }
            targetEl.innerHTML = relativeDate;
        } else if (opts.notAfter) {
            $el.addClass('modern-hidden');
        }
    });
            , success: function (resp) {
                if (resp[id] != null) {
                    var resultsForId = resp[id];
                    var total = 0;


                    for (var result in resultsForId) {
                        if (resultsForId.hasOwnProperty(result)) {
                            total += resultsForId[result];
                        }
                    }

                    bonzo($('.total')).html(total + ' votes in total');

                    var userAnswerHtml = answer ? '<h3 class="pseudo-radio__header ">You voted for "' + answersObj[answer] + '"</h3>' : '';

                    var barHtml = '<span class="bar__outer"><span class="bar__inner js-bar__inner"></span></span>';

                    var barsHtml = '';
                    var percentages = [];
                    for (var key in answersObj) {
                        if (answersObj.hasOwnProperty(key)) {
                            var count = resultsForId[key];
                            if (count) {
                                var percentage = Math.round(count / total * 100);
                                percentages.push(percentage);
                            } else {
                                //if there are no results then default to 0
                                percentages.push(0);
                                percentage = 0;
                            }
                            barsHtml += '<span class="bar__wrap pseudo-radio__note"><span class="bar__label">' + answersObj[key] + '</span>' + barHtml + '<span class="bar__label--percentage">' + percentage + '%</span></span>';
                        }
                    }

                    bonzo($('.form-body')[0]).replaceWith(
                        '<div class="bar">' +
                        userAnswerHtml +
                        barsHtml +
                        '</div>'
                    );
                    raf(function () {
                        var $bars = $('.js-bar__inner');
                        // Animate bars to correct position
                        for (var i = 0; i < $bars.length; i++) {
                            $bars[i].style.transform = 'translateX(' + percentages[i] + '%)';
                        }
                    });

                } else {
                    //there will be up to 60 seconds latency before first results are published
                    bonzo($('.form-body')[0]).replaceWith(
                        '<div class="pseudo-radio__header q1">Thank you for voting, come back soon to see the results</div>'
                    );
                }
            }
Example #6
0
 constructor(container: Element) {
     this.$container = bonzo(container);
     this.$button = bonzo(
         bonzo.create(
             btnTmpl({
                 text: 'Hide',
                 dataLink: 'Show',
             })
         )
     );
     this.state = 'displayed';
 }
Example #7
0
Auth0Widget.prototype._show = function (signinOptions, widgetLoadedCallback, popupCallback) {
  if (typeof signinOptions === 'function') {
    widgetLoadedCallback = signinOptions;
    callback = widgetLoadedCallback;
    signinOptions = {};
  }

  var self = this;

  self._signinOptions = _.extend({popupCallback: popupCallback}, self._options, signinOptions);

  var extra = utils.extract(self._signinOptions,
                            [ 'state', 'access_token',
                              'scope', 'protocol', 'device',
                              'request_id', 'connection_scopes', 'nonce',
                              'offline_mode' ]);

  self._signinOptions.extraParameters = _.extend({}, extra, self._signinOptions.extraParameters);

  // widget container
  if (self._signinOptions.container) {
    self._signinOptions.theme = 'static';
    self._signinOptions.standalone = true;
    self._signinOptions.top = true;

    var specifiedContainer = document.getElementById(self._signinOptions.container);
    specifiedContainer.innerHTML = self._getEmbededTemplate(self._signinOptions);
    self._container = specifiedContainer;
  } else {

    var div = document.createElement('div');
    bonzo(div).addClass('a0-widget-container');
    div.innerHTML = mainTmpl({
      i18n:    this._dict,
      options: self._signinOptions,
      alt_spinner: !has_animations() ? (self._signinOptions.cdn + 'img/ajax-loader.gif') : null
    });
    document.body.appendChild(div);
    self._container = div;
  }

  if (!placeholderSupported) {
    this._$('.a0-overlay').addClass('a0-no-placeholder-support');
  }

  if (!self._signinOptions.container) {
    bonzo(document.body).addClass('a0-widget-open');
  }

  self._initialize(widgetLoadedCallback);
  return self;
};
Example #8
0
 var gather = function() {
     var ondemand = w.el('ondemand').attr('checked');
     return {
         name : bonzo(qwery('#name')).val(),
         repo_url : bonzo(qwery('#repo_url')).val(),
         branch : bonzo(qwery('#branch')).val(),
         build_instructions : v.map(qwery('.app-build_instruction'), function(bi) {
             return bonzo(bi).val();
         }),
         polling_strategy : (ondemand ? 'ondemand' : {
             time : parseInt(bonzo(qwery('#time')).val(), 10)
         })
     };
 };
Example #9
0
        it('generate a list of images', function (done) {
            var testDOM = bonzo.create([
                '<div class="TEST_CONTAINER_SLIDESHOW_INITIALIZE">',
                    '<img class="test-image-1" src="/base/javascripts/test/fixtures/slideshow/one.svg">',
                    '<img class="test-image-2 js-lazy-loaded-slideshow" data-srcset="/base/javascripts/test/fixtures/slideshow/two.svg">',
                    '<img class="test-image-3 js-lazy-loaded-slideshow" data-srcset="/base/javascripts/test/fixtures/slideshow/three.svg">',
                '</div>'
            ].join(''));

            var container = bonzo(testDOM).appendTo(document.body);
            slideshowDOM.init(container[0])
            .then(function (listOfImages) {
                expect(listOfImages.length).toBe(3);
                expect(listOfImages[0].node[0].tagName.toLowerCase()).toBe('img');
                expect(listOfImages[0].loaded).toBe(true);
                expect(listOfImages[1].node[0].tagName.toLowerCase()).toBe('img');
                expect(listOfImages[1].loaded).toBe(false);
                expect(listOfImages[2].node[0].tagName.toLowerCase()).toBe('img');
                expect(listOfImages[2].loaded).toBe(false);
            })
            .then(function () {
                container.remove();
                done();
            });
        });
Example #10
0
Auth0Lock.prototype.exhibit = function() {
  var options = this.options;

  // Create and set the header
  this.header = new HeaderView(this, this.query('.a0-header').get(0), options);

  // activate panel
  // XXX: (?) this I don't get... why remove and add?
  this.query('div.a0-panel').removeClass('a0-active');
  this.query('div.a0-overlay').addClass('a0-active');
  this.query('.a0-panel.a0-onestep').addClass('a0-active');

  if (!options.container) {
    bonzo(document.body).addClass('a0-lock-open');
  } else {
    this.query('.a0-active').removeClass('a0-overlay');
  }

  this.query('.a0-popup .a0-invalid').removeClass('a0-invalid');

  this.query('.a0-overlay')
    .toggleClass('a0-no-placeholder-support', !placeholderSupported);

  // buttons actions
  this.query('.a0-onestep a.a0-close').a0_on('click', bind(this.oncloseclick, this));

  // close popup with ESC key
  if (options.closable) {
    this.query('').a0_on('keyup', bind(this.onescpressed, this));
  }

  // after pre-setting classes and dom handlers
  // emit as shown
  this.emit('shown');
}
Example #11
0
        it('loads an image correctly', function (done) {
            var container = qwery('.TEST_CONTAINER_SLIDESHOW_LOADER'),
                eventCalled = jasmine.createSpy('eventCalled');

            mediator.on('ui:images:lazyLoaded', eventCalled);
            slideshowDOM.insert({
                node: bonzo(container[0].childNodes[0]),
                loaded: false
            })
            .then(function (img) {
                expect(img.loaded).toBe(true);
                expect(img.node[0].tagName.toLowerCase()).toBe('img');
                expect(opacity(img.node)).toBe(0);
                expect(eventCalled.calls.count()).toEqual(1);
                expect(eventCalled.calls.argsFor(0)[0]).toBe(img.node[0]);

                // Remove the image just to insert it again later
                return slideshowDOM.remove(img);
            })
            .then(function (img) {
                // Fake the transition by changing the opacity
                bonzo(img.node).css('opacity', '1');
                return slideshowDOM.insert(img);
            })
            .then(function (img) {
                expect(img.loaded).toBe(true);
                expect(img.node[0].tagName.toLowerCase()).toBe('img');
                expect(opacity(img.node)).toBe(0);
                // The image was already loaded, I don't expect other events
                expect(eventCalled.calls.count()).toEqual(1);
            })
            .then(done);
        });
Example #12
0
  function closeListenerTab(protocol, port) {
    var selector = '[data-protocol="' + protocol + '"][listener-port="' + port + '"]'
      , tabBar
      , child
      ;

    if ($('.js-listener-window'+selector).hasClass('css-active')) {
      serverCtrl.closeListener(protocol, port);
    }

    // if the tab closed is the one we were on go to the default tab
    if (!$('.js-listener-window'+selector).hasClass('css-hidden')) {
      displayTab(protocol, 'default');
    }
    $('.js-listener-tab'+selector).remove();
    $('.js-listener-window'+selector).remove();

    // if only the default tab is left then hide the tab bar again
    tabBar = qwery('.js-listener-tab-bar[data-protocol='+protocol+']');
    if (tabBar.length !== 1) {
      console.error('multiple tab bars for', protocol);
      return;
    }
    child = bonzo.firstChild(tabBar[0]);
    if (!child) {
      console.log(protocol, 'tab bar has no children');
      return;
    }
    if (!child.nextSibling) {
      bonzo(tabBar).addClass('css-hidden');
    }
  }
Example #13
0
Auth0Widget.prototype._hideSignIn = function (cb) {
  var self = this;

  this._$('div.a0-overlay').removeClass('a0-active');

  this._$().removeClass('a0-mode-signin');
  this._$().css('display', 'none');
  bonzo(document.body).removeClass('a0-widget-open');

  if (this._container && this._signinOptions.container) {
    // remove `#a0-widget`
    this._$().remove();
  } else if(this._container) {
    // remove `.a0-widget-container`
    this._$().parent('.a0-widget-container').remove();
  }

  this._currentPane = null;
  this._container = null;

  if (cb) cb();
  this.emit('closed');

  return self;
};
Example #14
0
Auth0Lock.prototype.insert = function() {
  if (this.$container) return this;

  var options = this.options;
  var cid = options.container;
  var locals = {
    options: options,
    alt_spinner: !has_animations() ?
      (this.$options.cdn + 'img/ajax-loader.gif') :
      null
  };

  // widget container
  if (cid) {
    this.$container = document.getElementById(cid);
    if (!this.$container) throw new Error('Not found element with \'id\' ' + cid);

    this.$container.innerHTML = this.render(template, locals);

  } else {
    this.$container = document.createElement('div');
    bonzo(this.$container).addClass('a0-lock-container');

    this.$container.innerHTML = this.render(template, locals);
    document.body.appendChild(this.$container);
  }

  return this;
};
Example #15
0
 bean.add(add, 'click', function() {
     var removes = qwery('.app-remove');
     var r = bonzo(add).before(t.build_instruction.render({
         instruction : ''
     }));
     augment.bindRemove(qwery('.app-remove', r.previous())[0]);
 });
Example #16
0
  function injectProtocolTab(protocol) {
    var opts = {}
      , newElement
      ;

    opts.protocol = protocol;
    opts.display  = protocol.toUpperCase();
    newElement = bonzo.create(protocolTabTemplate(opts));
    bonzo(newElement).removeClass('js-protocol-tab-template');
    $('.js-protocol-tab-bar').append(newElement);

    opts.portNum = 'default';
    newElement = bonzo.create(protocolWindowTemplate(opts));
    bonzo(newElement).removeClass('js-protocol-window-template');
    $('.container').append(newElement);
  }
Example #17
0
            expect(_.every(cells, function (cell) {
                var $cell = bonzo(cell),
                    x = $cell.attr('x'),
                    y = $cell.attr('y');

                return x > 0 && x < gridWidth && y > 0 && y < gridHeight;
            })).toBe(true);
Example #18
0
                            $.create(resp.html).each(html => {
                                const htmlContainer = document.querySelector(
                                    `[data-show-more-contains="${putsMore}"]`
                                );

                                if (htmlContainer) {
                                    replaceLocaleTimestamps(html);
                                    htmlContainer.appendChild(html);
                                }

                                const nurl = resp[newData];

                                if (nurl) {
                                    bonzo(el).attr('href', nurl);
                                } else {
                                    bonzo(el).remove();
                                }
                            });
 beforeEach(function () {
     $container = bonzo(bonzo.create(
         '<div>' +
             itemWithId('loldongs') +
             itemWithId('corgi') +
             itemWithId('geekpie') +
         '</div>'
     ));
 });
Example #20
0
                .then(resp => {
                    const comment = bonzo.create(resp.html);
                    const replies = qwery(
                        this.getClass('reply'),
                        comment
                    ).slice(this.options && this.options.showRepliesCount);

                    bonzo(qwery('.d-thread--responses', source)).append(
                        replies
                    );
                    bonzo(li).addClass('u-h');

                    this.emit('untruncate-thread');

                    if (shouldMakeTimestampsRelative()) {
                        this.relativeDates();
                    }
                })
Example #21
0
        beforeEach(function () {
            var testDOM = bonzo.create([
                '<div class="TEST_CONTAINER_SLIDESHOW_LOADER">',
                    '<img class="test-image-1" data-srcset="/base/javascripts/test/fixtures/slideshow/one.svg">',
                    '<img class="test-image-2" data-srcset="this_image_doesnt_exists.png">',
                '</div>'
            ].join(''));

            bonzo(testDOM).appendTo(document.body);
        });
Example #22
0
    function renderPollForm() {
        var pollOptionHtml = '';

        for (var key in answersObj) {
            if (answersObj.hasOwnProperty(key)) {
                pollOptionHtml += '<label class="label" for="' + key + '"> <input type="radio" class="pseudo-radio-input" name="option" id="' + key + '" value="' + key + '" data-link-name="poll-id : ' + id + ' : poll-option : ' + key + '" required="required"> <div class="pseudo-radio"> <div class="q1"></div>' + answersObj[key] + '</div> </label>';
            }
        }

        bonzo($('.form-field')[0]).html(pollOptionHtml);
    }
Example #23
0
        it('auto plays lazy loaded images', function (done) {
            var testDOM = bonzo.create([
                '<div class="TEST_CONTAINER_SLIDESHOW_PLAY_LAZY js-slideshow">',
                    '<img class="test-image-1 js-lazy-loaded-image" data-srcset="/base/javascripts/test/fixtures/slideshow/one.svg">',
                    '<img class="test-image-2 js-lazy-loaded-slideshow" data-srcset="/base/javascripts/test/fixtures/slideshow/two.svg">',
                    '<img class="test-image-3 js-lazy-loaded-slideshow" data-srcset="/base/javascripts/test/fixtures/slideshow/three.svg">',
                '</div>'
            ].join('')),
                container = bonzo(testDOM).appendTo(document.body),
                opacityOf = function (selector) {
                    return opacity(bonzo(qwery(selector)));
                },
                nextImage = function (img) {
                    return tick(slideshowState.interval).then(function () {
                        mediator.emit('ui:images:lazyLoaded', img);
                        return new Promise(function (resolve) {
                            originalSetTimeout(resolve, 100);
                        });
                    })
                    .then(function () {
                        return tick(slideshowDOM.loadTime);
                    })
                    .then(function () {
                        return tick(slideshowDOM.duration);
                    });
                };

            slideshowController.init();

            nextImage(qwery('.test-image-1', container[0])[0])
            .then(function () {
                expect(opacityOf('.test-image-1', container[0])).toBe(0);
                expect(opacityOf('.test-image-2', container[0])).toBe(1);

                return nextImage();
            })
            .then(function () {
                expect(opacityOf('.test-image-1', container[0])).toBe(0);
                expect(opacityOf('.test-image-2', container[0])).toBe(0);
                expect(opacityOf('.test-image-3', container[0])).toBe(1);

                return nextImage();
            })
            .then(function () {
                expect(opacityOf('.test-image-1', container[0])).toBe(1);
                expect(opacityOf('.test-image-2', container[0])).toBe(0);
                expect(opacityOf('.test-image-3', container[0])).toBe(0);
            })
            .then(function () {
                slideshowController.destroy();
                container.remove();
            })
            .then(done);
        });
Example #24
0
 beforeEach(function () {
     container = bonzo.create(
         '<section class="fc-container js-container--toggle" data-id="' + containerId + '">' +
         '<div class="fc-container__header js-container__header">' +
         '<h2>A container</h2>' +
         '</div>' +
         '<div class="ad-slot--paid-for-badge"></div>' +
         '</section>'
     )[0];
     $container = bonzo(container);
 });
Example #25
0
        _.forEach(thumbnails, (elem) => {
            const $elem = bonzo(elem);
            const savedState = persistence.loadGridState($elem.attr('data-crossword-id'));

            if (savedState) {
                ajax({
                    url: $elem.attr('src'),
                    type: 'xml',
                    method: 'get',
                    crossOrigin: true,
                    success (data) {
                        const cells = makeTextCells(savedState);
                        const svg = qwery('svg', data)[0];
                        bonzo(svg).append(cells);
                        fastdom.write(function () {
                            $elem.replaceWith(svg);
                        });
                    }
                });
            }
        });
Example #26
0
 var gather = function() {
     var ondemand = w.el('ondemand').attr('checked');
     return {
         id : w.el('id').val(),
         repo_url : w.el('repo_url').val(),
         branch : w.el('branch').val(),
         build_instructions : v.reject(v.map(w.el('build_instructions').val().split('\n'), v.trim), v.is.emp),
         polling_strategy : (ondemand ? 'ondemand' : {
             time : parseInt(bonzo(qwery('#time')).val(), 10)
         })
     };
 };
Example #27
0
  function injectListenerTab(protocol, portNum) {
    var opts = {}
      , newElement
      ;

    opts.protocol = protocol;
    opts.portNum  = portNum;
    opts.display  = portNum;

    newElement = bonzo.create(listenerTabTemplate(opts));
    bonzo(newElement).removeClass('js-listener-tab-template');
    $('.js-listener-tab-bar[data-protocol='+protocol+']').append(newElement);

    newElement = bonzo.create(listenerWindowTemplate(opts));
    bonzo(newElement).removeClass('js-listener-window-template');
    qwery('.js-logging-options input[type="checkbox"]', newElement).forEach(function (box) {
      bean.on(box, 'click', preventDefault);
    });
    $('.js-scroll-lock', newElement).attr('checked', true);
    $('.js-listener-container[data-protocol='+protocol+']').append(newElement);
  }
Example #28
0
            .then(function (resp) {
                if (resp.sheets && resp.sheets[id]) {
                    var options = resp.sheets[id][0];

                    for (var key in options) {
                        if (options.hasOwnProperty(key)) {
                            if (/^a\d+/.test(key)) {
                                var compressed = (compressString(options[key]));
                                answersObj[compressed] = options[key];
                            } else if (key === 'title') {
                                metaObj['title'] = options[key];
                            } else if (key === 'isClosed') {
                                metaObj['isClosed'] = options[key].toLowerCase();
                            } else if (key === 'closedAfter') {
                                var date = options[key];
                                if (moment(date, moment.ISO_8601).isValid()) {
                                    metaObj['closedAfter'] = date;
                                } else {
                                    // eslint-disable-next-line
                                    console && console.warn('closedAfter date is not valid ISO8601');
                                }
                            }
                        }
                    }

                    bonzo($('.title')[0]).html(metaObj['title']);
                    bonzo($('#form')).removeClass('form-is-hidden');
                    var previousSubmission = getPreviousPollSubmission();
                    if (previousSubmission) {
                        renderResultsFromPollJson(previousSubmission.id, previousSubmission.answer);
                    } else if (metaObj['isClosed'] === 'true' || (metaObj['closedAfter']) && moment(metaObj['closedAfter']).isBefore()) {
                        renderResultsFromPollJson(id, null);
                    } else {
                        renderPollForm(id);
                    }
                } else {
                    // eslint-disable-next-line
                    console && console.warn('No poll found with ID: ' + id);
                }
            }, function (err, msg) {
Example #29
0
    fastdom.read(() => {
        const $el = bonzo(el);
        const conditionFn = () => {
            const elOffset = $el.offset();
            const loadAfter = elOffset.top - distanceThreshold;
            const loadBefore =
                elOffset.top + elOffset.height + distanceThreshold;

            return scroll.top > loadAfter && scroll.bottom < loadBefore;
        };

        addItem(conditionFn, loadFn);
    });
Example #30
0
 page.once('login', function(_, msg) {
     if(msg === null) {
         model.username.error([]);
         model.password.error([]);
         model.username._input.focus();
         loginResult.removeClass('hidden');
         loginResult.html('<p>Incorrect username/email or password.</p>');
     } else {
         page.setId(msg.sessionId, bonzo(qwery('#rememberme')).attr('checked'));
         page.setUser(msg.user);
         page.go('/');
     }
 });