<commit_before>import m from 'mithril';
import h from './h';
import _ from 'underscore';
import c from './c';
import Chart from 'chart.js';
import { isNumber } from 'util';
import { wrap } from './wrap';

m.originalTrust = m.trust;
m.trust = (text) => h.trust(text);

(function () {

    h.SentryInitSDK();

    try {
        functionThatDoesntExist();
    } catch(e) {
        h.captureException(e);
    }

    /// Setup an AUTO-SCROLL TOP when change route
    const pushState = history.pushState;
    history.pushState = function () {
        pushState.apply(history, arguments);
        h.scrollTop();
    };

    Chart.defaults.global.responsive = true;
    Chart.defaults.global.responsive = false;
    Chart.defaults.global.scaleFontFamily = 'proxima-nova';

    // NOTE: comment when need to use multilanguage i18n support
    window.I18n.defaultLocale = 'pt';
    window.I18n.locale = 'pt';

    const adminRoot = document.getElementById('new-admin');

    if (adminRoot) {
        const adminWrap = function (component, customAttr) {
            return {
                oninit: function (vnode) {
                    const attr = customAttr;

                    vnode.state = {
                        attr,
                    };
                },
                view: function ({ state }) {
                    const { attr } = state;
                    return m('#app', [
                        m(c.root.Menu, attr),
                        m(component, attr),
                        attr.hideFooter ? '' : m(c.root.Footer, attr)
                    ]);
                },
            };
        };
        m.route.prefix('#');

        m.route(adminRoot, '/', {
            '/': adminWrap(c.root.AdminContributions, { root: adminRoot, menuTransparency: false, hideFooter: true }),
            '/users': adminWrap(c.root.AdminUsers, { menuTransparency: false, hideFooter: true }),
            '/subscriptions': adminWrap(c.root.AdminSubscriptions, { menuTransparency: false, hideFooter: true }),
            '/projects': adminWrap(c.root.AdminProjects, { menuTransparency: false, hideFooter: true }),
            '/notifications': adminWrap(c.root.AdminNotifications, { menuTransparency: false, hideFooter: true }),
            '/balance-transfers': adminWrap(c.root.AdminBalanceTranfers, { menuTransparency: false, hideFooter: true }),
        });
    }

    const app = document.getElementById('application'),
        body = document.body

    const urlWithLocale = function (url) {
        return `/${window.I18n.locale}${url}`;
    };

    if (app) {
        const rootEl = app,
            isUserProfile =
                body.getAttribute('data-controller-name') == 'users' &&
                body.getAttribute('data-action') == 'show' &&
                app.getAttribute('data-hassubdomain') == 'true';

        m.route.prefix('');

        m.route(rootEl, '/', {
            '/': wrap(isUserProfile ? c.root.UsersShow : c.root.ProjectsHome, { menuTransparency: true, footerBig: true, absoluteHome: isUserProfile }),
            '/explore': wrap(c.root.ProjectsExplore, { menuTransparency: true, footerBig: true }),
            '/start': wrap(c.root.Start, { menuTransparency: true, footerBig: true }),
            '/start-sub': wrap(c.root.SubProjectNew, { menuTransparency: false }),
            '/projects/:project_id/contributions/new': wrap(c.root.ProjectsContribution),
            '/projects/:project_id/contributions/fallback_create': wrap(c.root.ProjectsContribution),
            '/projects/:project_id/contributions/:contribution_id/edit': wrap(c.root.ProjectsPayment, { menuShort: true }),
            '/projects/:project_id/subscriptions/start': wrap(c.root.ProjectsSubscriptionContribution, { menuShort: true, footerBig: false }),
            '/projects/:project_id/subscriptions/checkout': wrap(c.root.ProjectsSubscriptionCheckout, { menuShort: true, footerBig: false }),
            '/projects/:project_id/subscriptions/thank_you': wrap(c.root.ProjectsSubscriptionThankYou, { menuShort: true, footerBig: false }),
            [urlWithLocale('/projects/:project_id/contributions/new')]: wrap(c.root.ProjectsContribution),
            [urlWithLocale('/projects/:project_id/contributions/:contribution_id/edit')]: wrap(c.root.ProjectsPayment, { menuShort: true }),
            [urlWithLocale('/projects/:project_id/subscriptions/start')]: wrap(c.root.ProjectsSubscriptionContribution, { menuShort: true, footerBig: false }),
            [urlWithLocale('/projects/:project_id/subscriptions/checkout')]: wrap(c.root.ProjectsSubscriptionCheckout, { menuShort: true, footerBig: false }),
            [urlWithLocale('/projects/subscriptions/thank_you')]: wrap(c.root.ProjectsSubscriptionThankYou, { menuShort: true, footerBig: false }),
            '/en': wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            '/pt': wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/flexible_projects')]: wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/projects')]: wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            '/projects': wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/explore')]: wrap(c.root.ProjectsExplore, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/start')]: wrap(c.root.Start, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/projects/:project_id/contributions/:contribution_id')]: wrap(c.root.ThankYou, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/contributions/:contribution_id': wrap(c.root.ThankYou, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/insights': wrap(c.root.Insights, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/insights')]: wrap(c.root.Insights, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/contributions_report': wrap(c.root.ProjectsContributionReport, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/contributions_report')]: wrap(c.root.ProjectsContributionReport, {
                menuTransparency: false,
                footerBig: false,
            }),
            '/projects/:project_id/subscriptions_report': wrap(c.root.ProjectsSubscriptionReport, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/subscriptions_report')]: wrap(c.root.ProjectsSubscriptionReport, {
                menuTransparency: false,
                footerBig: false,
            }),
            '/projects/:project_id/subscriptions_report_download': wrap(c.root.ProjectsSubscriptionReportDownload, {
                menuTransparency: false,
                footerBig: false,
            }),
            [urlWithLocale('/projects/:project_id/subscriptions_report_download')]: wrap(c.root.ProjectsSubscriptionReportDownload, {
                menuTransparency: false,
                footerBig: false,
            }),
            '/projects/:project_id/surveys': wrap(c.root.Surveys, { menuTransparency: false, footerBig: false, menuShort: true }),
            '/projects/:project_id/fiscal': wrap(c.root.ProjectsFiscal, { menuTransparency: false, footerBig: false, menuShort: true }),
            '/projects/:project_id/posts': wrap(c.root.Posts, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/posts/:post_id': wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: true }),
            [urlWithLocale('/projects/:project_id/posts')]: wrap(c.root.Posts, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/posts/:post_id')]: wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: true }),
            '/projects/:project_id': wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: false }),
            '/users/:user_id': wrap(c.root.UsersShow, { menuTransparency: true, footerBig: false }),
            [urlWithLocale('/users/:user_id')]: wrap(c.root.UsersShow, { menuTransparency: true, footerBig: false }),
            '/contributions/:contribution_id/surveys/:survey_id': wrap(c.root.SurveysShow, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/contributions/:contribution_id/surveys/:survey_id')]: wrap(c.root.SurveysShow, { menuTransparency: false, footerBig: false }),
            '/users/:user_id/edit': wrap(c.root.UsersEdit, { menuTransparency: true, footerBig: false }),
            [urlWithLocale('/users/:user_id/edit')]: wrap(c.root.UsersEdit, { menuTransparency: true, footerBig: false }),
            '/projects/:project_id/edit': wrap(c.root.ProjectEdit, { menuTransparency: false, hideFooter: true, menuShort: true }),
            [urlWithLocale('/projects/:project_id/edit')]: wrap(c.root.ProjectEdit, { menuTransparency: false, hideFooter: true, menuShort: true }),
            '/projects/:project_id/rewards/:reward_id/surveys/new': wrap(c.root.SurveyCreate, { menuTransparency: false, hideFooter: true, menuShort: true }),
            [urlWithLocale('/follow-fb-friends')]: wrap(c.root.FollowFoundFriends, { menuTransparency: false, footerBig: false }),
            '/follow-fb-friends': wrap(c.root.FollowFoundFriends, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/:project')]: wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: false }),
            '/:project': wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/team')]: wrap(c.root.Team, { menuTransparency: true, footerBig: true }),
            '/team': wrap(c.root.Team, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/jobs')]: wrap(c.root.Jobs, { menuTransparency: true, footerBig: true }),
            '/jobs': wrap(c.root.Jobs, { menuTransparency: true, footerBig: true }),
            '/press': wrap(c.root.Press, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/press')]: wrap(c.root.Press, { menuTransparency: true, footerBig: true }),

            [urlWithLocale('/projects/:project_id/publish')]: wrap(c.root.Publish, { menuTransparency: false, hideFooter: true, menuShort: true }),
            ['/projects/:project_id/publish']: wrap(c.root.Publish, { menuTransparency: false, hideFooter: true, menuShort: true }),
        });
    }
})();
<commit_msg>removing sentry send exception test<commit_after>import m from 'mithril';
import h from './h';
import _ from 'underscore';
import c from './c';
import Chart from 'chart.js';
import { isNumber } from 'util';
import { wrap } from './wrap';

m.originalTrust = m.trust;
m.trust = (text) => h.trust(text);

(function () {

    h.SentryInitSDK();

    /// Setup an AUTO-SCROLL TOP when change route
    const pushState = history.pushState;
    history.pushState = function () {
        pushState.apply(history, arguments);
        h.scrollTop();
    };

    Chart.defaults.global.responsive = true;
    Chart.defaults.global.responsive = false;
    Chart.defaults.global.scaleFontFamily = 'proxima-nova';

    // NOTE: comment when need to use multilanguage i18n support
    window.I18n.defaultLocale = 'pt';
    window.I18n.locale = 'pt';

    const adminRoot = document.getElementById('new-admin');

    if (adminRoot) {
        const adminWrap = function (component, customAttr) {
            return {
                oninit: function (vnode) {
                    const attr = customAttr;

                    vnode.state = {
                        attr,
                    };
                },
                view: function ({ state }) {
                    const { attr } = state;
                    return m('#app', [
                        m(c.root.Menu, attr),
                        m(component, attr),
                        attr.hideFooter ? '' : m(c.root.Footer, attr)
                    ]);
                },
            };
        };
        m.route.prefix('#');

        m.route(adminRoot, '/', {
            '/': adminWrap(c.root.AdminContributions, { root: adminRoot, menuTransparency: false, hideFooter: true }),
            '/users': adminWrap(c.root.AdminUsers, { menuTransparency: false, hideFooter: true }),
            '/subscriptions': adminWrap(c.root.AdminSubscriptions, { menuTransparency: false, hideFooter: true }),
            '/projects': adminWrap(c.root.AdminProjects, { menuTransparency: false, hideFooter: true }),
            '/notifications': adminWrap(c.root.AdminNotifications, { menuTransparency: false, hideFooter: true }),
            '/balance-transfers': adminWrap(c.root.AdminBalanceTranfers, { menuTransparency: false, hideFooter: true }),
        });
    }

    const app = document.getElementById('application'),
        body = document.body

    const urlWithLocale = function (url) {
        return `/${window.I18n.locale}${url}`;
    };

    if (app) {
        const rootEl = app,
            isUserProfile =
                body.getAttribute('data-controller-name') == 'users' &&
                body.getAttribute('data-action') == 'show' &&
                app.getAttribute('data-hassubdomain') == 'true';

        m.route.prefix('');

        m.route(rootEl, '/', {
            '/': wrap(isUserProfile ? c.root.UsersShow : c.root.ProjectsHome, { menuTransparency: true, footerBig: true, absoluteHome: isUserProfile }),
            '/explore': wrap(c.root.ProjectsExplore, { menuTransparency: true, footerBig: true }),
            '/start': wrap(c.root.Start, { menuTransparency: true, footerBig: true }),
            '/start-sub': wrap(c.root.SubProjectNew, { menuTransparency: false }),
            '/projects/:project_id/contributions/new': wrap(c.root.ProjectsContribution),
            '/projects/:project_id/contributions/fallback_create': wrap(c.root.ProjectsContribution),
            '/projects/:project_id/contributions/:contribution_id/edit': wrap(c.root.ProjectsPayment, { menuShort: true }),
            '/projects/:project_id/subscriptions/start': wrap(c.root.ProjectsSubscriptionContribution, { menuShort: true, footerBig: false }),
            '/projects/:project_id/subscriptions/checkout': wrap(c.root.ProjectsSubscriptionCheckout, { menuShort: true, footerBig: false }),
            '/projects/:project_id/subscriptions/thank_you': wrap(c.root.ProjectsSubscriptionThankYou, { menuShort: true, footerBig: false }),
            [urlWithLocale('/projects/:project_id/contributions/new')]: wrap(c.root.ProjectsContribution),
            [urlWithLocale('/projects/:project_id/contributions/:contribution_id/edit')]: wrap(c.root.ProjectsPayment, { menuShort: true }),
            [urlWithLocale('/projects/:project_id/subscriptions/start')]: wrap(c.root.ProjectsSubscriptionContribution, { menuShort: true, footerBig: false }),
            [urlWithLocale('/projects/:project_id/subscriptions/checkout')]: wrap(c.root.ProjectsSubscriptionCheckout, { menuShort: true, footerBig: false }),
            [urlWithLocale('/projects/subscriptions/thank_you')]: wrap(c.root.ProjectsSubscriptionThankYou, { menuShort: true, footerBig: false }),
            '/en': wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            '/pt': wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/flexible_projects')]: wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/projects')]: wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            '/projects': wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/explore')]: wrap(c.root.ProjectsExplore, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/start')]: wrap(c.root.Start, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/projects/:project_id/contributions/:contribution_id')]: wrap(c.root.ThankYou, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/contributions/:contribution_id': wrap(c.root.ThankYou, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/insights': wrap(c.root.Insights, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/insights')]: wrap(c.root.Insights, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/contributions_report': wrap(c.root.ProjectsContributionReport, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/contributions_report')]: wrap(c.root.ProjectsContributionReport, {
                menuTransparency: false,
                footerBig: false,
            }),
            '/projects/:project_id/subscriptions_report': wrap(c.root.ProjectsSubscriptionReport, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/subscriptions_report')]: wrap(c.root.ProjectsSubscriptionReport, {
                menuTransparency: false,
                footerBig: false,
            }),
            '/projects/:project_id/subscriptions_report_download': wrap(c.root.ProjectsSubscriptionReportDownload, {
                menuTransparency: false,
                footerBig: false,
            }),
            [urlWithLocale('/projects/:project_id/subscriptions_report_download')]: wrap(c.root.ProjectsSubscriptionReportDownload, {
                menuTransparency: false,
                footerBig: false,
            }),
            '/projects/:project_id/surveys': wrap(c.root.Surveys, { menuTransparency: false, footerBig: false, menuShort: true }),
            '/projects/:project_id/fiscal': wrap(c.root.ProjectsFiscal, { menuTransparency: false, footerBig: false, menuShort: true }),
            '/projects/:project_id/posts': wrap(c.root.Posts, { menuTransparency: false, footerBig: false }),
            '/projects/:project_id/posts/:post_id': wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: true }),
            [urlWithLocale('/projects/:project_id/posts')]: wrap(c.root.Posts, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/projects/:project_id/posts/:post_id')]: wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: true }),
            '/projects/:project_id': wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: false }),
            '/users/:user_id': wrap(c.root.UsersShow, { menuTransparency: true, footerBig: false }),
            [urlWithLocale('/users/:user_id')]: wrap(c.root.UsersShow, { menuTransparency: true, footerBig: false }),
            '/contributions/:contribution_id/surveys/:survey_id': wrap(c.root.SurveysShow, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/contributions/:contribution_id/surveys/:survey_id')]: wrap(c.root.SurveysShow, { menuTransparency: false, footerBig: false }),
            '/users/:user_id/edit': wrap(c.root.UsersEdit, { menuTransparency: true, footerBig: false }),
            [urlWithLocale('/users/:user_id/edit')]: wrap(c.root.UsersEdit, { menuTransparency: true, footerBig: false }),
            '/projects/:project_id/edit': wrap(c.root.ProjectEdit, { menuTransparency: false, hideFooter: true, menuShort: true }),
            [urlWithLocale('/projects/:project_id/edit')]: wrap(c.root.ProjectEdit, { menuTransparency: false, hideFooter: true, menuShort: true }),
            '/projects/:project_id/rewards/:reward_id/surveys/new': wrap(c.root.SurveyCreate, { menuTransparency: false, hideFooter: true, menuShort: true }),
            [urlWithLocale('/follow-fb-friends')]: wrap(c.root.FollowFoundFriends, { menuTransparency: false, footerBig: false }),
            '/follow-fb-friends': wrap(c.root.FollowFoundFriends, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/:project')]: wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: false }),
            '/:project': wrap(c.root.ProjectsShow, { menuTransparency: false, footerBig: false }),
            [urlWithLocale('/team')]: wrap(c.root.Team, { menuTransparency: true, footerBig: true }),
            '/team': wrap(c.root.Team, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/jobs')]: wrap(c.root.Jobs, { menuTransparency: true, footerBig: true }),
            '/jobs': wrap(c.root.Jobs, { menuTransparency: true, footerBig: true }),
            '/press': wrap(c.root.Press, { menuTransparency: true, footerBig: true }),
            [urlWithLocale('/press')]: wrap(c.root.Press, { menuTransparency: true, footerBig: true }),

            [urlWithLocale('/projects/:project_id/publish')]: wrap(c.root.Publish, { menuTransparency: false, hideFooter: true, menuShort: true }),
            ['/projects/:project_id/publish']: wrap(c.root.Publish, { menuTransparency: false, hideFooter: true, menuShort: true }),
        });
    }
})();
<|endoftext|>


<commit_before>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['quill'], factory)
  } else if (typeof module !== 'undefined' && typeof exports === 'object') {
    module.exports = factory(require('quill'))
  } else {
    root.Requester = factory(root.Quill)
  }
}(this, function (Quill) {
  'use strict'

  var app
  // declare ngQuill module
  app = angular.module('ngQuill', [])

  app.provider('ngQuillConfig', function () {
    var config = {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
          ['blockquote', 'code-block'],

          [{ 'header': 1 }, { 'header': 2 }],               // custom button values
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
          [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
          [{ 'direction': 'rtl' }],                         // text direction

          [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

          [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
          [{ 'font': [] }],
          [{ 'align': [] }],

          ['clean'],                                         // remove formatting button

          ['link', 'image', 'video']                         // link and image, video
        ]
      },
      theme: 'snow',
      placeholder: 'Insert text here ...',
      readOnly: false,
      bounds: document.body
    }

    this.set = function (customConf) {
      customConf = customConf || {}

      if (customConf.modules) {
        config.modules = customConf.modules
      }
      if (customConf.theme) {
        config.theme = customConf.theme
      }
      if (customConf.placeholder !== null && customConf.placeholder !== undefined) {
        config.placeholder = customConf.placeholder.trim()
      }
      if (customConf.bounds) {
        config.bounds = customConf.bounds
      }
      if (customConf.readOnly) {
        config.readOnly = customConf.readOnly
      }
      if (customConf.formats) {
        config.formats = customConf.formats
      }
    }

    this.$get = function () {
      return config
    }
  })

  app.component('ngQuillEditor', {
    bindings: {
      'modules': '<modules',
      'theme': '@?',
      'readOnly': '<?',
      'formats': '<?',
      'placeholder': '@?',
      'bounds': '<?',
      'onEditorCreated': '&?',
      'onContentChanged': '&?',
      'onSelectionChanged': '&?',
      'ngModel': '<',
      'maxLength': '<',
      'minLength': '<'
    },
    require: {
      ngModelCtrl: 'ngModel'
    },
    transclude: {
      'toolbar': '?ngQuillToolbar'
    },
    template: '
<ng-transclude ng-transclude-slot="toolbar"></ng-transclude>
',
    controller: ['$scope', '$element', '$timeout', '$transclude', 'ngQuillConfig', function ($scope, $element, $timeout, $transclude, ngQuillConfig) {
      var config = {}
      var content
      var editorElem
      var modelChanged = false
      var editorChanged = false
      var editor
      var placeholder = ngQuillConfig.placeholder

      this.validate = function (text) {
        if (this.maxLength) {
          if (text.length > this.maxLength + 1) {
            this.ngModelCtrl.$setValidity('maxlength', false)
          } else {
            this.ngModelCtrl.$setValidity('maxlength', true)
          }
        }

        if (this.minLength > 1) {
          // validate only if text.length > 1
          if (text.length <= this.minLength && text.length > 1) {
            this.ngModelCtrl.$setValidity('minlength', false)
          } else {
            this.ngModelCtrl.$setValidity('minlength', true)
          }
        }
      }

      this.$onChanges = function (changes) {
        if (changes.ngModel && changes.ngModel.currentValue !== changes.ngModel.previousValue) {
          content = changes.ngModel.currentValue

          if (editor && !editorChanged) {
            modelChanged = true
            if (content) {
              editor.pasteHTML(content)
            } else {
              editor.setText('')
            }
          }
          editorChanged = false
        }

        if (editor && changes.readOnly) {
          editor.enable(!changes.readOnly.currentValue)
        }
      }

      this.$onInit = function () {
        if (this.placeholder !== null && this.placeholder !== undefined) {
          placeholder = this.placeholder.trim()
        }

        config = {
          theme: this.theme || ngQuillConfig.theme,
          readOnly: this.readOnly || ngQuillConfig.readOnly,
          modules: this.modules || ngQuillConfig.modules,
          formats: this.formats || ngQuillConfig.formats,
          placeholder: placeholder,
          bounds: this.bounds || ngQuillConfig.bounds
        }
      }

      this.$postLink = function () {
        // create quill instance after dom is rendered
        $timeout(function () {
          this._initEditor(editorElem)
        }.bind(this), 0)
      }

      this._initEditor = function (editorElem) {
        var $editorElem = angular.element('

')
        var container = $element.children()

        editorElem = $editorElem[0]

        // set toolbar to custom one
        if ($transclude.isSlotFilled('toolbar')) {
          config.modules.toolbar = container.find('ng-quill-toolbar').children()[0]
        }

        container.append($editorElem)

        editor = new Quill(editorElem, config)

        this.ready = true

        // mark model as touched if editor lost focus
        editor.on('selection-change', function (range, oldRange, source) {
          if (this.onSelectionChanged) {
            this.onSelectionChanged({
              editor: editor,
              oldRange: oldRange,
              range: range,
              source: source
            })
          }

          if (range) {
            return
          }
          $scope.$applyAsync(function () {
            this.ngModelCtrl.$setTouched()
          }.bind(this))
        }.bind(this))

        // update model if text changes
        editor.on('text-change', function (delta, oldDelta, source) {
          var html = editorElem.children[0].innerHTML
          var text = editor.getText()

          if (html === '

') {
            html = null
          }
          this.validate(text)

          if (!modelChanged) {
            $scope.$applyAsync(function () {
              editorChanged = true

              this.ngModelCtrl.$setViewValue(html)

              if (this.onContentChanged) {
                this.onContentChanged({
                  editor: editor,
                  html: html,
                  text: text,
                  delta: delta,
                  oldDelta: oldDelta,
                  source: source
                })
              }
            }.bind(this))
          }
          modelChanged = false
        }.bind(this))

        // set initial content
        if (content) {
          modelChanged = true

          var contents = editor.clipboard.convert(content)
          editor.setContents(contents)
          editor.history.clear()
        }

        // provide event to get informed when editor is created -> pass editor object.
        if (this.onEditorCreated) {
          this.onEditorCreated({editor: editor})
        }
      }
    }]
  })

  return app.name;
}))
<commit_msg>Remove unwanted semicolon<commit_after>(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['quill'], factory)
  } else if (typeof module !== 'undefined' && typeof exports === 'object') {
    module.exports = factory(require('quill'))
  } else {
    root.Requester = factory(root.Quill)
  }
}(this, function (Quill) {
  'use strict'

  var app
  // declare ngQuill module
  app = angular.module('ngQuill', [])

  app.provider('ngQuillConfig', function () {
    var config = {
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
          ['blockquote', 'code-block'],

          [{ 'header': 1 }, { 'header': 2 }],               // custom button values
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
          [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
          [{ 'direction': 'rtl' }],                         // text direction

          [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

          [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
          [{ 'font': [] }],
          [{ 'align': [] }],

          ['clean'],                                         // remove formatting button

          ['link', 'image', 'video']                         // link and image, video
        ]
      },
      theme: 'snow',
      placeholder: 'Insert text here ...',
      readOnly: false,
      bounds: document.body
    }

    this.set = function (customConf) {
      customConf = customConf || {}

      if (customConf.modules) {
        config.modules = customConf.modules
      }
      if (customConf.theme) {
        config.theme = customConf.theme
      }
      if (customConf.placeholder !== null && customConf.placeholder !== undefined) {
        config.placeholder = customConf.placeholder.trim()
      }
      if (customConf.bounds) {
        config.bounds = customConf.bounds
      }
      if (customConf.readOnly) {
        config.readOnly = customConf.readOnly
      }
      if (customConf.formats) {
        config.formats = customConf.formats
      }
    }

    this.$get = function () {
      return config
    }
  })

  app.component('ngQuillEditor', {
    bindings: {
      'modules': '<modules',
      'theme': '@?',
      'readOnly': '<?',
      'formats': '<?',
      'placeholder': '@?',
      'bounds': '<?',
      'onEditorCreated': '&?',
      'onContentChanged': '&?',
      'onSelectionChanged': '&?',
      'ngModel': '<',
      'maxLength': '<',
      'minLength': '<'
    },
    require: {
      ngModelCtrl: 'ngModel'
    },
    transclude: {
      'toolbar': '?ngQuillToolbar'
    },
    template: '
<ng-transclude ng-transclude-slot="toolbar"></ng-transclude>
',
    controller: ['$scope', '$element', '$timeout', '$transclude', 'ngQuillConfig', function ($scope, $element, $timeout, $transclude, ngQuillConfig) {
      var config = {}
      var content
      var editorElem
      var modelChanged = false
      var editorChanged = false
      var editor
      var placeholder = ngQuillConfig.placeholder

      this.validate = function (text) {
        if (this.maxLength) {
          if (text.length > this.maxLength + 1) {
            this.ngModelCtrl.$setValidity('maxlength', false)
          } else {
            this.ngModelCtrl.$setValidity('maxlength', true)
          }
        }

        if (this.minLength > 1) {
          // validate only if text.length > 1
          if (text.length <= this.minLength && text.length > 1) {
            this.ngModelCtrl.$setValidity('minlength', false)
          } else {
            this.ngModelCtrl.$setValidity('minlength', true)
          }
        }
      }

      this.$onChanges = function (changes) {
        if (changes.ngModel && changes.ngModel.currentValue !== changes.ngModel.previousValue) {
          content = changes.ngModel.currentValue

          if (editor && !editorChanged) {
            modelChanged = true
            if (content) {
              editor.pasteHTML(content)
            } else {
              editor.setText('')
            }
          }
          editorChanged = false
        }

        if (editor && changes.readOnly) {
          editor.enable(!changes.readOnly.currentValue)
        }
      }

      this.$onInit = function () {
        if (this.placeholder !== null && this.placeholder !== undefined) {
          placeholder = this.placeholder.trim()
        }

        config = {
          theme: this.theme || ngQuillConfig.theme,
          readOnly: this.readOnly || ngQuillConfig.readOnly,
          modules: this.modules || ngQuillConfig.modules,
          formats: this.formats || ngQuillConfig.formats,
          placeholder: placeholder,
          bounds: this.bounds || ngQuillConfig.bounds
        }
      }

      this.$postLink = function () {
        // create quill instance after dom is rendered
        $timeout(function () {
          this._initEditor(editorElem)
        }.bind(this), 0)
      }

      this._initEditor = function (editorElem) {
        var $editorElem = angular.element('

')
        var container = $element.children()

        editorElem = $editorElem[0]

        // set toolbar to custom one
        if ($transclude.isSlotFilled('toolbar')) {
          config.modules.toolbar = container.find('ng-quill-toolbar').children()[0]
        }

        container.append($editorElem)

        editor = new Quill(editorElem, config)

        this.ready = true

        // mark model as touched if editor lost focus
        editor.on('selection-change', function (range, oldRange, source) {
          if (this.onSelectionChanged) {
            this.onSelectionChanged({
              editor: editor,
              oldRange: oldRange,
              range: range,
              source: source
            })
          }

          if (range) {
            return
          }
          $scope.$applyAsync(function () {
            this.ngModelCtrl.$setTouched()
          }.bind(this))
        }.bind(this))

        // update model if text changes
        editor.on('text-change', function (delta, oldDelta, source) {
          var html = editorElem.children[0].innerHTML
          var text = editor.getText()

          if (html === '

') {
            html = null
          }
          this.validate(text)

          if (!modelChanged) {
            $scope.$applyAsync(function () {
              editorChanged = true

              this.ngModelCtrl.$setViewValue(html)

              if (this.onContentChanged) {
                this.onContentChanged({
                  editor: editor,
                  html: html,
                  text: text,
                  delta: delta,
                  oldDelta: oldDelta,
                  source: source
                })
              }
            }.bind(this))
          }
          modelChanged = false
        }.bind(this))

        // set initial content
        if (content) {
          modelChanged = true

          var contents = editor.clipboard.convert(content)
          editor.setContents(contents)
          editor.history.clear()
        }

        // provide event to get informed when editor is created -> pass editor object.
        if (this.onEditorCreated) {
          this.onEditorCreated({editor: editor})
        }
      }
    }]
  })

  return app.name
}))
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');

var dialectsHash = {
	base: require('./dialects/base'),
	mssql: require('./dialects/mssql'),
	postgresql: require('./dialects/postgresql'),
	sqlite: require('./dialects/sqlite'),
	mysql: require('./dialects/mysql')
};

var Builder = module.exports = function(options) {
	this.configure(options);
};

Builder.prototype._reset = function() {
	if (this.options.separatedValues) {
		this._placeholderId = 1;
		this._values = this.options.namedValues ? {} : [];
	} else {
		delete this._placeholderId;
		delete this._values;
	}

	this._query = '';
};

Builder.prototype._getPlaceholder = function() {
	return (this.options.namedValues ? 'p' : '') + (this._placeholderId++);
};

Builder.prototype._wrapPlaceholder = function(name) {
	return this.options.valuesPrefix + name;
};

Builder.prototype._pushValue = function(value) {
	if (_.isUndefined(value) || _.isNull(value)) {
		return 'null';
	} else if (_.isNumber(value) || _.isBoolean(value)) {
		return String(value);
	} else if (_.isString(value)) {
		if (this.options.separatedValues) {
			var placeholder = this._getPlaceholder();
			if (this.options.namedValues) {
				this._values[placeholder] = value;
			} else {
				this._values.push(value);
			}
			return this._wrapPlaceholder(placeholder);
		} else {
			return '\'' + value + '\'';
		}
	} else {
		throw new Error('Wrong value type "' + (typeof value) + '"');
	}
};

Builder.prototype.configure = function(options) {
	options = options || {};

	this.options = _.defaults({}, options, {
		separatedValues: true,
		namedValues: true,
		valuesPrefix: '$',
		dialect: 'base',
		wrappedIdentifiers: true
	});

	this.setDialect(this.options.dialect);

	this._reset();
};

Builder.prototype.build = function(params) {
	var builder = this;

	this._reset();

	this._query = this.dialect.buildTemplate('query', {queryBody: params}) + ';';

	if (this.options.separatedValues) {
		return {
			query: this._query,
			values: this._values,
			prefixValues: function() {
				var values = {};
				_(this.getValuesObject()).each(function(value, name) {
					values[builder._wrapPlaceholder(name)] = value;
				});
				return values;
			},
			getValuesArray: function() {
				return _.isArray(this.values) ? this.values : _(this.values).values();
			},
			getValuesObject: function() {
				return _.isArray(this.values) ? _(_.range(1, this.values.length + 1)).object(this.values) :
					this.values;
			}
		};
	} else {
		return {query: this._query};
	}
};

Builder.prototype.setDialect = function(name) {
	if (!dialectsHash[name]) {
		throw new Error('Unknown dialect "' + name + '"');
	}

	this.dialect = new (dialectsHash[name])(this);
};
<commit_msg>add usePlaceholderId option<commit_after>'use strict';

var _ = require('underscore');

var dialectsHash = {
	base: require('./dialects/base'),
	mssql: require('./dialects/mssql'),
	postgresql: require('./dialects/postgresql'),
	sqlite: require('./dialects/sqlite'),
	mysql: require('./dialects/mysql')
};

var Builder = module.exports = function(options) {
	this.configure(options);
};

Builder.prototype._reset = function() {
	if (this.options.separatedValues) {
		this._placeholderId = 1;
		this._values = this.options.namedValues ? {} : [];
	} else {
		delete this._placeholderId;
		delete this._values;
	}

	this._query = '';
};

Builder.prototype._getPlaceholder = function() {
	return (this.options.namedValues ? 'p' : '') + (this.options.usePlaceholderId ? (this._placeholderId++) : '');
};

Builder.prototype._wrapPlaceholder = function(name) {
	return this.options.valuesPrefix + name;
};

Builder.prototype._pushValue = function(value) {
	if (_.isUndefined(value) || _.isNull(value)) {
		return 'null';
	} else if (_.isNumber(value) || _.isBoolean(value)) {
		return String(value);
	} else if (_.isString(value)) {
		if (this.options.separatedValues) {
			var placeholder = this._getPlaceholder();
			if (this.options.namedValues) {
				this._values[placeholder] = value;
			} else {
				this._values.push(value);
			}
			return this._wrapPlaceholder(placeholder);
		} else {
			return '\'' + value + '\'';
		}
	} else {
		throw new Error('Wrong value type "' + (typeof value) + '"');
	}
};

Builder.prototype.configure = function(options) {
	options = options || {};

	this.options = _.defaults({}, options, {
		separatedValues: true,
		namedValues: true,
		valuesPrefix: '$',
		dialect: 'base',
		wrappedIdentifiers: true,
		usePlaceholderId: true
	});

	this.setDialect(this.options.dialect);

	this._reset();
};

Builder.prototype.build = function(params) {
	var builder = this;

	this._reset();

	this._query = this.dialect.buildTemplate('query', {queryBody: params}) + ';';

	if (this.options.separatedValues) {
		return {
			query: this._query,
			values: this._values,
			prefixValues: function() {
				var values = {};
				_(this.getValuesObject()).each(function(value, name) {
					values[builder._wrapPlaceholder(name)] = value;
				});
				return values;
			},
			getValuesArray: function() {
				return _.isArray(this.values) ? this.values : _(this.values).values();
			},
			getValuesObject: function() {
				return _.isArray(this.values) ? _(_.range(1, this.values.length + 1)).object(this.values) :
					this.values;
			}
		};
	} else {
		return {query: this._query};
	}
};

Builder.prototype.setDialect = function(name) {
	if (!dialectsHash[name]) {
		throw new Error('Unknown dialect "' + name + '"');
	}

	this.dialect = new (dialectsHash[name])(this);
};
<|endoftext|>


<commit_before>'use strict';
var EventEmitter = require('events').EventEmitter;
var StringWriter = require('./StringWriter');
var BufferedWriter = require('./BufferedWriter');
var documentProvider = require('../document-provider');
var RenderResult = require('../RenderResult');
var helpers;

var voidWriter = { write:function(){} };

function State(root, stream, writer, events) {
    this.root = root;
    this.stream = stream;
    this.writer = writer;
    this.events = events;

    this.remaining = 0;
    this.lastCount = 0;
    this.last = undefined; // Array
    this.ended = false;
    this.finished = false;
    this.ids = 0;
}

function AsyncStream(global, writer, state, shouldBuffer) {
    var finalGlobal = this.attributes = global || {};
    var originalStream;

    if (state) {
        originalStream = state.stream;
    } else {
        var events = finalGlobal.events /* deprecated */ = writer && writer.on ? writer : new EventEmitter();

        if (writer) {
            originalStream = writer;
            if (shouldBuffer) {
                writer = new BufferedWriter(writer);
            }
        } else {
            writer = originalStream = new StringWriter(events);
        }

        state = new State(this, originalStream, writer, events);
    }

    this.global = finalGlobal;
    this.stream = originalStream;
    this._state = state;

    this.data = {};
    this.writer = writer;
    writer.stream = this;

    this._sync = false;
    this._stack = undefined;
    this.name = undefined;
    this._timeoutId = undefined;

    this._node = undefined;

    this._elStack = undefined; // Array
}

AsyncStream.DEFAULT_TIMEOUT = 10000;
AsyncStream.INCLUDE_STACK = typeof process !== 'undefined' && process.env.NODE_ENV === 'development';
AsyncStream.enableAsyncStackTrace = function() {
    AsyncStream.INCLUDE_STACK = true;
};

var proto = AsyncStream.prototype = {
    constructor: AsyncStream,
    isAsyncWriter: AsyncStream, // Legacy
    isAsyncStream: AsyncStream,

    sync: function() {
        this._sync = true;
    },

    isSync: function() {
        return this._sync === true;
    },

    write: function(str) {
        if (str != null) {
            this.writer.write(str.toString());
        }
        return this;
    },

    getOutput: function() {
        return this._state.writer.toString();
    },

    beginAsync: function(options) {
        if (this._sync) {
            throw new Error('beginAsync() not allowed when using renderSync()');
        }

        var state = this._state;

        var currentWriter = this.writer;

        /* ┏━━━━━┓               this
           ┃ WAS ┃               ↓↑
           ┗━━━━━┛  prevWriter → currentWriter → nextWriter  */

        var newWriter = new StringWriter();
        var newStream = new AsyncStream(this.global, currentWriter, state);

        this.writer = newWriter;
        newWriter.stream = this;

        newWriter.next = currentWriter.next;
        currentWriter.next = newWriter;

        /* ┏━━━━━┓               newStream       this
           ┃ NOW ┃               ↓↑              ↓↑
           ┗━━━━━┛  prevWriter → currentWriter → newWriter → nextWriter  */

       var timeout;
       var name;

       state.remaining++;

       if (options != null) {
           if (typeof options === 'number') {
               timeout = options;
           } else {
               timeout = options.timeout;

               if (options.last === true) {
                   if (timeout == null) {
                       // Don't assign a timeout to last flush fragments
                       // unless it is explicitly given a timeout
                       timeout = 0;
                   }

                   state.lastCount++;
               }

               name = options.name;
           }
       }

       if (timeout == null) {
           timeout = AsyncStream.DEFAULT_TIMEOUT;
       }

       newStream.stack = AsyncStream.INCLUDE_STACK ? new Error().stack : null;
       newStream.name = name;

       if (timeout > 0) {
           newStream._timeoutId = setTimeout(function() {
               newStream.error(new Error('Async fragment ' + (name ? '(' + name + ') ': '') + 'timed out after ' + timeout + 'ms'));
           }, timeout);
       }

       state.events.emit('beginAsync', {
           writer: newStream, // Legacy
           parentWriter: this, // Legacy
           out: newStream,
           parentOut: this
       });

        return newStream;
    },

    end: function(data) {
        if (data) {
            this.write(data);
        }

        var currentWriter = this.writer;

        /* ┏━━━━━┓  this            nextStream
           ┃ WAS ┃  ↓↑              ↓↑
           ┗━━━━━┛  currentWriter → nextWriter → futureWriter  */

        // Prevent any more writes to the current steam
        this.writer = voidWriter;
        currentWriter.stream = null;

        // Flush the contents of nextWriter to the currentWriter
        this.flushNext(currentWriter);

        /* ┏━━━━━┓    this        ╵  nextStream
           ┃     ┃    ↓           ╵  ↓↑
           ┃ NOW ┃    voidWriter  ╵  currentWriter → futureWriter
           ┃     ┃  ──────────────┴────────────────────────────────
           ┗━━━━━┛    Flushed & garbage collected: nextWriter  */

       var state = this._state;

       if (state.finished) {
           return;
       }

       var remaining;

       if (this === state.root) {
           remaining = state.remaining;
           state.ended = true;
       } else {
           var timeoutId = this._timeoutId;

           if (timeoutId) {
               clearTimeout(timeoutId);
           }

           remaining = --state.remaining;
       }

       if (state.ended) {
           if (!state.lastFired && (state.remaining - state.lastCount === 0)) {
               state.lastFired = true;
               state.lastCount = 0;
               state.events.emit('last');
           }

           if (remaining === 0) {
               state.finished = true;
               if (state.writer.end) {
                   state.writer.end();
               } else {
                   state.events.emit('finish', this);
               }
           }
       }

       return this;
    },

    // flushNextOld: function(currentWriter) {
    //     if (currentWriter === this._state.writer) {
    //         var nextStream;
    //         var nextWriter = currentWriter.next;
    //
    //         // flush until there is no nextWriter
    //         // or the nextWriter is still attached
    //         // to a branch.
    //         while(nextWriter) {
    //             currentWriter.write(nextWriter.toString());
    //             nextStream = nextWriter.stream;
    //
    //             if(nextStream) break;
    //             else nextWriter = nextWriter.next;
    //         }
    //
    //         // Orphan the nextWriter and everything that
    //         // came before it. They have been flushed.
    //         currentWriter.next = nextWriter && nextWriter.next;
    //
    //         // If there is a nextStream,
    //         // set its writer to currentWriter
    //         // (which is the state.writer)
    //         if(nextStream) {
    //             nextStream.writer = currentWriter;
    //             currentWriter.stream = nextStream;
    //         }
    //     }
    // },

    flushNext: function(currentWriter) {
        // It is possible that currentWriter is the
        // last writer in the chain, so let's make
        // sure there is a nextWriter to flush.
        var nextWriter = currentWriter.next;
        if (nextWriter) {
            // Flush the contents of nextWriter
            // to the currentWriter
            currentWriter.write(nextWriter.toString());

            // Remove nextWriter from the chain.
            // It has been flushed and can now be
            // garbage collected.
            currentWriter.next = nextWriter.next;

            // It's possible that nextWriter is the last
            // writer in the chain and its stream already
            // ended, so let's make sure nextStream exists.
            var nextStream = nextWriter.stream;
            if (nextStream) {
                // Point the nextStream to currentWriter
                nextStream.writer = currentWriter;
                currentWriter.stream = nextStream;
            }
        }
    },

    on: function(event, callback) {
        var state = this._state;

        if (event === 'finish' && state.finished) {
            callback(this);
            return this;
        }

        state.events.on(event, callback);
        return this;
    },

    once: function(event, callback) {
        var state = this._state;

        if (event === 'finish' && state.finished) {
            callback(this);
            return this;
        }

        state.events.once(event, callback);
        return this;
    },

    onLast: function(callback) {
        var state = this._state;

        var lastArray = state.last;

        if (!lastArray) {
            lastArray = state.last = [];
            var i = 0;
            var next = function next() {
                if (i === lastArray.length) {
                    return;
                }
                var _next = lastArray[i++];
                _next(next);
            };

            this.once('last', function() {
                next();
            });
        }

        lastArray.push(callback);
        return this;
    },

    emit: function(type, arg) {
        var events = this._state.events;
        switch(arguments.length) {
            case 1:
                events.emit(type);
                break;
            case 2:
                events.emit(type, arg);
                break;
            default:
                events.emit.apply(events, arguments);
                break;
        }
        return this;
    },

    removeListener: function() {
        var events = this._state.events;
        events.removeListener.apply(events, arguments);
        return this;
    },

    prependListener: function() {
        var events = this._state.events;
        events.prependListener.apply(events, arguments);
        return this;
    },

    pipe: function(stream) {
        this._state.stream.pipe(stream);
        return this;
    },

    error: function(e) {
        var stack = this._stack;
        var name = this.name;

        var message = 'Async fragment failed' + (name ? ' (' + name + ')': '') + '. Exception: ' + (e.stack || e) + (stack ? ('\nCreation stack trace: ' + stack) : '');
        e = new Error(message);

        try {
            this.emit('error', e);
        } finally {
            // If there is no listener for the error event then it will
            // throw a new here. In order to ensure that the async fragment
            // is still properly ended we need to put the end() in a `finally`
            // block
            this.end();
        }

        if (console) {
            console.error(message);
        }

        return this;
    },

    flush: function() {
        var state = this._state;

        if (!state.finished) {
            var writer = state.writer;
            if (writer && writer.flush) {
                writer.flush();
            }
        }
        return this;
    },

    createOut: function() {
        return new AsyncStream(this.global);
    },

    beginElement: function(name, elementAttrs) {

        var str = '<' + name;
        helpers.as(elementAttrs);

        str += '>';

        this.write(str);

        if (this._elStack) {
            this._elStack.push(name);
        } else {
            this._elStack = [name];
        }
    },

    endElement: function() {
        var tagName = this._elStack.pop();
        this.write('</' + tagName + '>');
    },

    text: function(str) {
        this.write(helpers.x(str));
    },

    getNode: function(doc) {
        var node = this._node;
        var curEl;
        var newBodyEl;
        var html = this.getOutput();

        if (!doc) {
            doc = documentProvider.document;
        }

        if (!node) {
            if (html) {
                newBodyEl = doc.createElement('body');
                newBodyEl.innerHTML = html;
                if (newBodyEl.childNodes.length == 1) {
                    // If the rendered component resulted in a single node then just use that node
                    node = newBodyEl.childNodes[0];
                } else {
                    // Otherwise, wrap the nodes in a document fragment node
                    node = doc.createDocumentFragment();
                    while ((curEl = newBodyEl.firstChild)) {
                        node.appendChild(curEl);
                    }
                }
            } else {
                // empty HTML so use empty document fragment (so that we're returning a valid DOM node)
                node = doc.createDocumentFragment();
            }
            this._node = node;
        }
        return node;
    },
    toString: function() {
        return this.getOutput();
    },

    then: function(fn, fnErr) {
        var out = this;
        var promise = new Promise(function(resolve, reject) {
            out.on('error', reject);
            out.on('finish', function() {
                resolve(new RenderResult(out));
            });
        });

        return Promise.resolve(promise).then(fn, fnErr);
    },

    catch: function(fnErr) {
        return this.then(undefined, fnErr);
    },

    // END DOM METHODS

    // Deprecated BEGIN:
    getAttributes: function() {
        return this.global;
    },
    getAttribute: function(name) {
        return this.global[name];
    },

    captureString: function(func, thisObj) {
        var sb = new StringWriter();
        this.swapWriter(sb, func, thisObj);
        return sb.toString();
    },
    swapWriter: function(newWriter, func, thisObj) {
        var currentWriter = this.writer;
        this.writer = newWriter;
        func.call(thisObj);
        this.writer = currentWriter;
    }
    // // Deprecated END
};

// alias:
proto.w = proto.write;

module.exports = AsyncStream;

helpers = require('./helpers');<commit_msg>Added element() method<commit_after>'use strict';
var EventEmitter = require('events').EventEmitter;
var StringWriter = require('./StringWriter');
var BufferedWriter = require('./BufferedWriter');
var documentProvider = require('../document-provider');
var RenderResult = require('../RenderResult');
var helpers;

var voidWriter = { write:function(){} };

function State(root, stream, writer, events) {
    this.root = root;
    this.stream = stream;
    this.writer = writer;
    this.events = events;

    this.remaining = 0;
    this.lastCount = 0;
    this.last = undefined; // Array
    this.ended = false;
    this.finished = false;
    this.ids = 0;
}

function AsyncStream(global, writer, state, shouldBuffer) {
    var finalGlobal = this.attributes = global || {};
    var originalStream;

    if (state) {
        originalStream = state.stream;
    } else {
        var events = finalGlobal.events /* deprecated */ = writer && writer.on ? writer : new EventEmitter();

        if (writer) {
            originalStream = writer;
            if (shouldBuffer) {
                writer = new BufferedWriter(writer);
            }
        } else {
            writer = originalStream = new StringWriter(events);
        }

        state = new State(this, originalStream, writer, events);
    }

    this.global = finalGlobal;
    this.stream = originalStream;
    this._state = state;

    this.data = {};
    this.writer = writer;
    writer.stream = this;

    this._sync = false;
    this._stack = undefined;
    this.name = undefined;
    this._timeoutId = undefined;

    this._node = undefined;

    this._elStack = undefined; // Array
}

AsyncStream.DEFAULT_TIMEOUT = 10000;
AsyncStream.INCLUDE_STACK = typeof process !== 'undefined' && process.env.NODE_ENV === 'development';
AsyncStream.enableAsyncStackTrace = function() {
    AsyncStream.INCLUDE_STACK = true;
};

var proto = AsyncStream.prototype = {
    constructor: AsyncStream,
    isAsyncWriter: AsyncStream, // Legacy
    isAsyncStream: AsyncStream,

    sync: function() {
        this._sync = true;
    },

    isSync: function() {
        return this._sync === true;
    },

    write: function(str) {
        if (str != null) {
            this.writer.write(str.toString());
        }
        return this;
    },

    getOutput: function() {
        return this._state.writer.toString();
    },

    beginAsync: function(options) {
        if (this._sync) {
            throw new Error('beginAsync() not allowed when using renderSync()');
        }

        var state = this._state;

        var currentWriter = this.writer;

        /* ┏━━━━━┓               this
           ┃ WAS ┃               ↓↑
           ┗━━━━━┛  prevWriter → currentWriter → nextWriter  */

        var newWriter = new StringWriter();
        var newStream = new AsyncStream(this.global, currentWriter, state);

        this.writer = newWriter;
        newWriter.stream = this;

        newWriter.next = currentWriter.next;
        currentWriter.next = newWriter;

        /* ┏━━━━━┓               newStream       this
           ┃ NOW ┃               ↓↑              ↓↑
           ┗━━━━━┛  prevWriter → currentWriter → newWriter → nextWriter  */

       var timeout;
       var name;

       state.remaining++;

       if (options != null) {
           if (typeof options === 'number') {
               timeout = options;
           } else {
               timeout = options.timeout;

               if (options.last === true) {
                   if (timeout == null) {
                       // Don't assign a timeout to last flush fragments
                       // unless it is explicitly given a timeout
                       timeout = 0;
                   }

                   state.lastCount++;
               }

               name = options.name;
           }
       }

       if (timeout == null) {
           timeout = AsyncStream.DEFAULT_TIMEOUT;
       }

       newStream.stack = AsyncStream.INCLUDE_STACK ? new Error().stack : null;
       newStream.name = name;

       if (timeout > 0) {
           newStream._timeoutId = setTimeout(function() {
               newStream.error(new Error('Async fragment ' + (name ? '(' + name + ') ': '') + 'timed out after ' + timeout + 'ms'));
           }, timeout);
       }

       state.events.emit('beginAsync', {
           writer: newStream, // Legacy
           parentWriter: this, // Legacy
           out: newStream,
           parentOut: this
       });

        return newStream;
    },

    end: function(data) {
        if (data) {
            this.write(data);
        }

        var currentWriter = this.writer;

        /* ┏━━━━━┓  this            nextStream
           ┃ WAS ┃  ↓↑              ↓↑
           ┗━━━━━┛  currentWriter → nextWriter → futureWriter  */

        // Prevent any more writes to the current steam
        this.writer = voidWriter;
        currentWriter.stream = null;

        // Flush the contents of nextWriter to the currentWriter
        this.flushNext(currentWriter);

        /* ┏━━━━━┓    this        ╵  nextStream
           ┃     ┃    ↓           ╵  ↓↑
           ┃ NOW ┃    voidWriter  ╵  currentWriter → futureWriter
           ┃     ┃  ──────────────┴────────────────────────────────
           ┗━━━━━┛    Flushed & garbage collected: nextWriter  */

       var state = this._state;

       if (state.finished) {
           return;
       }

       var remaining;

       if (this === state.root) {
           remaining = state.remaining;
           state.ended = true;
       } else {
           var timeoutId = this._timeoutId;

           if (timeoutId) {
               clearTimeout(timeoutId);
           }

           remaining = --state.remaining;
       }

       if (state.ended) {
           if (!state.lastFired && (state.remaining - state.lastCount === 0)) {
               state.lastFired = true;
               state.lastCount = 0;
               state.events.emit('last');
           }

           if (remaining === 0) {
               state.finished = true;
               if (state.writer.end) {
                   state.writer.end();
               } else {
                   state.events.emit('finish', this);
               }
           }
       }

       return this;
    },

    // flushNextOld: function(currentWriter) {
    //     if (currentWriter === this._state.writer) {
    //         var nextStream;
    //         var nextWriter = currentWriter.next;
    //
    //         // flush until there is no nextWriter
    //         // or the nextWriter is still attached
    //         // to a branch.
    //         while(nextWriter) {
    //             currentWriter.write(nextWriter.toString());
    //             nextStream = nextWriter.stream;
    //
    //             if(nextStream) break;
    //             else nextWriter = nextWriter.next;
    //         }
    //
    //         // Orphan the nextWriter and everything that
    //         // came before it. They have been flushed.
    //         currentWriter.next = nextWriter && nextWriter.next;
    //
    //         // If there is a nextStream,
    //         // set its writer to currentWriter
    //         // (which is the state.writer)
    //         if(nextStream) {
    //             nextStream.writer = currentWriter;
    //             currentWriter.stream = nextStream;
    //         }
    //     }
    // },

    flushNext: function(currentWriter) {
        // It is possible that currentWriter is the
        // last writer in the chain, so let's make
        // sure there is a nextWriter to flush.
        var nextWriter = currentWriter.next;
        if (nextWriter) {
            // Flush the contents of nextWriter
            // to the currentWriter
            currentWriter.write(nextWriter.toString());

            // Remove nextWriter from the chain.
            // It has been flushed and can now be
            // garbage collected.
            currentWriter.next = nextWriter.next;

            // It's possible that nextWriter is the last
            // writer in the chain and its stream already
            // ended, so let's make sure nextStream exists.
            var nextStream = nextWriter.stream;
            if (nextStream) {
                // Point the nextStream to currentWriter
                nextStream.writer = currentWriter;
                currentWriter.stream = nextStream;
            }
        }
    },

    on: function(event, callback) {
        var state = this._state;

        if (event === 'finish' && state.finished) {
            callback(this);
            return this;
        }

        state.events.on(event, callback);
        return this;
    },

    once: function(event, callback) {
        var state = this._state;

        if (event === 'finish' && state.finished) {
            callback(this);
            return this;
        }

        state.events.once(event, callback);
        return this;
    },

    onLast: function(callback) {
        var state = this._state;

        var lastArray = state.last;

        if (!lastArray) {
            lastArray = state.last = [];
            var i = 0;
            var next = function next() {
                if (i === lastArray.length) {
                    return;
                }
                var _next = lastArray[i++];
                _next(next);
            };

            this.once('last', function() {
                next();
            });
        }

        lastArray.push(callback);
        return this;
    },

    emit: function(type, arg) {
        var events = this._state.events;
        switch(arguments.length) {
            case 1:
                events.emit(type);
                break;
            case 2:
                events.emit(type, arg);
                break;
            default:
                events.emit.apply(events, arguments);
                break;
        }
        return this;
    },

    removeListener: function() {
        var events = this._state.events;
        events.removeListener.apply(events, arguments);
        return this;
    },

    prependListener: function() {
        var events = this._state.events;
        events.prependListener.apply(events, arguments);
        return this;
    },

    pipe: function(stream) {
        this._state.stream.pipe(stream);
        return this;
    },

    error: function(e) {
        var stack = this._stack;
        var name = this.name;

        var message = 'Async fragment failed' + (name ? ' (' + name + ')': '') + '. Exception: ' + (e.stack || e) + (stack ? ('\nCreation stack trace: ' + stack) : '');
        e = new Error(message);

        try {
            this.emit('error', e);
        } finally {
            // If there is no listener for the error event then it will
            // throw a new here. In order to ensure that the async fragment
            // is still properly ended we need to put the end() in a `finally`
            // block
            this.end();
        }

        if (console) {
            console.error(message);
        }

        return this;
    },

    flush: function() {
        var state = this._state;

        if (!state.finished) {
            var writer = state.writer;
            if (writer && writer.flush) {
                writer.flush();
            }
        }
        return this;
    },

    createOut: function() {
        return new AsyncStream(this.global);
    },

    element: function(tagName, elementAttrs, openTagOnly) {
        var str = '<' + tagName +
            helpers.as(elementAttrs) +
            '>';

        if (openTagOnly !== true) {
            str += '</' + tagName + '>';
        }

        this.write(str);
    },

    beginElement: function(name, elementAttrs) {

        var str = '<' + name +
            helpers.as(elementAttrs) +
            '>';

        this.write(str);

        if (this._elStack) {
            this._elStack.push(name);
        } else {
            this._elStack = [name];
        }
    },

    endElement: function() {
        var tagName = this._elStack.pop();
        this.write('</' + tagName + '>');
    },

    text: function(str) {
        this.write(helpers.x(str));
    },

    getNode: function(doc) {
        var node = this._node;
        var curEl;
        var newBodyEl;
        var html = this.getOutput();

        if (!doc) {
            doc = documentProvider.document;
        }

        if (!node) {
            if (html) {
                newBodyEl = doc.createElement('body');
                newBodyEl.innerHTML = html;
                if (newBodyEl.childNodes.length == 1) {
                    // If the rendered component resulted in a single node then just use that node
                    node = newBodyEl.childNodes[0];
                } else {
                    // Otherwise, wrap the nodes in a document fragment node
                    node = doc.createDocumentFragment();
                    while ((curEl = newBodyEl.firstChild)) {
                        node.appendChild(curEl);
                    }
                }
            } else {
                // empty HTML so use empty document fragment (so that we're returning a valid DOM node)
                node = doc.createDocumentFragment();
            }
            this._node = node;
        }
        return node;
    },
    toString: function() {
        return this.getOutput();
    },

    then: function(fn, fnErr) {
        var out = this;
        var promise = new Promise(function(resolve, reject) {
            out.on('error', reject);
            out.on('finish', function() {
                resolve(new RenderResult(out));
            });
        });

        return Promise.resolve(promise).then(fn, fnErr);
    },

    catch: function(fnErr) {
        return this.then(undefined, fnErr);
    },

    // END DOM METHODS

    // Deprecated BEGIN:
    getAttributes: function() {
        return this.global;
    },
    getAttribute: function(name) {
        return this.global[name];
    },

    captureString: function(func, thisObj) {
        var sb = new StringWriter();
        this.swapWriter(sb, func, thisObj);
        return sb.toString();
    },
    swapWriter: function(newWriter, func, thisObj) {
        var currentWriter = this.writer;
        this.writer = newWriter;
        func.call(thisObj);
        this.writer = currentWriter;
    }
    // // Deprecated END
};

// alias:
proto.w = proto.write;

module.exports = AsyncStream;

helpers = require('./helpers');<|endoftext|>


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

angular.module(PKG.name + '.feature.hydratorplusplus')
  .service('HydratorPlusPlusDetailMetricsStore', function(HydratorPlusPlusDetailMetricsDispatcher) {

    var dispatcher = HydratorPlusPlusDetailMetricsDispatcher.getDispatcher();
    this.changeListeners = [];
    this.setDefaults = function() {
      this.state = {
        metrics: []
      };
    };
    this.setDefaults();
    this.getMetrics = function() {
      return this.state.metrics;
    };
    this.registerOnChangeListener = function(callback) {
      this.changeListeners.push(callback);
    };
    this.emitChange = function() {
      this.changeListeners.forEach(function(listener) {
        listener(this.state);
      }.bind(this));
    };

    this.emptyMetrics = function () {
      this.state.metrics = [];
      this.emitChange();
    };

    this.setState = function(metrics) {
      var metricObj = {};
      angular.forEach(metrics.series, function (metric) {
        var split = metric.metricName.split('.');
        var key = split[1];

        if (!metricObj[key]) {
          metricObj[key] = {
            nodeName: split[1]
          };
        }

        if (split[split.length - 1] === 'in') {
          metricObj[key].recordsIn = metric.data[0].value;
        } else if (split[split.length - 1] === 'out') {
          metricObj[key].recordsOut = metric.data[0].value;
        }

      });

      var metricsArr = [];
      angular.forEach(metricObj, function (val) {
        metricsArr.push(val);
      });

      this.state.metrics = metricsArr;
      this.emitChange();
    };
    dispatcher.register('onMetricsFetch', this.setState.bind(this));
    dispatcher.register('onEmptyMetrics', this.emptyMetrics.bind(this));
    dispatcher.register('onReset', this.setDefaults.bind(this));
  });
<commit_msg>Fixes the logic to match metric with a node name in hydrator++<commit_after>/*
 * Copyright © 2016 Cask Data, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

angular.module(PKG.name + '.feature.hydratorplusplus')
  .service('HydratorPlusPlusDetailMetricsStore', function(HydratorPlusPlusDetailMetricsDispatcher) {

    var dispatcher = HydratorPlusPlusDetailMetricsDispatcher.getDispatcher();
    this.changeListeners = [];
    this.setDefaults = function() {
      this.state = {
        metrics: []
      };
    };
    this.setDefaults();
    this.getMetrics = function() {
      return this.state.metrics;
    };
    this.registerOnChangeListener = function(callback) {
      this.changeListeners.push(callback);
    };
    this.emitChange = function() {
      this.changeListeners.forEach(function(listener) {
        listener(this.state);
      }.bind(this));
    };

    this.emptyMetrics = function () {
      this.state.metrics = [];
      this.emitChange();
    };

    this.setState = function(metrics) {
      var metricObj = {};
      angular.forEach(metrics.series, function (metric) {
        var split = metric.metricName.split('.');
        var key = split[1];

        if (!metricObj[key]) {
          metricObj[key] = {
            nodeName: split[1]
          };
        }

        if (metric.metricName.indexOf(split[1] + '.records.in') !== -1) {
          metricObj[key].recordsIn = metric.data[0].value;
        } else if (metric.metricName.indexOf(split[1] + '.records.out') !== -1) {
          metricObj[key].recordsOut = metric.data[0].value;
        }

      });

      var metricsArr = [];
      angular.forEach(metricObj, function (val) {
        metricsArr.push(val);
      });

      this.state.metrics = metricsArr;
      this.emitChange();
    };
    dispatcher.register('onMetricsFetch', this.setState.bind(this));
    dispatcher.register('onEmptyMetrics', this.emptyMetrics.bind(this));
    dispatcher.register('onReset', this.setDefaults.bind(this));
  });
<|endoftext|>


<commit_before>var Slider = function(target){
	var self = this;

	this.el = target.querySelector('.component-wrapper');
	this.elTrack = this.el.querySelector('.well');
	this.elSlider = this.el.querySelector('#slider');
	this.elButton = this.el.querySelector('.trigger-button')

	this.wellWidth = 256;
	self.valueNow = 0;

	$(this.elSlider).draggable({
		axis: 'x',
		containment: 'parent',
		cancel: false,
		start: function(event, ui) {
			console.log(ui.position.left);
		},
		drag: function(event, ui) {
			self.valueNow = Math.floor(ui.position.left / self.wellWidth * 100);
			$(this).attr({
				'aria-valuenow': self.valueNow
			});
			if (ui.position.left >= self.wellWidth) {
				$(self.elTrack).fadeOut();
				$(this).attr({
					'aria-hidden': 'true',
					'aria-disabled': 'true'
				});
				$(self.elButton)
					.addClass('visible')
					.removeAttr('disabled')
					.attr({
						'aria-hidden':'false',
						'aria-disabled':'false'
					});
			}
		},
		stop: function(event, ui) {
			if (ui.position.left < self.wellWidth) {
				self.valueNow = 0;
				$(this).animate({
					left: 0
				}).attr({
					'aria-valuenow': self.valueNow
				});
			}
		}
	});
	this.numKeypresses = 0;
	this.elSlider.addEventListener('keydown', this.keydownHandler.bind(this), false);
	this.elSlider.addEventListener('touchmove', this.touchMoveHandler.bind(this), false);
	this.elSlider.addEventListener('touchend', this.touchEndHandler.bind(this), false);
}
Slider.prototype = {
	keydownHandler: function(event){
		if(event.which === 38 || event.which === 39){
			var target = event.target;
	    this.numKeypresses++;
	    curX = this.numKeypresses * 100;
	    if(curX <= 0) return;
	    if(curX > this.wellWidth){
	    	$(this.el).fadeOut();
	    }
	   	target.style.webkitTransform = 'translateX(' + curX + 'px)';
		}
	},
	touchMoveHandler: function(event){
    event.preventDefault();
    var target = event.target;
    var touch = event.touches[0];
    curX = touch.pageX - this.offsetLeft - 73;
    if(curX <= 0) return;
    if(curX > this.wellWidth){
    	this.elTrack.fadeOut();
    }
   	target.style.webkitTransform = 'translateX(' + curX + 'px)';
	},
	touchEndHandler: function(event) {
    this.style.webkitTransition = '-webkit-transform 0.3s ease-in';
    this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false );
    this.style.webkitTransform = 'translateX(0px)';
	}
}<commit_msg>Improving accessibility of demo2<commit_after>var Slider = function(target){
	var self = this;

	this.el = target.querySelector('.component-wrapper');
	this.elTrack = this.el.querySelector('.well');
	this.elSlider = this.el.querySelector('#slider');
	this.elButton = this.el.querySelector('.trigger-button')

	this.wellWidth = 256;
	self.valueNow = 0;

	$(this.elSlider).draggable({
		axis: 'x',
		containment: 'parent',
		cancel: false,
		start: function(event, ui) {
			console.log(ui.position.left);
		},
		drag: function(event, ui) {
			self.updateSlider(event, ui);
		},
		stop: function(event, ui) {
			if (ui.position.left < self.wellWidth) {
				self.valueNow = 0;
				$(this).animate({
					left: 0
				}).attr({
					'aria-valuenow': self.valueNow
				});
			}
		}
	});
	this.numKeypresses = 0;
	this.elSlider.addEventListener('keydown', this.keydownHandler.bind(this), false);
	this.elSlider.addEventListener('touchmove', this.touchMoveHandler.bind(this), false);
	this.elSlider.addEventListener('touchend', this.touchEndHandler.bind(this), false);
}
Slider.prototype = {
	updateSlider: function(event, ui) {
		var self = this;
		this.valueNow = Math.floor(ui.position.left / self.wellWidth * 100);
		$(event.target).attr({
			'aria-valuenow': self.valueNow
		});
		if (ui.position.left >= self.wellWidth) {
			self.transitionElements();
		}
	},
	transitionElements: function(){
		$(this.elTrack).fadeOut();
		$(this.elSlider).attr({
			'aria-hidden': 'true',
			'aria-disabled': 'true'
		});
		$(this.elButton)
			.addClass('visible')
			.removeAttr('disabled')
			.attr({
				'aria-hidden':'false',
				'aria-disabled':'false'
			});
	},
	keydownHandler: function(event){
		if(event.which === 38 || event.which === 39){
			var target = event.target;
	    this.numKeypresses++;
	    curX = this.numKeypresses * 100;
	    if(curX <= 0) return;
	    if(curX >= this.wellWidth){
	    	this.transitionElements();
	    	this.elButton.focus();
	    }
	   	target.style.webkitTransform = 'translateX(' + curX + 'px)';
		}
	},
	touchMoveHandler: function(event){
    event.preventDefault();
    var target = event.target;
    var touch = event.touches[0];
    curX = touch.pageX - this.offsetLeft - 73;
    if(curX <= 0) return;
    if(curX >= this.wellWidth){
    	$(this.elTrack).fadeOut();
    }
   	target.style.webkitTransform = 'translateX(' + curX + 'px)';
	},
	touchEndHandler: function(event) {
    this.style.webkitTransition = '-webkit-transform 0.3s ease-in';
    this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false );
    this.style.webkitTransform = 'translateX(0px)';
	}
}<|endoftext|>