<commit_before>/**
 * Model: Stylesheet
 *
 * This model is *not* backed directly by the server.
 * It is a child model of Project and is saved serialized as part of the parent
 * Project model.
 */
var Stylesheet = Backbone.Model.extend({
    initialize: function() {
        if (!this.get('data')) {
            this.set({'data': ''});
        }
    },
    validate: function() {
        if (/^[a-z0-9\-_.]+$/i.test(this.id) === false) {
            return 'Name must contain only letters, numbers, dashes, underscores and periods.';
        }
    }
});

/**
 * Collection: StylesheetList
 *
 * This collection is *not* backed directly by the server.
 * This collection is a child of the Project model. When it is updated
 * (add/remove events) it updates the attributes of its parent model as well.
 */
var StylesheetList = Backbone.Collection.extend({
    model: Stylesheet,
    initialize: function(models, options) {
        var self = this;
        this.parent = options.parent;
        this.bind('add', function() {
            this.parent.set({ 'Stylesheet': self });
            this.parent.change();
        });
        this.bind('remove', function() {
            this.parent.set({ 'Stylesheet': self });
            this.parent.change();
        });
    },
});

/**
 * View: StylesheetListView
 *
 * Display a StylesheetList collection as a set of tabs.
 */
var StylesheetListView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render', 'add', 'activate');
        var self = this;
        this.collection.bind('add', this.render);
        this.collection.bind('add', this.activate);
        this.collection.bind('remove', this.render);
        this.collection.bind('remove', this.activate);
        window.app.bind('ready', this.activate);
        this.render();
        /*
        @TODO: bind re-render to project events.
        */
    },
    render: function() {
        // Render the stylesheets wrapper if not present.
        if ($(this.el).has('.stylesheets').length === 0) {
            $(this.el).html(ich.StylesheetListView());
            $('.stylesheets', this.el).sortable({
                axis: 'x',
                revert: true,
                containment: 'parent'
                // @TODO: proper event.
                // change: TileMill.project.changed
            });
        }

        // Add a tab view for each stylesheet.
        var self = this;
        this.collection.each(function(stylesheet) {
            if (!stylesheet.view) {
                stylesheet.view = new StylesheetTabView({
                    model: stylesheet,
                    list: self
                });
                $('.stylesheets', self.el).append(stylesheet.view.el);
                self.activeTab = self.activeTab || stylesheet.view;
            }
        });
        return this;
    },
    activate: function() {
        if (this.activeTab) {
            this.activeTab.activate();
        }
    },
    events: {
        'click .tab-add': 'add'
    },
    add: function() {
        new StylesheetPopupView({collection: this.collection});
        return false;
    }
});

/**
 * View: StylesheetTabView
 *
 * Display a Stylesheet as a tab within a StylesheetListView.
 */
var StylesheetTabView = Backbone.View.extend({
    tagName: 'a',
    className: 'tab',
    initialize: function (params) {
        _.bindAll(this, 'render', 'update', 'del', 'activate', 'remove');

        // Bind an update event that stores the codemirror input contents with
        // the Stylesheet model whenever the project model validate event
        // occurs, indicating that a save/sync is imminent.
        this.model.collection.parent.bind('validate', this.update);

        this.list = params.list;
        this.input = $(ich.StylesheetTabEditor());
        this.codemirror = false;
        this.render();
    },
    render: function () {
        $(this.el).html(ich.StylesheetTabView({ id: this.model.get('id') }));
        $('#editor', this.list.el).append(this.input);
        var colorPicker = new ColorPickerToolView();
        var colorSwatches = new ColorSwatchesToolView();
        var fontPicker = new FontPickerToolView({model: new Abilities, parent: this});
        this.list.$('#tools').append(colorPicker.el);
        this.list.$('#tools').append(fontPicker.el);
        this.list.$('#tools').append(colorSwatches.el);
        return this;
    },
    events: {
        'click .name': 'activate',
        'click .tab-delete': 'del',
    },
    activate: function() {
        var self = this;

        $('#tabs .tab, #editor .editor', this.list.el).removeClass('active');
        $(this.el).addClass('active');
        $(this.input).addClass('active');
        this.list.activeTab = this;
        if (!this.codemirror) {
            this.codemirror = CodeMirror.fromTextArea($('textarea', this.input).get(0), {
                content: this.model.get('data'),
                height: '100%',
                stylesheet: 'css/code.css',
                path: 'js/codemirror/js/',
                parserfile: 'parsemss.js',
                parserConfig: window.data.reference,
                saveFunction: function() {
                    self.model.collection.parent.view.saveProject();
                },
                onChange: function() {
                    self.model.collection.parent.change();
                    // @TODO need an event that the color picker (and other
                    // editor "plugins" can bind to.
                },
                initCallback: function(cm) {
                    // @TODO need an event that the color picker (and other
                    // editor "plugins" can bind to.
                },
            });
        }
    },
    del: function() {
        window.app.loading();
        if (confirm('Are you sure you want to delete this stylesheet?')) {
            this.list.collection.remove(this.model);
            this.remove();
            window.app.done();
        }
        else {
            window.app.done();
        }
        return false;
    },
    update: function() {
        if (this.codemirror) {
            this.model.set({'data': this.codemirror.getCode()});
        }
    },
    /**
     * Override of .remove(). Removes the input editor element as well.
     */
    remove: function() {
        $(this.el).remove();
        $(this.input).remove();
        return this;
    },
});

var ColorPickerToolView = Backbone.View.extend({
    id: 'color-picker',
    className: 'pane',
    events: {
        'click a.color-picker': 'showPicker'
    },
    initialize: function() {
        _.bindAll(this, 'activate', 'showPicker');
        this.render();
        window.app.bind('ready', this.activate);
    },
    render: function() {
        $(this.el).html(ich.ColorPickerToolView);
    },
    activate: function() {
        this.$('#farbtastic').farbtastic({
            callback: 'input#color',
            width: 200,
            height: 200
        });
    },
    showPicker: function() {
        this.$('#farbtastic').toggle('fast');
        return false;
    }
});

var ColorSwatchesToolView = Backbone.View.extend({
    id: 'color-swatches',
    initialize: function() {
        this.render();
    },
    render: function() {
        $(this.el).html(ich.ColorSwatchesToolView);
    }
});

var FontPickerToolView = Backbone.View.extend({
    id: 'font-picker',
    events: {
        'change #fonts-list': 'insertFont'
    },
    initialize: function(options) {
        _.bindAll(this, 'render', 'insertFont');
        this.model.fetch({ success: this.render, error: this.render});
        this.parent = options.parent;
    },
    render: function() {
        $(this.el).html(ich.FontPickerToolView({ fonts: this.model.get('fonts') }));
    },
    insertFont: function() {
        var mirror = this.parent.codemirror;
        mirror.insertIntoLine(
          mirror.cursorPosition().line,
          mirror.cursorPosition().character, '"' + this.$('select').val() + '"');
    }
});

/**
 * View: StylesheetPopupView
 *
 * Popup form for adding a new stylesheet.
 */
var StylesheetPopupView = PopupView.extend({
    events: _.extend(PopupView.prototype.events, {
        'click input.submit': 'submit',
    }),
    initialize: function(params) {
        this.options.title = 'Add stylesheet';
        this.options.content = ich.StylesheetPopupView({}, true);
        this.render();
    },
    submit: function() {
        var id = $('input.text', this.el).val();
        var stylesheet = new Stylesheet({id: id});
        var error = stylesheet.validate();
        if (error) {
            window.app.message('Error', error);
        }
        else {
            this.collection.add(stylesheet);
            this.remove();
        }
        return false;
    }
});

<commit_msg>Cleaning up stylesheet code before working on it<commit_after>/**
 * Model: Stylesheet
 *
 * This model is *not* backed directly by the server.
 * It is a child model of Project and is saved serialized as part of the parent
 * Project model.
 */
var Stylesheet = Backbone.Model.extend({
    initialize: function() {
        if (!this.get('data')) {
            this.set({'data': ''});
        }
    },
    validate: function() {
        if (/^[a-z0-9\-_.]+$/i.test(this.id) === false) {
            return 'Name must contain only letters, numbers, dashes, underscores and periods.';
        }
    }
});

/**
 * Collection: StylesheetList
 *
 * This collection is *not* backed directly by the server.
 * This collection is a child of the Project model. When it is updated
 * (add/remove events) it updates the attributes of its parent model as well.
 */
var StylesheetList = Backbone.Collection.extend({
    model: Stylesheet,
    initialize: function(models, options) {
        var self = this;
        this.parent = options.parent;
        this.bind('add', function() {
            this.parent.set({ 'Stylesheet': self });
            this.parent.change();
        });
        this.bind('remove', function() {
            this.parent.set({ 'Stylesheet': self });
            this.parent.change();
        });
    }
});

/**
 * View: StylesheetListView
 *
 * Display a StylesheetList collection as a set of tabs.
 */
var StylesheetListView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render', 'add', 'activate');
        var self = this;
        this.collection.bind('add', this.render);
        this.collection.bind('add', this.activate);
        this.collection.bind('remove', this.render);
        this.collection.bind('remove', this.activate);
        window.app.bind('ready', this.activate);
        this.render();
        /*
        @TODO: bind re-render to project events.
        */
    },
    render: function() {
        // Render the stylesheets wrapper if not present.
        if ($(this.el).has('.stylesheets').length === 0) {
            $(this.el).html(ich.StylesheetListView());
            $('.stylesheets', this.el).sortable({
                axis: 'x',
                revert: true,
                containment: 'parent'
                // @TODO: proper event.
                // change: TileMill.project.changed
            });
        }

        // Add a tab view for each stylesheet.
        var self = this;
        this.collection.each(function(stylesheet) {
            if (!stylesheet.view) {
                stylesheet.view = new StylesheetTabView({
                    model: stylesheet,
                    list: self
                });
                $('.stylesheets', self.el).append(stylesheet.view.el);
                self.activeTab = self.activeTab || stylesheet.view;
            }
        });
        return this;
    },
    activate: function() {
        if (this.activeTab) {
            this.activeTab.activate();
        }
    },
    events: {
        'click .tab-add': 'add'
    },
    add: function() {
        new StylesheetPopupView({collection: this.collection});
        return false;
    }
});

/**
 * View: StylesheetTabView
 *
 * Display a Stylesheet as a tab within a StylesheetListView.
 */
var StylesheetTabView = Backbone.View.extend({
    tagName: 'a',
    className: 'tab',
    initialize: function(params) {
        _.bindAll(this, 'render', 'update', 'del', 'activate', 'remove');

        // Bind an update event that stores the codemirror input contents with
        // the Stylesheet model whenever the project model validate event
        // occurs, indicating that a save/sync is imminent.
        this.model.collection.parent.bind('validate', this.update);

        this.list = params.list;
        this.input = $(ich.StylesheetTabEditor());
        this.codemirror = false;
        this.render();
    },
    render: function() {
        $(this.el).html(ich.StylesheetTabView({ id: this.model.get('id') }));
        $('#editor', this.list.el).append(this.input);
        var colorPicker = new ColorPickerToolView();
        var colorSwatches = new ColorSwatchesToolView();
        var fontPicker = new FontPickerToolView({
            model: new Abilities,
            parent: this
        });
        this.list.$('#tools').append(colorPicker.el);
        this.list.$('#tools').append(fontPicker.el);
        this.list.$('#tools').append(colorSwatches.el);
        return this;
    },
    events: {
        'click .name': 'activate',
        'click .tab-delete': 'del'
    },
    activate: function() {
        var self = this;

        $('#tabs .tab, #editor .editor', this.list.el).removeClass('active');
        $(this.el).addClass('active');
        $(this.input).addClass('active');
        this.list.activeTab = this;
        if (!this.codemirror) {
            this.codemirror = CodeMirror.fromTextArea($('textarea', this.input).get(0), {
                content: this.model.get('data'),
                height: '100%',
                stylesheet: 'css/code.css',
                path: 'js/codemirror/js/',
                parserfile: 'parsemss.js',
                parserConfig: window.data.reference,
                saveFunction: function() {
                    self.model.collection.parent.view.saveProject();
                },
                onChange: function() {
                    self.model.collection.parent.change();
                    // @TODO need an event that the color picker (and other
                    // editor "plugins" can bind to.
                },
                initCallback: function(cm) {
                    // @TODO need an event that the color picker (and other
                    // editor "plugins" can bind to.
                }
            });
        }
    },
    del: function() {
        window.app.loading();
        if (confirm('Are you sure you want to delete this stylesheet?')) {
            this.list.collection.remove(this.model);
            this.remove();
            window.app.done();
        }
        else {
            window.app.done();
        }
        return false;
    },
    update: function() {
        if (this.codemirror) {
            this.model.set({'data': this.codemirror.getCode()});
        }
    },
    /**
     * Override of .remove(). Removes the input editor element as well.
     */
    remove: function() {
        $(this.el).remove();
        $(this.input).remove();
        return this;
    }
});

var ColorPickerToolView = Backbone.View.extend({
    id: 'color-picker',
    className: 'pane',
    events: {
        'click a.color-picker': 'showPicker'
    },
    initialize: function() {
        _.bindAll(this, 'activate', 'showPicker');
        this.render();
        window.app.bind('ready', this.activate);
    },
    render: function() {
        $(this.el).html(ich.ColorPickerToolView);
    },
    activate: function() {
        this.$('#farbtastic').farbtastic({
            callback: 'input#color',
            width: 200,
            height: 200
        });
    },
    showPicker: function() {
        this.$('#farbtastic').toggle('fast');
        return false;
    }
});

var ColorSwatchesToolView = Backbone.View.extend({
    id: 'color-swatches',
    initialize: function() {
        this.render();
    },
    render: function() {
        $(this.el).html(ich.ColorSwatchesToolView);
    }
});

var FontPickerToolView = Backbone.View.extend({
    id: 'font-picker',
    events: {
        'change #fonts-list': 'insertFont'
    },
    initialize: function(options) {
        _.bindAll(this, 'render', 'insertFont');
        this.model.fetch({
            success: this.render,
            error: this.render
        });
        this.parent = options.parent;
    },
    render: function() {
        $(this.el).html(ich.FontPickerToolView({
            fonts: this.model.get('fonts')
        }));
    },
    insertFont: function() {
        var mirror = this.parent.codemirror;
        mirror.insertIntoLine(
          mirror.cursorPosition().line,
          mirror.cursorPosition().character, '"' + this.$('select').val() + '"');
    }
});

/**
 * View: StylesheetPopupView
 *
 * Popup form for adding a new stylesheet.
 */
var StylesheetPopupView = PopupView.extend({
    events: _.extend(PopupView.prototype.events, {
        'click input.submit': 'submit'
    }),
    initialize: function(params) {
        this.options.title = 'Add stylesheet';
        this.options.content = ich.StylesheetPopupView({}, true);
        this.render();
    },
    submit: function() {
        var id = $('input.text', this.el).val();
        var stylesheet = new Stylesheet({id: id});
        var error = stylesheet.validate();
        if (error) {
            window.app.message('Error', error);
        }
        else {
            this.collection.add(stylesheet);
            this.remove();
        }
        return false;
    }
});

<|endoftext|>


<commit_before>require('isomorphic-fetch')

export function checkStatus(response) {
  if (response.ok) {
    return response
  }

  if (response.body || response._bodyBlob) {
    return response.json().then(err => {
      const error = new Error(response.statusText)
      error.error = err
      error.response = response

      return Promise.reject(error)
    })
  }

  return Promise.reject(response)
}

export function parseJSON(response) {
  return response.json()
}
<commit_msg>Fix for Firefox fetch api implementation<commit_after>global.fetch = undefined
require('isomorphic-fetch')

export function checkStatus(response) {
  if (response.ok) {
    return response
  }

  if (response.body || response._bodyBlob) {
    return response.json().then(err => {
      const error = new Error(response.statusText)
      error.error = err
      error.response = response

      return Promise.reject(error)
    })
  }

  return Promise.reject(response)
}

export function parseJSON(response) {
  return response.json()
}
<|endoftext|>


<commit_before>import app from '../app'
import React from 'react'
import debug from 'debug'
import fetch from 'node-fetch'
import Html from '../components/Html'
import { Router } from 'react-router'
import serialize from 'serialize-javascript'
import routes from '../components/routes.jsx'
import Location from 'react-router/lib/Location'
import { createElementWithContext } from 'fluxible-addons-react'
import navigateAction from '../actions/navigateAction'

const log = debug('bshed:client:renderer')
export default function renderer ({ scripts=[], styles=[] }={}) {
  return function * rendererMiddleware () {
    const rootUrl = `${this.protocol}://${this.host}`
    const cookie = this.get('cookie')

    log('creating context')
    const context = app.createContext({ fetch, rootUrl, cookie })

    log('running router')
    const location = new Location(this.url, this.query)
    const state = yield runRouter({ location })

    log('running navigateAction')
    yield context.executeAction(navigateAction, { location, ...state })

    log('generating state')
    const appState = `window.BSHED=${serialize(app.dehydrate(context))}`

    log('generating markup')
    const markup = React.renderToString(createElementWithContext(context, state))

    log('generating html')
    const html = React.renderToStaticMarkup(
      <Html
        state={appState}
        markup={markup}
        styles={styles}
        scripts={scripts}
      />
    )

    log('sending response')
    this.status = 200
    this.type = 'html'
    this.body = `<!DOCTYPE html>${html}`
  }
}

function runRouter ({ location }) {
  return new Promise((resolve, reject) => {
    Router.run(routes, location, (error, state) => {
      error ? reject(error) : resolve(state)
    })
  })
}

<commit_msg>Organize module order<commit_after>import app from '../app'
import React from 'react'
import debug from 'debug'
import fetch from 'node-fetch'
import Html from '../components/Html'
import { Router } from 'react-router'
import serialize from 'serialize-javascript'
import routes from '../components/routes.jsx'
import Location from 'react-router/lib/Location'
import navigateAction from '../actions/navigateAction'
import { createElementWithContext } from 'fluxible-addons-react'

const log = debug('bshed:client:renderer')
export default function renderer ({ scripts=[], styles=[] }={}) {
  return function * rendererMiddleware () {
    const rootUrl = `${this.protocol}://${this.host}`
    const cookie = this.get('cookie')

    log('creating context')
    const context = app.createContext({ fetch, rootUrl, cookie })

    log('running router')
    const location = new Location(this.url, this.query)
    const state = yield runRouter({ location })

    log('running navigateAction')
    yield context.executeAction(navigateAction, { location, ...state })

    log('generating state')
    const appState = `window.BSHED=${serialize(app.dehydrate(context))}`

    log('generating markup')
    const markup = React.renderToString(createElementWithContext(context, state))

    log('generating html')
    const html = React.renderToStaticMarkup(
      <Html
        state={appState}
        markup={markup}
        styles={styles}
        scripts={scripts}
      />
    )

    log('sending response')
    this.status = 200
    this.type = 'html'
    this.body = `<!DOCTYPE html>${html}`
  }
}

function runRouter ({ location }) {
  return new Promise((resolve, reject) => {
    Router.run(routes, location, (error, state) => {
      error ? reject(error) : resolve(state)
    })
  })
}

<|endoftext|>


<commit_before>import { Chart } from '../../../shared/model/chart'
import axios from 'axios'

import { GET_USERCHARTS } from './types'

const serverHost = 'localhost'
const serverPort = '5000'
const baseUrl = `http://${serverHost}:${serverPort}/api`

const getUserCharts = (userId) => {
  if (!userId) {
    return { type: GET_USERCHARTS }
  }
  const request = axios.get(`${baseUrl}/users/${userId}/charts`)
  return {
    type: GET_USERCHARTS,
    payload: request
  }
}

module.exports = {
  getUserCharts,
}<commit_msg>Update path to chart model.<commit_after>import Chart from '../../../shared/src/model/chart'
import axios from 'axios'

import { GET_USERCHARTS } from './types'

const serverHost = 'localhost'
const serverPort = '5000'
const baseUrl = `http://${serverHost}:${serverPort}/api`

const getUserCharts = (userId) => {
  if (!userId) {
    return { type: GET_USERCHARTS }
  }
  const request = axios.get(`${baseUrl}/users/${userId}/charts`)
  return {
    type: GET_USERCHARTS,
    payload: request
  }
}

module.exports = {
  getUserCharts,
}<|endoftext|>


<commit_before>Template.results.events({
    'submit form': function(event){
        var movie = document.querySelector('input[name="movie"]:checked').value;
        var id = document.querySelector('input[name="movie"]:checked').id;
        if (Movies.findOne({text: movie}) == undefined) {
            var mg = '
Movie was successfully requested! Want to search again?
'
            document.getElementById("info").setAttribute("class", "alert alert-success");
            document.getElementById("info").innerHTML = mg;

            var mg = ""
            document.getElementById("overview").innerHTML = mg;

            var list = document.getElementById("results");
            while (list.firstChild) {
                    list.removeChild(list.firstChild);
            }

            Meteor.call('addMovie', movie);
            Meteor.call('pushBullet', movie);
            return false;
        } else {
            var mg = '
Movie has alrady been requested! Request another movie?
';
            document.getElementById("info").setAttribute("class", "alert alert-warning");
            document.getElementById("info").innerHTML = mg;

            var mg = ""
            document.getElementById("overview").innerHTML = mg;

            var list = document.getElementById("results");
            while (list.firstChild) {
                    list.removeChild(list.firstChild);
            }
            return false }

}})<commit_msg>Set session variables, cleaned up code<commit_after>Template.body.events({
    "submit .results": function (event) {
        Session.set('searchingresults', false);
        Session.set('resultsloaded', false);

        var movie = document.querySelector('input[name="movie"]:checked').value;
        var id = document.querySelector('input[name="movie"]:checked').id;

        if (Movies.findOne({text: movie}) === undefined) {
            document.getElementById("info").setAttribute("class", "alert alert-success");
            document.getElementById("info").innerHTML = '
Movie was successfully requested! Want to search again?
';
            document.getElementById("overview").innerHTML = "";

            Meteor.call('addMovie', movie, id);
            Meteor.call('pushBullet', movie);

            return false;
        } else {
            document.getElementById("info").setAttribute("class", "alert alert-warning");
            document.getElementById("info").innerHTML = '
Movie has alrady been requested! Request another movie?
';
            document.getElementById("overview").innerHTML = "";

            return false;
        }
    }
});<|endoftext|>


<commit_before>define(['./getputdelete', './util'], function (getputdelete, util) {

  "use strict";

  var prefix = 'remote_storage_wire_';

  var events = util.getEventEmitter('connected', 'error');

  function set(key, value) {
    localStorage.setItem(prefix+key, JSON.stringify(value));

    if(getState() == 'connected') {
      events.emit('connected');
    }
  }
  function remove(key) {
    localStorage.removeItem(prefix+key);
  }
  function get(key) {
    var valStr = localStorage.getItem(prefix+key);
    if(typeof(valStr) == 'string') {
      try {
        return JSON.parse(valStr);
      } catch(e) {
        localStorage.removeItem(prefix+key);
      }
    }
    return null;
  }
  function disconnectRemote() {
    remove('storageType');
    remove('storageHref');
    remove('bearerToken');
  }
  function getState() {
    if(get('storageType') && get('storageHref')) {
      if(get('bearerToken')) {
        return 'connected';
      } else {
        return 'authing';
      }
    } else {
      return 'anonymous';
    }
  }
  function on(eventType, cb) {
    if(eventType == 'error') {
      errorCbs.push(cb);
    } else if(eventType == 'connected') {
      connectedCbs.push(cb);
    } else {
      throw "Unknown eventType: " + eventType;
    }
  }

  function resolveKey(storageType, storageHref, basePath, relPath) {
    var item = ((basePath.length?(basePath + '/'):'') + relPath);
    return storageHref + item;
  }
  function setChain(driver, hashMap, mimeType, token, cb, timestamp) {
    var i;
    for(i in hashMap) {
      break;
    }
    if(i) {
      var thisOne = hashMap[i];
      delete hashMap[i];
      driver.set(i, thisOne, mimeType, token, function(err, timestamp) {
        if(err) {
          cb(err);
        } else {
          setChain(driver, hashMap, mimeType, token, cb, timestamp);
        }
      });
    } else {
      cb(null, timestamp);
    }
  }

  // Namespace: wireClient
  //
  // The wireClient stores the user's storage information and controls getputdelete accordingly.
  //
  // Event: connected
  //
  // Fired once everything is configured.
  return {

    // Method: get
    //
    // Get data from given path from remotestorage
    //
    // Parameters:
    //   path     - absolute path (starting from storage root)
    //   callback - see <getputdelete.get> for details on the callback parameters
    get: function (path, cb) {
      var storageType = get('storageType'),
        storageHref = get('storageHref'),
        token = get('bearerToken');
      if(typeof(path) != 'string') {
        cb('argument "path" should be a string');
      } else {
        getputdelete.get(resolveKey(storageType, storageHref, '', path), token, cb);
      }
    },

    // Method: set
    //
    // Write data to given path in remotestorage
    //
    // Parameters:
    //   path     - absolute path (starting from storage root)
    //   valueStr - raw data to write
    //   mimeType - MIME type to set as Content-Type header
    //   callback - see <getputdelete.set> for details on the callback parameters.
    set: function (path, valueStr, mimeType, cb) {
      var storageType = get('storageType'),
        storageHref = get('storageHref'),
        token = get('bearerToken');
      if(typeof(path) != 'string') {
        cb('argument "path" should be a string');
      } else {
        getputdelete.set(resolveKey(storageType, storageHref, '', path), valueStr, mimeType, token, cb);
      }
    },

    // Method: setStorageInfo
    //
    // Configure wireClient.
    //
    // Parameters:
    //   type - the storage type (see specification)
    //   href - base URL of the storage server
    //
    // Fires:
    //   configured - if wireClient is now fully configured
    //
    setStorageInfo   : function(type, href) { set('storageType', type); set('storageHref', href); },

    // Method: getStorageHref
    //
    // Get base URL of the user's remotestorage.
    getStorageHref   : function() { return get('storageHref') },

    // Method: SetBearerToken
    //
    // Set the bearer token for authorization
    //
    // Parameters:
    //   bearerToken - token to use
    //
    // Fires:
    //   configured - if wireClient is now fully configured.
    //
    setBearerToken   : function(bearerToken) { set('bearerToken', bearerToken); },

    // Method: disconnectRemote
    //
    // Clear the wireClient configuration
    disconnectRemote : disconnectRemote,

    // Method: on
    //
    // Install an event handler
    //
    //
    on               : on,

    // Method: getState
    //
    // Get current state.
    //
    // Possible states are:
    //   anonymous - no information set
    //   authing   - storage's type & href set, but no token received yet
    //   connected - all information present.
    getState         : getState
  };
});
<commit_msg>fixed wireClient.on<commit_after>define(['./getputdelete', './util'], function (getputdelete, util) {

  "use strict";

  var prefix = 'remote_storage_wire_';

  var events = util.getEventEmitter('connected', 'error');

  function set(key, value) {
    localStorage.setItem(prefix+key, JSON.stringify(value));

    if(getState() == 'connected') {
      events.emit('connected');
    }
  }
  function remove(key) {
    localStorage.removeItem(prefix+key);
  }
  function get(key) {
    var valStr = localStorage.getItem(prefix+key);
    if(typeof(valStr) == 'string') {
      try {
        return JSON.parse(valStr);
      } catch(e) {
        localStorage.removeItem(prefix+key);
      }
    }
    return null;
  }
  function disconnectRemote() {
    remove('storageType');
    remove('storageHref');
    remove('bearerToken');
  }
  function getState() {
    if(get('storageType') && get('storageHref')) {
      if(get('bearerToken')) {
        return 'connected';
      } else {
        return 'authing';
      }
    } else {
      return 'anonymous';
    }
  }
  function on(eventType, cb) {
    events.on(eventType, cb);
  }

  function resolveKey(storageType, storageHref, basePath, relPath) {
    var item = ((basePath.length?(basePath + '/'):'') + relPath);
    return storageHref + item;
  }
  function setChain(driver, hashMap, mimeType, token, cb, timestamp) {
    var i;
    for(i in hashMap) {
      break;
    }
    if(i) {
      var thisOne = hashMap[i];
      delete hashMap[i];
      driver.set(i, thisOne, mimeType, token, function(err, timestamp) {
        if(err) {
          cb(err);
        } else {
          setChain(driver, hashMap, mimeType, token, cb, timestamp);
        }
      });
    } else {
      cb(null, timestamp);
    }
  }

  // Namespace: wireClient
  //
  // The wireClient stores the user's storage information and controls getputdelete accordingly.
  //
  // Event: connected
  //
  // Fired once everything is configured.
  return {

    // Method: get
    //
    // Get data from given path from remotestorage
    //
    // Parameters:
    //   path     - absolute path (starting from storage root)
    //   callback - see <getputdelete.get> for details on the callback parameters
    get: function (path, cb) {
      var storageType = get('storageType'),
        storageHref = get('storageHref'),
        token = get('bearerToken');
      if(typeof(path) != 'string') {
        cb('argument "path" should be a string');
      } else {
        getputdelete.get(resolveKey(storageType, storageHref, '', path), token, cb);
      }
    },

    // Method: set
    //
    // Write data to given path in remotestorage
    //
    // Parameters:
    //   path     - absolute path (starting from storage root)
    //   valueStr - raw data to write
    //   mimeType - MIME type to set as Content-Type header
    //   callback - see <getputdelete.set> for details on the callback parameters.
    set: function (path, valueStr, mimeType, cb) {
      var storageType = get('storageType'),
        storageHref = get('storageHref'),
        token = get('bearerToken');
      if(typeof(path) != 'string') {
        cb('argument "path" should be a string');
      } else {
        getputdelete.set(resolveKey(storageType, storageHref, '', path), valueStr, mimeType, token, cb);
      }
    },

    // Method: setStorageInfo
    //
    // Configure wireClient.
    //
    // Parameters:
    //   type - the storage type (see specification)
    //   href - base URL of the storage server
    //
    // Fires:
    //   configured - if wireClient is now fully configured
    //
    setStorageInfo   : function(type, href) { set('storageType', type); set('storageHref', href); },

    // Method: getStorageHref
    //
    // Get base URL of the user's remotestorage.
    getStorageHref   : function() { return get('storageHref') },

    // Method: SetBearerToken
    //
    // Set the bearer token for authorization
    //
    // Parameters:
    //   bearerToken - token to use
    //
    // Fires:
    //   configured - if wireClient is now fully configured.
    //
    setBearerToken   : function(bearerToken) { set('bearerToken', bearerToken); },

    // Method: disconnectRemote
    //
    // Clear the wireClient configuration
    disconnectRemote : disconnectRemote,

    // Method: on
    //
    // Install an event handler
    //
    //
    on               : on,

    // Method: getState
    //
    // Get current state.
    //
    // Possible states are:
    //   anonymous - no information set
    //   authing   - storage's type & href set, but no token received yet
    //   connected - all information present.
    getState         : getState
  };
});
<|endoftext|>


<commit_before>import "./jquery-bootstrap";
import Vue from "vue/dist/vue.esm.js";
import "./lib/moment";
import Sortable from "sortablejs";

window.Vue = Vue;
window.Sortable = Sortable;
<commit_msg>refactor: updated vue syntax<commit_after>import "./jquery-bootstrap";
import { createApp } from "vue";
import "./lib/moment";
import Sortable from "sortablejs";

window.Vue = createApp;
window.Sortable = Sortable;
<|endoftext|>


<commit_before>//Na vrhu gulpfile.js datoteke pišemo sve module koje ćemo koristiti
var gulp = require('gulp');

var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var webserver = require('gulp-webserver');
//concat-vendor služi za spajanje stranih biblioteka koje preuzimamo putem bower alata
var concatVendor = require('gulp-concat-vendor');
//sass kompajler i css obrađivači
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var concatCss = require('gulp-concat-css');
//jshint
var jshint = require('gulp-jshint');

var sources = [
	'app/app.module.js',
	// 'app/components/place/place.module.js',
	// 'app/components/company/company.module.js',
	// 'app/components/employee/employee.module.js',
	'app/**/*.js'
];

gulp.task('vendorScripts', function() {
	return gulp.src('assets/js/*')
		.pipe(concatVendor('vendor.min.js'))
		.pipe(uglify())
		.pipe(gulp.dest('dist'))
});

gulp.task('scripts', function() {
	return gulp.src(sources)
		.pipe(concat('all.min.js'))
		.pipe(uglify())
		.pipe(gulp.dest('dist'));
});

gulp.task('webserver', function() {
  gulp.src('.')
    .pipe(webserver({
      livereload: true,
      open: true
    }));
});

gulp.task('sass', function () {
    gulp.src('assets/sass/**/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('assets/css'));
});

 gulp.task('minCss', ['sass'], function() {
	gulp.src('assets/css/**/*.css')
		.pipe(concatCss("all.min.css"))
        .pipe(minifyCss())
        .pipe(gulp.dest('dist'));
});

// gulp.task('sass:watch', function () {
//     gulp.watch(['assets/sass/**/*.scss', 'assets/css/**/*.css'], ['minCss']);
// });

gulp.task('lint', function() {
    gulp.src('app/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('watch', function() {
	gulp.watch('app/**/*.js', ['lint'/*, 'scripts'*/]);
});

gulp.task('default', ['lint', /*'vendorScripts', 'scripts', */'watch', 'minCss', /*'sass:watch'*/, 'webserver']);
<commit_msg>Fixed double comma in default gulp task<commit_after>//Na vrhu gulpfile.js datoteke pišemo sve module koje ćemo koristiti
var gulp = require('gulp');

var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var webserver = require('gulp-webserver');
//concat-vendor služi za spajanje stranih biblioteka koje preuzimamo putem bower alata
var concatVendor = require('gulp-concat-vendor');
//sass kompajler i css obrađivači
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var concatCss = require('gulp-concat-css');
//jshint
var jshint = require('gulp-jshint');

var sources = [
	'app/app.module.js',
	// 'app/components/place/place.module.js',
	// 'app/components/company/company.module.js',
	// 'app/components/employee/employee.module.js',
	'app/**/*.js'
];

gulp.task('vendorScripts', function() {
	return gulp.src('assets/js/*')
		.pipe(concatVendor('vendor.min.js'))
		.pipe(uglify())
		.pipe(gulp.dest('dist'))
});

gulp.task('scripts', function() {
	return gulp.src(sources)
		.pipe(concat('all.min.js'))
		.pipe(uglify())
		.pipe(gulp.dest('dist'));
});

gulp.task('webserver', function() {
  gulp.src('.')
    .pipe(webserver({
      livereload: true,
      open: true
    }));
});

gulp.task('sass', function () {
    gulp.src('assets/sass/**/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('assets/css'));
});

 gulp.task('minCss', ['sass'], function() {
	gulp.src('assets/css/**/*.css')
		.pipe(concatCss("all.min.css"))
        .pipe(minifyCss())
        .pipe(gulp.dest('dist'));
});

// gulp.task('sass:watch', function () {
//     gulp.watch(['assets/sass/**/*.scss', 'assets/css/**/*.css'], ['minCss']);
// });

gulp.task('lint', function() {
    gulp.src('app/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('watch', function() {
	gulp.watch('app/**/*.js', ['lint'/*, 'scripts'*/]);
});

gulp.task('default', ['lint', /*'vendorScripts', 'scripts', */'watch', 'minCss', /*'sass:watch'*/ 'webserver']);
<|endoftext|>


<commit_before>// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require('jasmine-spec-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  onPrepare() {
    require('ts-node').register({
      project: require('path').join(__dirname, './tsconfig.e2e.json')
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};
<commit_msg>Add firefox and ie to protractor capable browsers<commit_after>// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require('jasmine-spec-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/**/*.e2e-spec.ts'
  ],
  multiCapabilities: [
    { 'browserName': 'firefox' },
    { 'browserName': 'chrome' },
    { 'browserName': 'internet explorer' }
  ],
  seleniumAddress: 'http://localhost:4444/wd/hub',
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  onPrepare() {
    require('ts-node').register({
      project: require('path').join(__dirname, './tsconfig.e2e.json')
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
  plumber = require('gulp-plumber'),
  rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var ngmin = require('gulp-ngmin');
var inject = require('gulp-inject');
var flatten = require('gulp-flatten');
var minifycss = require('gulp-minify-css');
var angularFilesort = require('gulp-angular-filesort');
var templateCache = require('gulp-angular-templatecache');
var sass = require('gulp-sass');
var wiredep = require('wiredep');
var gls = require('gulp-live-server');
var exec = require('child_process').exec;

gulp.task('vendor-scripts', function() {

  return gulp.src(wiredep().js)

  .pipe(gulp.dest('dist/vendor'));

});

gulp.task('vendor-css', function() {

  return gulp.src(wiredep().css)

  .pipe(gulp.dest('dist/vendor'));

});

gulp.task('vendor-fonts', function() {
  return gulp.src('./**/*.woff2')
    .pipe(flatten())
    .pipe(gulp.dest('dist/fonts'));

});

gulp.task('sass', function() {
  return gulp.src(['app/assets/**/*.sass'])
    .pipe(plumber({
      errorHandler: function(error) {
        console.log(error.message);
        this.emit('end');
      }
    }))
    .pipe(sass())
    .pipe(autoprefixer('last 2 versions'))
    .pipe(gulp.dest('dev/assets/'));
});

gulp.task('styles', ['sass'], function() {
  return gulp.src(['dev/assets/**/*.css'])
    .pipe(plumber({
      errorHandler: function(error) {
        console.log(error.message);
        this.emit('end');
      }
    }))
    .pipe(gulp.dest('dist/styles/'))
    // .pipe(rename({
    // suffix: '.min'
    // }))
    .pipe(minifycss())
    .pipe(gulp.dest('dist/styles/'));
});

gulp.task('scripts', function() {
  return gulp.src('dev/src/**/*.js')
    .pipe(angularFilesort())
    .pipe(concat('main.js'))
    .pipe(uglify({
      mangle: false
    }))
    .pipe(gulp.dest('dist/scripts/'));
});

gulp.task('dev-scripts', function() {
  return gulp.src(['app/src/**/*.js', 'app/src/templates.js'])
    .pipe(plumber({
      errorHandler: function(error) {
        console.log(error.message);
        this.emit('end');
      }
    }))
    .pipe(gulp.dest('dev/src/'))
});

gulp.task('templates', function() {
  return gulp.src(['app/**/*.html', '!/**/index.html'])
    .pipe(templateCache('templates.js', {
      module: 'TwitchCaster'
    }))
    .pipe(gulp.dest('dev/src/'));
});

gulp.task('html', function() {
  return gulp.src('app/*.html')
    .pipe(gulp.dest('dev/'))
});

gulp.task('dist', [
    'html',
    'templates',
    'dev-scripts',
    'scripts',
    'styles',
    'vendor-scripts',
    'vendor-css',
    'vendor-fonts'
  ],
  function() {

    return gulp.src('app/index.html')
      .pipe(wiredep.stream({
        fileTypes: {
          html: {
            replace: {
              js: function(filePath) {
                return '<script src="' + 'vendor/' + filePath.split('/')
                  .pop() + '"></script>';
              },
              css: function(filePath) {
                return '<link rel="stylesheet" href="' + 'vendor/' +
                  filePath.split('/').pop() + '"/>';
              }
            }
          }
        }
      }))
      .pipe(inject(
        gulp.src(['dist/scripts/**/*.js'], {
          read: false
        }), {
          addRootSlash: false,
          transform: function(filePath, file, i, length) {
            return '<script src="' + filePath.replace('dist/', '') +
              '"></script>';
          }
        }))

    .pipe(inject(
      gulp.src(['dist/styles/**/*.css'], {
        read: false
      }), {
        addRootSlash: false,
        transform: function(filePath, file, i, length) {
          return '<link rel="stylesheet" href="' + filePath.replace(
            'dist/', '') + '"/>';
        }
      }))

    .pipe(gulp.dest('dist'));
  });

gulp.task('watch', function() {
  gulp.watch(['./app/**/*'], {
    interval: 1000,
    mode: 'poll'
  }, ['dist']);
});
<commit_msg>Fixed task sync Just understood it was asynchronous<commit_after>'use strict';

var gulp = require('gulp'),
  plumber = require('gulp-plumber'),
  rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var ngmin = require('gulp-ngmin');
var inject = require('gulp-inject');
var flatten = require('gulp-flatten');
var minifycss = require('gulp-minify-css');
var angularFilesort = require('gulp-angular-filesort');
var templateCache = require('gulp-angular-templatecache');
var sass = require('gulp-sass');
var wiredep = require('wiredep');
var gls = require('gulp-live-server');
var exec = require('child_process').exec;

gulp.task('vendor-scripts', function() {

  return gulp.src(wiredep().js)

  .pipe(gulp.dest('dist/vendor'));

});

gulp.task('vendor-css', function() {

  return gulp.src(wiredep().css)

  .pipe(gulp.dest('dist/vendor'));

});

gulp.task('vendor-fonts', function() {
  return gulp.src('./**/*.woff2')
    .pipe(flatten())
    .pipe(gulp.dest('dist/fonts'));

});

gulp.task('sass', function() {
  return gulp.src(['app/assets/**/*.sass'])
    .pipe(plumber({
      errorHandler: function(error) {
        console.log(error.message);
        this.emit('end');
      }
    }))
    .pipe(sass())
    .pipe(autoprefixer('last 2 versions'))
    .pipe(gulp.dest('dev/assets/'));
});

gulp.task('styles', ['sass'], function() {
  return gulp.src(['dev/assets/**/*.css'])
    .pipe(plumber({
      errorHandler: function(error) {
        console.log(error.message);
        this.emit('end');
      }
    }))
    .pipe(gulp.dest('dist/styles/'))
    // .pipe(rename({
    // suffix: '.min'
    // }))
    .pipe(minifycss())
    .pipe(gulp.dest('dist/styles/'));
});

gulp.task('scripts', ['dev-scripts'], function() {
  return gulp.src(['dev/src/**/*.js', 'dev/src/templates.js'])
    .pipe(angularFilesort())
    .pipe(concat('main.js'))
    .pipe(uglify({
      mangle: false
    }))
    .pipe(gulp.dest('dist/scripts/'));
});

gulp.task('dev-scripts', function() {
  return gulp.src('app/src/**/*.js')
    .pipe(plumber({
      errorHandler: function(error) {
        console.log(error.message);
        this.emit('end');
      }
    }))
    .pipe(gulp.dest('dev/src/'))
});

gulp.task('templates', function() {
  return gulp.src(['app/**/*.html', '!/**/index.html'])
    .pipe(templateCache('templates.js', {
      module: 'TwitchCaster'
    }))
    .pipe(gulp.dest('dev/src/'));
});

gulp.task('html', function() {
  return gulp.src('app/*.html')
    .pipe(gulp.dest('dev/'))
});

gulp.task('dist', [
    'html',
    'templates',
    'scripts',
    'styles',
    'vendor-scripts',
    'vendor-css',
    'vendor-fonts'
  ],
  function() {

    return gulp.src('app/index.html')
      .pipe(wiredep.stream({
        fileTypes: {
          html: {
            replace: {
              js: function(filePath) {
                return '<script src="' + 'vendor/' + filePath.split('/')
                  .pop() + '"></script>';
              },
              css: function(filePath) {
                return '<link rel="stylesheet" href="' + 'vendor/' +
                  filePath.split('/').pop() + '"/>';
              }
            }
          }
        }
      }))
      .pipe(inject(
        gulp.src(['dist/scripts/**/*.js'], {
          read: false
        }), {
          addRootSlash: false,
          transform: function(filePath, file, i, length) {
            return '<script src="' + filePath.replace('dist/', '') +
              '"></script>';
          }
        }))

    .pipe(inject(
      gulp.src(['dist/styles/**/*.css'], {
        read: false
      }), {
        addRootSlash: false,
        transform: function(filePath, file, i, length) {
          return '<link rel="stylesheet" href="' + filePath.replace(
            'dist/', '') + '"/>';
        }
      }))

    .pipe(gulp.dest('dist'));
  });

gulp.task('watch', function() {
  gulp.watch(['./app/**/*'], {
    interval: 1000,
    mode: 'poll'
  }, ['dist']);
});
<|endoftext|>


<commit_before>var Backbone = require('backbone'),
    template = require("../templates/feedback-form.hbs"),
    forms = require("../forms"),
    $ = require('jquery'),
    nationality = require('../models/nationality'),
    service = require('../models/service'),
    servicearea = require('../models/servicearea'),
    models = require('../models/models')
    i18n = require('i18next-client');

module.exports = Backbone.View.extend({
    initialize: function(opts){
        var $el = this.$el,
            self = this;
        self.nationalities = [];
        self.serviceareas = [];

        var public_services = new models.service.PublicServices();

        var waiting = [
            models.preloaded,
            public_services.fetch({data:{id: opts.id}})
        ];

        Promise.all(waiting).then(function(results){
            self.serviceareas = results[0].servicearea.data();
            self.nationalities = results[0].nationality.data();

            self.service = public_services.models[0];
            self.service.loadSubModels().then(function(){
                self.service = self.service.data();
                self.render();
            });
        }, function onerror(error) {
            messages.error(error);
            console.error("Unlogged errors:");
            console.error(error);
        });
    },

    populateDropdowns: function() {
        var $form = this.$el.find('form');
        forms.populateDropdown($form, "area_of_residence", this.serviceareas);
        forms.populateDropdown($form, "nationality", this.nationalities);
    },

    render: function() {
        var context = {
            service: this.service,
            starvalues: [5, 4, 3, 2, 1]
        };

        this.$el.html(template(context));
        this.$el.i18n();
        this.populateDropdowns();

        // hide the conditional ones to start
        $('.ifdelivered, .ifnotdelivered, #row_other_difficulties').hide();
    },

    events: {
        "change [name=delivered]": function() {
            var delivered = $('[name=delivered]:checked').val() === "1";
            $('.ifdelivered').toggle(delivered);
            $('.ifnotdelivered').toggle(!delivered);
        },
        "change [name=difficulty_contacting]": function() {
            var difficulty = $("#id_difficulty_contacting option:selected").val();
            $('#row_other_difficulties').toggle(difficulty === 'other');
        },
        "click .form-btn-submit": function() {
            var $el = this.$el;
            var data = forms.collect($el);
            var $submit = $el.find('.form-btn-submit');
            $submit.attr('disabled', 'disabled');
            $el.find('.error').text('');
            var errors = {};
            forms.submit($el, 'api/feedback/', data, errors).then(
                function success(data) {
                    $submit.removeAttr('disabled');
                    window.location = '#/feedback/confirm';
                },
                function error(errors) {
                    $submit.removeAttr('disabled');
                    // forms.js has already displayed any errors
                }
            );
        },
        "click .form-btn-clear": function() {
            this.$el.find('[name]').each(function() {
                var $field = $(this);
                $field.val('');
            });
            return false;
        }
    }
});
<commit_msg>Remove unused event handlers<commit_after>var Backbone = require('backbone'),
    template = require("../templates/feedback-form.hbs"),
    forms = require("../forms"),
    $ = require('jquery'),
    nationality = require('../models/nationality'),
    service = require('../models/service'),
    servicearea = require('../models/servicearea'),
    models = require('../models/models')
    i18n = require('i18next-client');

module.exports = Backbone.View.extend({
    initialize: function(opts){
        var $el = this.$el,
            self = this;
        self.nationalities = [];
        self.serviceareas = [];

        var public_services = new models.service.PublicServices();

        var waiting = [
            models.preloaded,
            public_services.fetch({data:{id: opts.id}})
        ];

        Promise.all(waiting).then(function(results){
            self.serviceareas = results[0].servicearea.data();
            self.nationalities = results[0].nationality.data();

            self.service = public_services.models[0];
            self.service.loadSubModels().then(function(){
                self.service = self.service.data();
                self.render();
            });
        }, function onerror(error) {
            messages.error(error);
            console.error("Unlogged errors:");
            console.error(error);
        });
    },

    populateDropdowns: function() {
        var $form = this.$el.find('form');
        forms.populateDropdown($form, "area_of_residence", this.serviceareas);
        forms.populateDropdown($form, "nationality", this.nationalities);
    },

    render: function() {
        var context = {
            service: this.service,
            starvalues: [5, 4, 3, 2, 1]
        };

        this.$el.html(template(context));
        this.$el.i18n();
        this.populateDropdowns();

        // hide the conditional ones to start
        $('.ifdelivered, .ifnotdelivered, #row_other_difficulties').hide();
    },

    events: {
        "click .form-btn-submit": function() {
            var $el = this.$el;
            var data = forms.collect($el);
            var $submit = $el.find('.form-btn-submit');
            $submit.attr('disabled', 'disabled');
            $el.find('.error').text('');
            var errors = {};
            forms.submit($el, 'api/feedback/', data, errors).then(
                function success(data) {
                    $submit.removeAttr('disabled');
                    window.location = '#/feedback/confirm';
                },
                function error(errors) {
                    $submit.removeAttr('disabled');
                    // forms.js has already displayed any errors
                }
            );
        },
        "click .form-btn-clear": function() {
            this.$el.find('[name]').each(function() {
                var $field = $(this);
                $field.val('');
            });
            return false;
        }
    }
});
<|endoftext|>


<commit_before>angular.module('app.shopitems', ['ui.router'])

//---------------
// Services
//---------------

        .factory('Shopitems', ['$resource', 'BASE_URI', function($resource, BASE_URI){
          return $resource(BASE_URI+'api/shopitems/:id', null, {
	    'update': { method:'PUT' }
	  });
        }])

        .factory('Frequentshopitems', ['$resource', 'BASE_URI', function($resource, BASE_URI){
          return $resource(BASE_URI+'api/frequentshopitems/');
        }])

        .factory('retrieveShopitems', ['UserService', 'Shopitems', '$q', function(UserService, Shopitems, $q){

    			var containsObj = function(array, obj) {
      			var i, l = array.length;
      			for (i=0;i<array.length;i++)
      			{
        			if (angular.equals(array[i], obj)) return i;
      			}
      			return false;
    			}, retrieve = function(pauseExecution){
      			var deferred = $q.defer();
						Shopitems.query(function(response) {
						  var uniqueIngredients = [];
						  var uniqueIngredientsTemp = [];
						  var user = UserService.getCurrentLoginUser();
						  for(i=0;i<response.length;i++){
						    if ( response[i].ingredient ) {
						      var order = user.settings.categoryOrder.indexOf(response[i].ingredient.category) >= 0 ? user.settings.categoryOrder.indexOf(response[i].ingredient.category) : 99999;
						    } else {
						      var order = 99999;
						    }
						    var obj = {ingredient:response[i].ingredient, unit:response[i].unit, order: order, completed: response[i].completed};
						    var index = containsObj(uniqueIngredientsTemp, obj);
						    if ( index === false) {
						      uniqueIngredientsTemp.push({ingredient:response[i].ingredient, unit:response[i].unit, order: order, completed: response[i].completed});
						      obj.details = [response[i]];
						      obj.amount = response[i].amount;
						      uniqueIngredients.push(obj);
						    }
						    else {
						      uniqueIngredients[index].details.push(response[i]);
						      uniqueIngredients[index].amount = response[i].amount + uniqueIngredients[index].amount;
						    }
						  }
						 	deferred.resolve(uniqueIngredients);
		        });
		        return deferred.promise;
		      };

		      return {
            retrieve: retrieve
        	}
		    }])

//---------------
// Controllers
//---------------

// Shopitems

    .controller('ShopitemsController', ['$scope', '$stateParams', '$uibModal', 'shopitems', 'retrieveShopitems', 'Shopitems', 'frequentshopitems', 'TAIngredients', 'units', '$state', '$filter', '$timeout', function ($scope, $stateParams, $uibModal, shopitems, retrieveShopitems, Shopitems, frequentshopitems, TAIngredients, units, $state, $filter, $timeout) {

      $scope.units = units;
      $scope.shopitems = shopitems;
      $scope.frequentshopitems = frequentshopitems;
	    $scope.pauseAutoupdate = false;

      $scope.autoupdate = true;

      $scope.alerts = [];
      $scope.status = [];
			for(i=0;i<$scope.shopitems.length;i++){
				$scope.status[$scope.shopitems[i].ingredient.category] = true;
			}

      containsObj = function(array, obj) {
        var i, l = array.length;
        for (i=0;i<array.length;i++)
        {
          if (angular.equals(array[i], obj)) return i;
        }
        return false;
      };

      var timer;
      $scope.startAutoupdate = function() {
				$scope.autoupdate = true;
				if (!$scope.pauseAutoupdate){
					retrieveShopitems.retrieve().then( function(data){
						if (data) $scope.shopitems = data;
					});
				}
				timer =  $timeout(function () {
          $scope.startAutoupdate();
        }, 5000);
				$scope.$on( "$destroy",
					function( event ) {
						$timeout.cancel( timer );
					}
				);
      };

      $scope.stopAutoupdate = function(){
				$scope.autoupdate = false;
				$timeout.cancel(timer);
      };

      if ($scope.autoupdate === true){
				$scope.startAutoupdate();
      }

      $scope.GetIngredients = function(viewValue){
        return TAIngredients.search({search: viewValue, language: 'de'})
        .$promise.then(function(response) {
          return response;
        });
      };

      $scope.addShopitem = function(newshopitem){
        var expDate = new Date();
        expDate.setDate(expDate.getDate() + 14);
        expDate.setHours(0, 0, 0, 0);
				if (!newshopitem) {
          for(i=0;i<$scope.units.length;i++){
            if($scope.units[i]._id === $scope.newunit) {
              $scope.newunitobject = $scope.units[i];
            }
          }
					newshopitem = {ingredient: $scope.newingredient, unit: $scope.newunitobject, amount: $scope.newamount};
				}
        var newshopitem = new Shopitems({ingredient: newshopitem.ingredient, unit: newshopitem.unit, amount: newshopitem.amount, completed: false , expire_date: expDate });
        newshopitem.$save();
        obj = {ingredient: newshopitem.ingredient, unit: newshopitem.unit, completed: newshopitem.completed};
        obj.details = [newshopitem];
        obj.amount = newshopitem.amount;
        $scope.shopitems.push(obj);
        $scope.newingredient = "";
        $scope.newunit = "";
        $scope.newamount = "";
      }

      $scope.remove = function(item = null){
      	$scope.pauseAutoupdate = true;
      	if (!item) {
      		Shopitems.remove({}, null, function(success){
	          $scope.shopitems = []
		    	}, function(err){
		      	$scope.alerts.push({type: 'danger', msg: 'Network connection error'});
			    });
      	} else {
	       	var itemIndex = containsObj($scope.shopitems, item);
	        for(var i=item.details.length-1;i>=0;i--){
	          Shopitems.remove({id: item.details[i]._id}, null, function(success){
							var index;
							for(var j=0;j<$scope.shopitems[itemIndex].details.length;j++){
							  if ($scope.shopitems[itemIndex].details[j]._id == success._id){
							    index = j;
							  }
							}
		          $scope.shopitems[itemIndex].details.splice(index, 1);
							if ($scope.shopitems[itemIndex].details.length === 0) {
							  $scope.shopitems.splice(itemIndex, 1);
							}
			    	}, function(err){
			      	$scope.alerts.push({type: 'danger', msg: 'Network connection error'});
				    });
	      	}
      	}
      	var pauseTimer;
      	$timeout.cancel( timer );
				pauseTimer =  $timeout(function () {
	        $scope.pauseAutoupdate = false;
	        $scope.startAutoupdate();
	      }, 5000);
      }

      $scope.complete = function(item){
      	$scope.pauseAutoupdate = true;

       	var itemIndex = containsObj($scope.shopitems, item);
      	item.completed = !item.completed;
        for(var i=item.details.length-1;i>=0;i--){
          Shopitems.update({id: item.details[i]._id}, {completed: item.completed}, function(success){
						var index;
						for(var j=0;j<$scope.shopitems[itemIndex].details.length;j++){
		  				if ($scope.shopitems[itemIndex].details[j]._id == success._id){
		    				index = j;
		  				}
						}
            $scope.shopitems[itemIndex].details[index].completed = item.completed;
	    		}, function(err){
	      		$scope.alerts.push({type: 'danger', msg: 'Network connection error'});
	    		});
        }

        $scope.shopitems[itemIndex].completed = item.completed;
	      $scope.pauseAutoupdate = false;
      }

			$scope.shopitemDetails = function(item){
        var modalShopitemDetails = $uibModal.open({
          animation: true,
          templateUrl: 'partials/shopitems.modal.details.tpl.html',
          controller: 'ModalShopitemDetailsController',
          size: 'lg',
          resolve: {
            item: function(){
              return item;
            },
            units: function(){
              return $scope.units;
            }
          }
        });

        modalShopitemDetails.result.then(function(response){
          $scope.complete(response);
        });
			}

      $scope.modalShopitemAdd = function() {
        var modalAddShopitem = $uibModal.open({
          animation: true,
          templateUrl: 'partials/shopitems.modal.add.tpl.html',
          controller: 'ModalShopitemAddController',
          size: 'lg',
          resolve: {
            units: function(){
              return $scope.units;
            }
          }
        });

        modalAddShopitem.result.then(function(response){
          $scope.addShopitem(response);
        });

      }

      $scope.modalFrequentshopitemAdd = function(ingredient) {
        var modalAddFrequentshopitem = $uibModal.open({
          animation: true,
          templateUrl: 'partials/frequentshopitems.modal.add.tpl.html',
          controller: 'ModalFrequentshopitemAddController',
          size: 'lg',
          resolve: {
            ingredient: function(){
              return ingredient;
            },
            units: function(){
              return $scope.units;
            }
          }
        });

        modalAddFrequentshopitem.result.then(function(response){
          $scope.addShopitem(response);
        });

      }

      $scope.closeAlert = function(index){
        $scope.alerts.splice(index, 1);
      }

    }])

    .controller('ModalShopitemDetailsController', ['$scope', '$stateParams', '$modalInstance', 'item', function ($scope, $stateParams, $modalInstance, item) {
      $scope.item = item;

      $scope.ok = function(){
        $modalInstance.close($scope.item);
      }

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      }
    }])

    .controller('ModalShopitemAddController', ['$scope', '$stateParams', '$modalInstance', 'TAIngredients', 'units', function ($scope, $stateParams, $modalInstance, TAIngredients, units) {

      $scope.units = units;

      $scope.GetIngredients = function(viewValue){
        return TAIngredients.search({search: viewValue, language: 'de'})
        .$promise.then(function(response) {
          return response;
        });
      };

      $scope.ok = function(){
        for(i=0;i<$scope.units.length;i++){
          if($scope.units[i]._id === $scope.newunit) {
            $scope.newunitobject = $scope.units[i];
          }
        }
        $modalInstance.close({amount: $scope.newamount, unit: $scope.newunitobject, ingredient: $scope.newingredient});
      }

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      }

    }])

    .controller('ModalFrequentshopitemAddController', ['$scope', '$stateParams', '$modalInstance', 'ingredient', 'units', function ($scope, $stateParams, $modalInstance, ingredient, units) {

      $scope.units = units;
      $scope.newunit = $scope.units[2]._id;

      $scope.ingredient = ingredient;

      $scope.ok = function(){
	for(i=0;i<$scope.units.length;i++){
	    if($scope.units[i]._id === $scope.newunit) {
	      $scope.newunitobject = $scope.units[i];
	    }
	  }
        $modalInstance.close({amount: $scope.amount, unit: $scope.newunitobject, ingredient: $scope.ingredient});
      }

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      }

    }])

//---------------
// Routes
//---------------

  .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

    $stateProvider
      		.state('user.shopitems', {
			url: '/shopitems',
      templateUrl: 'partials/shopitems.tpl.html',
      controller: 'ShopitemsController',
			resolve: {
				frequentshopitems: function(Frequentshopitems){
					return Frequentshopitems.query().$promise;
				},
				units: function(Units){
					return Units.query().$promise;
				},
				shopitems: function(retrieveShopitems){
						return retrieveShopitems.retrieve().then( function(data){
							return data;
						});
				}
			},
			data: {
	        		name: 'Shopping',
        			icon: 'glyphicon glyphicon-shopping-cart'
			}
      		})
    ;
  }])
;

<commit_msg>version 2.8a<commit_after>angular.module('app.shopitems', ['ui.router'])

//---------------
// Services
//---------------

        .factory('Shopitems', ['$resource', 'BASE_URI', function($resource, BASE_URI){
          return $resource(BASE_URI+'api/shopitems/:id', null, {
	    'update': { method:'PUT' }
	  });
        }])

        .factory('Frequentshopitems', ['$resource', 'BASE_URI', function($resource, BASE_URI){
          return $resource(BASE_URI+'api/frequentshopitems/');
        }])

        .factory('retrieveShopitems', ['UserService', 'Shopitems', '$q', function(UserService, Shopitems, $q){

    			var containsObj = function(array, obj) {
      			var i, l = array.length;
      			for (i=0;i<array.length;i++)
      			{
        			if (angular.equals(array[i], obj)) return i;
      			}
      			return false;
    			}, retrieve = function(pauseExecution){
      			var deferred = $q.defer();
						Shopitems.query(function(response) {
						  var uniqueIngredients = [];
						  var uniqueIngredientsTemp = [];
						  var user = UserService.getCurrentLoginUser();
						  for(i=0;i<response.length;i++){
						    if ( response[i].ingredient ) {
						      var order = user.settings.categoryOrder.indexOf(response[i].ingredient.category) >= 0 ? user.settings.categoryOrder.indexOf(response[i].ingredient.category) : 99999;
						    } else {
						      var order = 99999;
						    }
						    var obj = {ingredient:response[i].ingredient, unit:response[i].unit, order: order, completed: response[i].completed};
						    var index = containsObj(uniqueIngredientsTemp, obj);
						    if ( index === false) {
						      uniqueIngredientsTemp.push({ingredient:response[i].ingredient, unit:response[i].unit, order: order, completed: response[i].completed});
						      obj.details = [response[i]];
						      obj.amount = response[i].amount;
						      uniqueIngredients.push(obj);
						    }
						    else {
						      uniqueIngredients[index].details.push(response[i]);
						      uniqueIngredients[index].amount = response[i].amount + uniqueIngredients[index].amount;
						    }
						  }
						 	deferred.resolve(uniqueIngredients);
		        });
		        return deferred.promise;
		      };

		      return {
            retrieve: retrieve
        	}
		    }])

//---------------
// Controllers
//---------------

// Shopitems

    .controller('ShopitemsController', ['$scope', '$stateParams', '$uibModal', 'shopitems', 'retrieveShopitems', 'Shopitems', 'frequentshopitems', 'TAIngredients', 'units', '$state', '$filter', '$timeout', function ($scope, $stateParams, $uibModal, shopitems, retrieveShopitems, Shopitems, frequentshopitems, TAIngredients, units, $state, $filter, $timeout) {

      $scope.units = units;
      $scope.shopitems = shopitems;
      $scope.frequentshopitems = frequentshopitems;
	    $scope.pauseAutoupdate = false;

      $scope.autoupdate = true;

      $scope.alerts = [];
      $scope.status = [];
			for(i=0;i<$scope.shopitems.length;i++){
				$scope.status[$scope.shopitems[i].ingredient.category] = true;
			}

      containsObj = function(array, obj) {
        var i, l = array.length;
        for (i=0;i<array.length;i++)
        {
          if (angular.equals(array[i], obj)) return i;
        }
        return false;
      };

      var timer;
      $scope.startAutoupdate = function() {
				$scope.autoupdate = true;
				if (!$scope.pauseAutoupdate){
					retrieveShopitems.retrieve().then( function(data){
						if (data) $scope.shopitems = data;
					});
				}
				timer =  $timeout(function () {
          $scope.startAutoupdate();
        }, 5000);
				$scope.$on( "$destroy",
					function( event ) {
						$timeout.cancel( timer );
					}
				);
      };

      $scope.stopAutoupdate = function(){
				$scope.autoupdate = false;
				$timeout.cancel(timer);
      };

      if ($scope.autoupdate === true){
				$scope.startAutoupdate();
      }

      $scope.GetIngredients = function(viewValue){
        return TAIngredients.search({search: viewValue, language: 'de'})
        .$promise.then(function(response) {
          return response;
        });
      };

      $scope.addShopitem = function(newshopitem){
        var expDate = new Date();
        expDate.setDate(expDate.getDate() + 14);
        expDate.setHours(0, 0, 0, 0);
				if (!newshopitem) {
          for(i=0;i<$scope.units.length;i++){
            if($scope.units[i]._id === $scope.newunit) {
              $scope.newunitobject = $scope.units[i];
            }
          }
					newshopitem = {ingredient: $scope.newingredient, unit: $scope.newunitobject, amount: $scope.newamount};
				}
        var newshopitem = new Shopitems({ingredient: newshopitem.ingredient, unit: newshopitem.unit, amount: newshopitem.amount, completed: false , expire_date: expDate });
        newshopitem.$save();
        obj = {ingredient: newshopitem.ingredient, unit: newshopitem.unit, completed: newshopitem.completed};
        obj.details = [newshopitem];
        obj.amount = newshopitem.amount;
        $scope.shopitems.push(obj);
        $scope.newingredient = "";
        $scope.newunit = "";
        $scope.newamount = "";
      }

      $scope.remove = function(item){
      	$scope.pauseAutoupdate = true;
      	if (!item) {
      		Shopitems.remove({}, null, function(success){
	          $scope.shopitems = []
		    	}, function(err){
		      	$scope.alerts.push({type: 'danger', msg: 'Network connection error'});
			    });
      	} else {
	       	var itemIndex = containsObj($scope.shopitems, item);
	        for(var i=item.details.length-1;i>=0;i--){
	          Shopitems.remove({id: item.details[i]._id}, null, function(success){
							var index;
							for(var j=0;j<$scope.shopitems[itemIndex].details.length;j++){
							  if ($scope.shopitems[itemIndex].details[j]._id == success._id){
							    index = j;
							  }
							}
		          $scope.shopitems[itemIndex].details.splice(index, 1);
							if ($scope.shopitems[itemIndex].details.length === 0) {
							  $scope.shopitems.splice(itemIndex, 1);
							}
			    	}, function(err){
			      	$scope.alerts.push({type: 'danger', msg: 'Network connection error'});
				    });
	      	}
      	}
      	var pauseTimer;
      	$timeout.cancel( timer );
				pauseTimer =  $timeout(function () {
	        $scope.pauseAutoupdate = false;
	        $scope.startAutoupdate();
	      }, 5000);
      }

      $scope.complete = function(item){
      	$scope.pauseAutoupdate = true;

       	var itemIndex = containsObj($scope.shopitems, item);
      	item.completed = !item.completed;
        for(var i=item.details.length-1;i>=0;i--){
          Shopitems.update({id: item.details[i]._id}, {completed: item.completed}, function(success){
						var index;
						for(var j=0;j<$scope.shopitems[itemIndex].details.length;j++){
		  				if ($scope.shopitems[itemIndex].details[j]._id == success._id){
		    				index = j;
		  				}
						}
            $scope.shopitems[itemIndex].details[index].completed = item.completed;
	    		}, function(err){
	      		$scope.alerts.push({type: 'danger', msg: 'Network connection error'});
	    		});
        }

        $scope.shopitems[itemIndex].completed = item.completed;
	      $scope.pauseAutoupdate = false;
      }

			$scope.shopitemDetails = function(item){
        var modalShopitemDetails = $uibModal.open({
          animation: true,
          templateUrl: 'partials/shopitems.modal.details.tpl.html',
          controller: 'ModalShopitemDetailsController',
          size: 'lg',
          resolve: {
            item: function(){
              return item;
            },
            units: function(){
              return $scope.units;
            }
          }
        });

        modalShopitemDetails.result.then(function(response){
          $scope.complete(response);
        });
			}

      $scope.modalShopitemAdd = function() {
        var modalAddShopitem = $uibModal.open({
          animation: true,
          templateUrl: 'partials/shopitems.modal.add.tpl.html',
          controller: 'ModalShopitemAddController',
          size: 'lg',
          resolve: {
            units: function(){
              return $scope.units;
            }
          }
        });

        modalAddShopitem.result.then(function(response){
          $scope.addShopitem(response);
        });

      }

      $scope.modalFrequentshopitemAdd = function(ingredient) {
        var modalAddFrequentshopitem = $uibModal.open({
          animation: true,
          templateUrl: 'partials/frequentshopitems.modal.add.tpl.html',
          controller: 'ModalFrequentshopitemAddController',
          size: 'lg',
          resolve: {
            ingredient: function(){
              return ingredient;
            },
            units: function(){
              return $scope.units;
            }
          }
        });

        modalAddFrequentshopitem.result.then(function(response){
          $scope.addShopitem(response);
        });

      }

      $scope.closeAlert = function(index){
        $scope.alerts.splice(index, 1);
      }

    }])

    .controller('ModalShopitemDetailsController', ['$scope', '$stateParams', '$modalInstance', 'item', function ($scope, $stateParams, $modalInstance, item) {
      $scope.item = item;

      $scope.ok = function(){
        $modalInstance.close($scope.item);
      }

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      }
    }])

    .controller('ModalShopitemAddController', ['$scope', '$stateParams', '$modalInstance', 'TAIngredients', 'units', function ($scope, $stateParams, $modalInstance, TAIngredients, units) {

      $scope.units = units;

      $scope.GetIngredients = function(viewValue){
        return TAIngredients.search({search: viewValue, language: 'de'})
        .$promise.then(function(response) {
          return response;
        });
      };

      $scope.ok = function(){
        for(i=0;i<$scope.units.length;i++){
          if($scope.units[i]._id === $scope.newunit) {
            $scope.newunitobject = $scope.units[i];
          }
        }
        $modalInstance.close({amount: $scope.newamount, unit: $scope.newunitobject, ingredient: $scope.newingredient});
      }

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      }

    }])

    .controller('ModalFrequentshopitemAddController', ['$scope', '$stateParams', '$modalInstance', 'ingredient', 'units', function ($scope, $stateParams, $modalInstance, ingredient, units) {

      $scope.units = units;
      $scope.newunit = $scope.units[2]._id;

      $scope.ingredient = ingredient;

      $scope.ok = function(){
	for(i=0;i<$scope.units.length;i++){
	    if($scope.units[i]._id === $scope.newunit) {
	      $scope.newunitobject = $scope.units[i];
	    }
	  }
        $modalInstance.close({amount: $scope.amount, unit: $scope.newunitobject, ingredient: $scope.ingredient});
      }

      $scope.cancel = function(){
        $modalInstance.dismiss('cancel');
      }

    }])

//---------------
// Routes
//---------------

  .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {

    $stateProvider
      		.state('user.shopitems', {
			url: '/shopitems',
      templateUrl: 'partials/shopitems.tpl.html',
      controller: 'ShopitemsController',
			resolve: {
				frequentshopitems: function(Frequentshopitems){
					return Frequentshopitems.query().$promise;
				},
				units: function(Units){
					return Units.query().$promise;
				},
				shopitems: function(retrieveShopitems){
						return retrieveShopitems.retrieve().then( function(data){
							return data;
						});
				}
			},
			data: {
	        		name: 'Shopping',
        			icon: 'glyphicon glyphicon-shopping-cart'
			}
      		})
    ;
  }])
;

<|endoftext|>


<commit_before>import ResourceLoader from 'resource-loader';
import { blobMiddlewareFactory } from 'resource-loader/lib/middlewares/parsing/blob';
import EventEmitter from 'eventemitter3';
import textureParser from './textureParser';
import spritesheetParser from './spritesheetParser';
import bitmapFontParser from './bitmapFontParser';

/**
 *
 * The new loader, extends Resource Loader by Chad Engler : https://github.com/englercj/resource-loader
 *
 * ```js
 * let loader = PIXI.loader; // pixi exposes a premade instance for you to use.
 * //or
 * let loader = new PIXI.loaders.Loader(); // you can also create your own if you want
 *
 * loader.add('bunny', 'data/bunny.png');
 * loader.add('spaceship', 'assets/spritesheet.json');
 * loader.add('scoreFont', 'assets/score.fnt');
 *
 * loader.once('complete',onAssetsLoaded);
 *
 * loader.load();
 * ```
 *
 * @see https://github.com/englercj/resource-loader
 *
 * @class
 * @extends module:resource-loader.ResourceLoader
 * @memberof PIXI.loaders
 */
export default class Loader extends ResourceLoader
{
    /**
     * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader.
     * @param {number} [concurrency=10] - The number of resources to load concurrently.
     */
    constructor(baseUrl, concurrency)
    {
        super(baseUrl, concurrency);
        EventEmitter.call(this);

        for (let i = 0; i < Loader._pixiMiddleware.length; ++i)
        {
            this.use(Loader._pixiMiddleware[i]());
        }

        // Compat layer, translate the new v2 signals into old v1 events.
        this.onStart.add((l) => this.emit('start', l));
        this.onProgress.add((l, r) => this.emit('progress', l, r));
        this.onError.add((e, l, r) => this.emit('error', e, l, r));
        this.onLoad.add((l, r) => this.emit('load', l, r));
        this.onComplete.add((l, r) => this.emit('complete', l, r));
    }

    /**
     * Adds a default middleware to the pixi loader.
     *
     * @static
     * @param {Function} fn - The middleware to add.
     */
    static addPixiMiddleware(fn)
    {
        Loader._pixiMiddleware.push(fn);
    }
}

// Copy EE3 prototype (mixin)
for (const k in EventEmitter.prototype)
{
    Loader.prototype[k] = EventEmitter.prototype[k];
}

Loader._pixiMiddleware = [
    // parse any blob into more usable objects (e.g. Image)
    blobMiddlewareFactory,
    // parse any Image objects into textures
    textureParser,
    // parse any spritesheet data into multiple textures
    spritesheetParser,
    // parse bitmap font data into multiple textures
    bitmapFontParser,
];

// Add custom extentions
const Resource = ResourceLoader.Resource;

Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT);
<commit_msg>update<commit_after>import ResourceLoader from 'resource-loader';
import { blobMiddlewareFactory } from 'resource-loader/lib/middlewares/parsing/blob';
import EventEmitter from 'eventemitter3';
import textureParser from './textureParser';
import spritesheetParser from './spritesheetParser';
import bitmapFontParser from './bitmapFontParser';

/**
 *
 * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader
 *
 * ```js
 * const loader = PIXI.loader; // pixi exposes a premade instance for you to use.
 * //or
 * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want
 *
 * const sprites = {};
 *
 * // Chainable `add` to enqueue a resource
 * loader.add('bunny', 'data/bunny.png')
 *       .add('spaceship', 'assets/spritesheet.json');
 * loader.add('scoreFont', 'assets/score.fnt');
 *
 * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource.
 * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc).
 * loader.pre(cachingMiddleware);
 *
 * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource.
 * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc).
 * loader.use(parsingMiddleware);
 *
 * // The `load` method loads the queue of resources, and calls the passed in callback called once all
 * // resources have loaded.
 * loader.load((loader, resources) => {
 *     // resources is an object where the key is the name of the resource loaded and the value is the resource object.
 *     // They have a couple default properties:
 *     // - `url`: The URL that the resource was loaded from
 *     // - `error`: The error that happened when trying to load (if any)
 *     // - `data`: The raw data that was loaded
 *     // also may contain other properties based on the middleware that runs.
 *     sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture);
 *     sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture);
 *     sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture);
 * });
 *
 * // throughout the process multiple signals can be dispatched.
 * loader.onProgress.add(() => {}); // called once per loaded/errored file
 * loader.onError.add(() => {}); // called once per errored file
 * loader.onLoad.add(() => {}); // called once per loaded file
 * loader.onComplete.add(() => {}); // called once when the queued resources all load.
 * ```
 *
 * @see https://github.com/englercj/resource-loader
 *
 * @class
 * @extends module:resource-loader.ResourceLoader
 * @memberof PIXI.loaders
 */
export default class Loader extends ResourceLoader
{
    /**
     * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader.
     * @param {number} [concurrency=10] - The number of resources to load concurrently.
     */
    constructor(baseUrl, concurrency)
    {
        super(baseUrl, concurrency);
        EventEmitter.call(this);

        for (let i = 0; i < Loader._pixiMiddleware.length; ++i)
        {
            this.use(Loader._pixiMiddleware[i]());
        }

        // Compat layer, translate the new v2 signals into old v1 events.
        this.onStart.add((l) => this.emit('start', l));
        this.onProgress.add((l, r) => this.emit('progress', l, r));
        this.onError.add((e, l, r) => this.emit('error', e, l, r));
        this.onLoad.add((l, r) => this.emit('load', l, r));
        this.onComplete.add((l, r) => this.emit('complete', l, r));
    }

    /**
     * Adds a default middleware to the pixi loader.
     *
     * @static
     * @param {Function} fn - The middleware to add.
     */
    static addPixiMiddleware(fn)
    {
        Loader._pixiMiddleware.push(fn);
    }
}

// Copy EE3 prototype (mixin)
for (const k in EventEmitter.prototype)
{
    Loader.prototype[k] = EventEmitter.prototype[k];
}

Loader._pixiMiddleware = [
    // parse any blob into more usable objects (e.g. Image)
    blobMiddlewareFactory,
    // parse any Image objects into textures
    textureParser,
    // parse any spritesheet data into multiple textures
    spritesheetParser,
    // parse bitmap font data into multiple textures
    bitmapFontParser,
];

// Add custom extentions
const Resource = ResourceLoader.Resource;

Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT);
<|endoftext|>