<commit_before>var app = angular.module('evewt', ['ui-notification']);
app.controller('wt-list',[ '$scope','$http','$location','$interval','$window','API','EveIGB','Notification','Minions',function ($scope,$http,$location,$interval,$window,API,EveIGB,Notification,Minions) {

    //=== Helpers

    function getQueryParam(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    //=== Vars
    $scope.waitlistVO = null;
    $scope.waitlists = {waitlists:[]};
    $scope.shipDNA = '';
    $scope.apiKey = '';
    $scope.apiVCode = '';
    $scope.remeberMe = true;

    $scope.asciiHead = '-== VG Fleet ==-';
    $scope.asciiFoot = '-==          ==-';
    $scope.waitlistTxt = '';

    $scope.roles = [
        {name: 'T1',     type: 'DD', id:'DD'},
        {name: 'shiny',  type: 'DD', id:'DD'},
        {name: 'Logi',   type: 'L' , id:'LL'},
        {name: 'Logi4',  type: 'L' , id:'L4'},
        {name: 'Logi5',  type: 'L' , id:'L5'},
        {name: 'Scout',  type: 'OG', id:'S'},
        {name: 'Picket', type: 'OG', id:'P'},
        {name: 'OGB',    type: 'OG', id:'OGB'}
    ]
    $scope.mRole = $scope.roles[0]

    $scope.authenticated = false;
    $scope.isIGB = (typeof CCPEVE !== 'undefined');
    console.log('You are' + ($scope.isIGB ? '' : ' not') + ' in Eve IGB')
    $scope.window = $window;

    $scope.getWaitlistId = function () {
        var waitlistId = getQueryParam('waitlistId');
        return waitlistId;
    }

    $scope.isOwner = function () {
        return $scope.waitlistVO.ownerId == $scope.me.characterId;
    }

    $scope.forwardMe = function(){

    }

    $scope.isItemOwner = function(item) {
        return $scope.waitlistVO.ownerId == item.characterId;
    }

    $scope.postFit = function(){
        API.postFit($scope.waitlistVO.waitlistId,$scope.shipDNA,$scope.mRole.id)
            .then(function (data) {
                $scope.refreshWL();
                Notification.success("Successfully x-ed up")
            }, function () {
                Notification.error("Cannot x up, logged in? on waitlist?")
            })
    };

    $scope.newWaitlist = function () {
        return API.newWaitlist()
            .then(function (waitlist) {
                waitlist.waitlistId;
                $scope.updateWL(waitlist);
                Notification.success("Successfully created waitlist")
            }, function () {
                Notification.error("Cannot create waitlist, logged in?")
            })
    };

    //=== Functions
    $scope.updateWL = function(waitlistVO){
        $scope.waitlistVO = waitlistVO;
        // add ascii list
        $scope.waitlistTxt = Minions.waitlist2ascii(waitlistVO,$scope.asciiHead,$scope.asciiFoot);
    };

    $scope.refreshWL = function(){
        API.getWaitlist($scope.waitlistVO.waitlistId)
            .then(function (data) {
                $scope.updateWL(data);
            })
        /*
        API.getWaitlistTxt($scope.waitlistVO.waitlistId)
            .then(function (waitlistTxt) {
                $scope.waitlistTxt = waitlistTxt;
            })
            */
    };

    $scope.showCharInfo = function(item){
        EveIGB.showInfo(1377, item.characterId);
    };

    $scope.showFitting = function(item){
        EveIGB.showFitting(item.shipDNA);
    };

    $scope.showCorporation = function(item){
        EveIGB.showInfo(2,item.corporationId);
    };
    $scope.showAlliance = function(item){
        EveIGB.showInfo(16159,item.allianceId);
    };

    $scope.fleetInvite = function(item){
        EveIGB.inviteToFleet(item.characterId)
        Notification.success("Invited " + item.characterName + " to fleet")
    };

    $scope.makeBoss = function(item){
        API.makeBoss($scope.waitlistVO.waitlistId,item.characterId)
            .then(function () {
                Notification.success("Made " + item.characterName + " waitlist manager")
            }, function () {
                Notification.error('Failed to make ' + item.characterName + ' boss');
            })
    };

    $scope.removeItem = function(item){
        API.removeItem($scope.waitlistVO.waitlistId,item.itemId)
            .then(function () {
                $scope.refreshWL();
                Notification.success("Removed " + item.characterName + " from the waitlist")
            })
            .then(null,function () {
                Notification.error('failed to remove item :(');
            })
    };

    $scope.logout = function () {
        API.logout()
            .then(function () {
                Notification.success("Logged out")
            })
            .then(null,function () {
                Notification.error('failed to logout :(');
            })
    }

    //=== Fetch data

    API.getMe()
        .then(function (data) {
            $scope.me = data;
            var waitlistId = $scope.getWaitlistId(); //$location.hash();
            $scope.authenticated = true;
            if(waitlistId && waitlistId.length>0){
                return API.getWaitlist(waitlistId)
                    .then(function (waitlist) {
                        $scope.updateWL(waitlist);
                        Notification.success('Joined waitlist');
                    })
                    .then(null,function () {
                        $location.hash('');
                        Notification.error('Failed to fetch waitlist :(');
                    })
            }else{
                // Stay on home, need waitlist firs
            }
        })
        .then(null,function (status) {
            if(status==401){
                $scope.authenticated = false;
                Notification.error('Please login first');
            }
        })

    API.getWaitlists()
        .then(function (waitlists) {
            $scope.waitlists = waitlists;
        })

    //update every 10s, veeery inefficient
    $interval(function(){
        $scope.refreshWL();
    }, 10000);
    //
}]);<commit_msg>made it nicer<commit_after>var app = angular.module('evewt', ['ui-notification']);
app.controller('wt-list',[ '$scope','$http','$location','$interval','$window','API','EveIGB','Notification','Minions',function ($scope,$http,$location,$interval,$window,API,EveIGB,Notification,Minions) {

    //=== Helpers

    function getQueryParam(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    //=== Vars
    $scope.waitlistVO = null;
    $scope.waitlists = {waitlists:[]};
    $scope.shipDNA = '';
    $scope.apiKey = '';
    $scope.apiVCode = '';
    $scope.remeberMe = true;

    $scope.asciiHead = '-== VG Fleet ==-';
    $scope.asciiFoot = '-==          ==-';
    $scope.waitlistTxt = '';

    $scope.roles = [
        {name: 'T1',     type: 'Damage Dealer', id:'DD'},
        {name: 'shiny',  type: 'Damage Dealer', id:'DD'},
        {name: 'Logi',   type: 'Logistics' , id:'LL'},
        {name: 'Logi4',  type: 'Logistics' , id:'L4'},
        {name: 'Logi5',  type: 'Logistics' , id:'L5'},
        {name: 'Scout',  type: 'Off-grid', id:'S'},
        {name: 'Picket', type: 'Off-grid', id:'P'},
        {name: 'OGB',    type: 'Off-grid', id:'OGB'}
    ]
    $scope.mRole = $scope.roles[0]

    $scope.authenticated = false;
    $scope.isIGB = (typeof CCPEVE !== 'undefined');
    console.log('You are' + ($scope.isIGB ? '' : ' not') + ' in Eve IGB')
    $scope.window = $window;

    $scope.getWaitlistId = function () {
        var waitlistId = getQueryParam('waitlistId');
        return waitlistId;
    }

    $scope.isOwner = function () {
        return $scope.waitlistVO.ownerId == $scope.me.characterId;
    }

    $scope.forwardMe = function(){

    }

    $scope.isItemOwner = function(item) {
        return $scope.waitlistVO.ownerId == item.characterId;
    }

    $scope.postFit = function(){
        API.postFit($scope.waitlistVO.waitlistId,$scope.shipDNA,$scope.mRole.id)
            .then(function (data) {
                $scope.refreshWL();
                Notification.success("Successfully x-ed up")
            }, function () {
                Notification.error("Cannot x up, logged in? on waitlist?")
            })
    };

    $scope.newWaitlist = function () {
        return API.newWaitlist()
            .then(function (waitlist) {
                waitlist.waitlistId;
                $scope.updateWL(waitlist);
                Notification.success("Successfully created waitlist")
            }, function () {
                Notification.error("Cannot create waitlist, logged in?")
            })
    };

    //=== Functions
    $scope.updateWL = function(waitlistVO){
        $scope.waitlistVO = waitlistVO;
        // add ascii list
        $scope.waitlistTxt = Minions.waitlist2ascii(waitlistVO,$scope.asciiHead,$scope.asciiFoot);
    };

    $scope.refreshWL = function(){
        API.getWaitlist($scope.waitlistVO.waitlistId)
            .then(function (data) {
                $scope.updateWL(data);
            })
        /*
        API.getWaitlistTxt($scope.waitlistVO.waitlistId)
            .then(function (waitlistTxt) {
                $scope.waitlistTxt = waitlistTxt;
            })
            */
    };

    $scope.showCharInfo = function(item){
        EveIGB.showInfo(1377, item.characterId);
    };

    $scope.showFitting = function(item){
        EveIGB.showFitting(item.shipDNA);
    };

    $scope.showCorporation = function(item){
        EveIGB.showInfo(2,item.corporationId);
    };
    $scope.showAlliance = function(item){
        EveIGB.showInfo(16159,item.allianceId);
    };

    $scope.fleetInvite = function(item){
        EveIGB.inviteToFleet(item.characterId)
        Notification.success("Invited " + item.characterName + " to fleet")
    };

    $scope.makeBoss = function(item){
        API.makeBoss($scope.waitlistVO.waitlistId,item.characterId)
            .then(function () {
                Notification.success("Made " + item.characterName + " waitlist manager")
            }, function () {
                Notification.error('Failed to make ' + item.characterName + ' boss');
            })
    };

    $scope.removeItem = function(item){
        API.removeItem($scope.waitlistVO.waitlistId,item.itemId)
            .then(function () {
                $scope.refreshWL();
                Notification.success("Removed " + item.characterName + " from the waitlist")
            })
            .then(null,function () {
                Notification.error('failed to remove item :(');
            })
    };

    $scope.logout = function () {
        API.logout()
            .then(function () {
                Notification.success("Logged out")
            })
            .then(null,function () {
                Notification.error('failed to logout :(');
            })
    }

    //=== Fetch data

    API.getMe()
        .then(function (data) {
            $scope.me = data;
            var waitlistId = $scope.getWaitlistId(); //$location.hash();
            $scope.authenticated = true;
            if(waitlistId && waitlistId.length>0){
                return API.getWaitlist(waitlistId)
                    .then(function (waitlist) {
                        $scope.updateWL(waitlist);
                        Notification.success('Joined waitlist');
                    })
                    .then(null,function () {
                        $location.hash('');
                        Notification.error('Failed to fetch waitlist :(');
                    })
            }else{
                // Stay on home, need waitlist firs
            }
        })
        .then(null,function (status) {
            if(status==401){
                $scope.authenticated = false;
                Notification.error('Please login first');
            }
        })

    API.getWaitlists()
        .then(function (waitlists) {
            $scope.waitlists = waitlists;
        })

    //update every 10s, veeery inefficient
    $interval(function(){
        $scope.refreshWL();
    }, 10000);
    //
}]);<|endoftext|>


<commit_before>var bows = require('bows');
var async = require('async');
var WildEmitter = require('wildemitter');

var log = bows('JingleSession');

function actionToMethod(action) {
    var words = action.split('-');
    return 'on' + words[0][0].toUpperCase() + words[0].substr(1) + words[1][0].toUpperCase() + words[1].substr(1);
}

function JingleSession(opts) {
    var self = this;
    this.sid = opts.sid || Date.now().toString();
    this.peer = opts.peer;
    this.isInitiator = opts.initiator || false;
    this.state = 'starting';
    this.parent = opts.parent;

    this.processingQueue = async.queue(function (task, next) {
        var action  = task.action;
        var changes = task.changes;
        var cb = task.cb;

        log(self.sid + ': ' + action);
        self[action](changes, function (err) {
            cb(err);
            next();
        });
    });
}

JingleSession.prototype = Object.create(WildEmitter.prototype, {
    constructor: {
        value: JingleSession
    }
});

JingleSession.prototype.process = function (action, changes, cb) {
    var method = actionToMethod(action);

    this.processingQueue.push({
        action: method,
        changes: changes,
        cb: cb
    });
};

JingleSession.prototype.send = function (type, data) {
    data = data || {};
    data.sid = this.sid;
    data.action = type;
    this.parent.emit('send', {
        to: this.peer,
        type: 'set',
        jingle: data
    });
};

Object.defineProperty(JingleSession.prototype, 'state', {
    get: function () {
        return this._state;
    },
    set: function (value) {
        var validStates = {
            starting: true,
            pending: true,
            active: true,
            ended: true
        };

        if (!validStates[value]) {
            throw new Error('Invalid Jingle Session State: ' + value);
        }

        if (this._state !== value) {
            this._state = value;
            log(this.sid + ': State changed to ' + value);
        }
    }
});
Object.defineProperty(JingleSession.prototype, 'starting', {
    get: function () {
        return this._state === 'starting';
    }
});
Object.defineProperty(JingleSession.prototype, 'pending', {
    get: function () {
        return this._state === 'pending';
    }
});
Object.defineProperty(JingleSession.prototype, 'active', {
    get: function () {
        return this._state === 'active';
    }
});
Object.defineProperty(JingleSession.prototype, 'ended', {
    get: function () {
        return this._state === 'ended';
    }
});

JingleSession.prototype.start = function () {
    this.state = 'pending';
    log(this.sid + ': Can not start generic session');
};
JingleSession.prototype.end = function (reason, silence) {
    this.parent.peers[this.peer].splice(this.parent.peers[this.peer].indexOf(this), 1);
    delete this.parent.sessions[this.sid];

    this.state = 'ended';

    reason = reason || {};

    if (!silence) {
        this.send('session-terminate', {reason: reason});
    }

    this.parent.emit('terminated', this, reason);
};

var actions = [
    'content-accept', 'content-add', 'content-modify',
    'content-reject', 'content-remove', 'description-info',
    'session-accept', 'session-info', 'session-initiate',
    'session-terminate', 'transport-accept', 'transport-info',
    'transport-reject', 'transport-replace'
];

actions.forEach(function (action) {
    var method = actionToMethod(action);
    JingleSession.prototype[method] = function (changes, cb) {
        log(this.sid + ': Unsupported action ' + action);
        cb();
    };
});

module.exports = JingleSession;
<commit_msg>reject unknown action with a bad-request as described in http://xmpp.org/extensions/xep-0166.html#def-action<commit_after>var bows = require('bows');
var async = require('async');
var WildEmitter = require('wildemitter');

var log = bows('JingleSession');

function actionToMethod(action) {
    var words = action.split('-');
    return 'on' + words[0][0].toUpperCase() + words[0].substr(1) + words[1][0].toUpperCase() + words[1].substr(1);
}

// actions defined in http://xmpp.org/extensions/xep-0166.html#def-action
var actions = [
    'content-accept', 'content-add', 'content-modify',
    'content-reject', 'content-remove', 'description-info',
    'session-accept', 'session-info', 'session-initiate',
    'session-terminate', 'transport-accept', 'transport-info',
    'transport-reject', 'transport-replace'
];

function JingleSession(opts) {
    var self = this;
    this.sid = opts.sid || Date.now().toString();
    this.peer = opts.peer;
    this.isInitiator = opts.initiator || false;
    this.state = 'starting';
    this.parent = opts.parent;

    this.processingQueue = async.queue(function (task, next) {
        var action  = task.action;
        var changes = task.changes;
        var cb = task.cb;

        log(self.sid + ': ' + action);

        if (actions.indexOf(action) === -1) {
            log(this.sid + ': Invalid action ' + action);
            cb({condition: 'bad-request'});
            next();
            return;
        }

        var method = actionToMethod(action);
        self[method](changes, function (err) {
            cb(err);
            next();
        });
    });
}

JingleSession.prototype = Object.create(WildEmitter.prototype, {
    constructor: {
        value: JingleSession
    }
});

JingleSession.prototype.process = function (action, changes, cb) {
    this.processingQueue.push({
        action: action,
        changes: changes,
        cb: cb
    });
};

JingleSession.prototype.send = function (type, data) {
    data = data || {};
    data.sid = this.sid;
    data.action = type;
    this.parent.emit('send', {
        to: this.peer,
        type: 'set',
        jingle: data
    });
};

Object.defineProperty(JingleSession.prototype, 'state', {
    get: function () {
        return this._state;
    },
    set: function (value) {
        var validStates = {
            starting: true,
            pending: true,
            active: true,
            ended: true
        };

        if (!validStates[value]) {
            throw new Error('Invalid Jingle Session State: ' + value);
        }

        if (this._state !== value) {
            this._state = value;
            log(this.sid + ': State changed to ' + value);
        }
    }
});
Object.defineProperty(JingleSession.prototype, 'starting', {
    get: function () {
        return this._state === 'starting';
    }
});
Object.defineProperty(JingleSession.prototype, 'pending', {
    get: function () {
        return this._state === 'pending';
    }
});
Object.defineProperty(JingleSession.prototype, 'active', {
    get: function () {
        return this._state === 'active';
    }
});
Object.defineProperty(JingleSession.prototype, 'ended', {
    get: function () {
        return this._state === 'ended';
    }
});

JingleSession.prototype.start = function () {
    this.state = 'pending';
    log(this.sid + ': Can not start generic session');
};
JingleSession.prototype.end = function (reason, silence) {
    this.parent.peers[this.peer].splice(this.parent.peers[this.peer].indexOf(this), 1);
    delete this.parent.sessions[this.sid];

    this.state = 'ended';

    reason = reason || {};

    if (!silence) {
        this.send('session-terminate', {reason: reason});
    }

    this.parent.emit('terminated', this, reason);
};

actions.forEach(function (action) {
    var method = actionToMethod(action);
    JingleSession.prototype[method] = function (changes, cb) {
        log(this.sid + ': Unsupported action ' + action);
        cb();
    };
});

module.exports = JingleSession;
<|endoftext|>


<commit_before>import {createRandomString} from './helpers/string';
import {isNil, isArray, flatten} from 'lodash';

class Entity {
    entityId = createRandomString()

    get props(): Object {
        return this._props;
    }

    set props(props: ?Object) {
        this._props = isNil(props) ? {} : props;
    }

    get children(): Array {
        return this._children;
    }

    set children(children: ?Array) {
        this._children = isArray(children) ? flatten(children) : [];
    }
}

export default Entity;
<commit_msg>Actually start to use Entity<commit_after>//TODO: figure out a way to make systems lifecycle methods work if original entity doesn't have method.
class Entity {
    willMount = () => {}
    create = () => {}
    didCreate = () => {}
    didMount = () => {}
    willUpdate = () => {}
    update = () => {}
    didUpdate = () => {}
}

export default Entity;
<|endoftext|>


<commit_before>/** @babel */

import {Emitter, CompositeDisposable} from 'atom'
import Repository from './repository'
import CommitPanelComponent from './commit-panel-component'

export default class GithubPackage {
  constructor (workspace, project) {
    this.workspace = workspace
    this.project = project
    this.activeRepository = null
    this.fileDiffPaneItem = null
    this.repositoriesByProjectDirectory = new Map
    this.subscriptions = new CompositeDisposable
    this.commitPanelComponent = new CommitPanelComponent({repository: null, didSelectFileDiff: this.didSelectFileDiff.bind(this)})
  }

  async activate () {
    await this.updateActiveRepository()
    await this.commitPanelComponent.update({repository: this.getActiveRepository()})
    this.workspace.addRightPanel({item: this.commitPanelComponent})

    this.subscriptions.add(
      this.project.onDidChangePaths(this.didChangeProjectPaths.bind(this)),
      this.workspace.onDidChangeActivePaneItem(this.didChangeActivePaneItem.bind(this))
    )
  }

  async didChangeProjectPaths () {
    await this.destroyRepositoriesForRemovedProjectFolders()
    await this.updateActiveRepository()
    await this.commitPanelComponent.update({repository: this.getActiveRepository()})
  }

  async didChangeActivePaneItem () {
    await this.updateActiveRepository()
    await this.commitPanelComponent.update({repository: this.getActiveRepository()})
  }

  didSelectFileDiff (fileDiff, stageStatus) {
    // TODO: render fileDiffView in designated fileDiffPaneItem
  }

  getActiveRepository () {
    return this.activeRepository
  }

  async updateActiveRepository () {
    let activeRepository

    if (this.activeRepository && this.project.getDirectories().indexOf(this.activeRepository.getWorkingDirectory()) === -1) {
      this.activeRepository = null
    }

    let activeItem = this.workspace.getActivePaneItem()
    if (activeItem && typeof activeItem.getPath === 'function') {
      let projectDirectory = this.projectDirectoryForPath(activeItem.getPath())
      if (projectDirectory) {
        activeRepository = await this.repositoryForProjectDirectory(projectDirectory)
      }
    }

    if (!(activeRepository || this.activeRepository)) {
      for (let directory of this.project.getDirectories()) {
        activeRepository = await this.repositoryForProjectDirectory(directory)
        if (activeRepository) break
      }
    }

    if (activeRepository) {
      this.activeRepository = activeRepository
    }
  }

  projectDirectoryForPath (path) {
    return this.project.getDirectories().find(d => d.getPath() === path || d.contains(path))
  }

  async repositoryForProjectDirectory (projectDirectory) {
    let repository = this.repositoriesByProjectDirectory.get(projectDirectory)

    if (!repository) {
      const atomRepository = await this.project.repositoryForDirectory(projectDirectory)
      if (atomRepository == null) {
        return
      } else {
        const rawRepository = await atomRepository.async.repo.repoPromise
        repository = new Repository(rawRepository, projectDirectory)
        this.repositoriesByProjectDirectory.set(projectDirectory, repository)
      }
    }

    return repository
  }

  async repositoryForWorkdirPath (workdirPath) {
    return this.repositoryForProjectDirectory(this.projectDirectoryForPath(workdirPath))
  }

  destroyRepositoriesForRemovedProjectFolders () {
    const projectDirectories = this.project.getDirectories()
    for (let [projectDirectory, repository] of this.repositoriesByProjectDirectory) {
      if (projectDirectories.indexOf(projectDirectory) === -1) {
        this.repositoriesByProjectDirectory.delete(projectDirectory)
      }
    }
  }
}
<commit_msg>Add destroy method in GithubPackage<commit_after>/** @babel */

import {Emitter, CompositeDisposable} from 'atom'
import Repository from './repository'
import CommitPanelComponent from './commit-panel-component'

export default class GithubPackage {
  constructor (workspace, project) {
    this.workspace = workspace
    this.project = project
    this.activeRepository = null
    this.fileDiffPaneItem = null
    this.repositoriesByProjectDirectory = new Map
    this.subscriptions = new CompositeDisposable
    this.commitPanelComponent = new CommitPanelComponent({repository: null, didSelectFileDiff: this.didSelectFileDiff.bind(this)})
  }

  async activate () {
    await this.updateActiveRepository()
    await this.commitPanelComponent.update({repository: this.getActiveRepository()})
    this.workspace.addRightPanel({item: this.commitPanelComponent})

    this.subscriptions.add(
      this.project.onDidChangePaths(this.didChangeProjectPaths.bind(this)),
      this.workspace.onDidChangeActivePaneItem(this.didChangeActivePaneItem.bind(this))
    )
  }

  async didChangeProjectPaths () {
    await this.destroyRepositoriesForRemovedProjectFolders()
    await this.updateActiveRepository()
    await this.commitPanelComponent.update({repository: this.getActiveRepository()})
  }

  async didChangeActivePaneItem () {
    await this.updateActiveRepository()
    await this.commitPanelComponent.update({repository: this.getActiveRepository()})
  }

  didSelectFileDiff (fileDiff, stageStatus) {
    // TODO: render fileDiffView in designated fileDiffPaneItem
  }

  getActiveRepository () {
    return this.activeRepository
  }

  async updateActiveRepository () {
    let activeRepository

    if (this.activeRepository && this.project.getDirectories().indexOf(this.activeRepository.getWorkingDirectory()) === -1) {
      this.activeRepository = null
    }

    let activeItem = this.workspace.getActivePaneItem()
    if (activeItem && typeof activeItem.getPath === 'function') {
      let projectDirectory = this.projectDirectoryForPath(activeItem.getPath())
      if (projectDirectory) {
        activeRepository = await this.repositoryForProjectDirectory(projectDirectory)
      }
    }

    if (!(activeRepository || this.activeRepository)) {
      for (let directory of this.project.getDirectories()) {
        activeRepository = await this.repositoryForProjectDirectory(directory)
        if (activeRepository) break
      }
    }

    if (activeRepository) {
      this.activeRepository = activeRepository
    }
  }

  projectDirectoryForPath (path) {
    return this.project.getDirectories().find(d => d.getPath() === path || d.contains(path))
  }

  async repositoryForProjectDirectory (projectDirectory) {
    let repository = this.repositoriesByProjectDirectory.get(projectDirectory)

    if (!repository) {
      const atomRepository = await this.project.repositoryForDirectory(projectDirectory)
      if (atomRepository == null) {
        return
      } else {
        const rawRepository = await atomRepository.async.repo.repoPromise
        repository = new Repository(rawRepository, projectDirectory)
        this.repositoriesByProjectDirectory.set(projectDirectory, repository)
      }
    }

    return repository
  }

  async repositoryForWorkdirPath (workdirPath) {
    return this.repositoryForProjectDirectory(this.projectDirectoryForPath(workdirPath))
  }

  destroyRepositoriesForRemovedProjectFolders () {
    const projectDirectories = this.project.getDirectories()
    for (let [projectDirectory, repository] of this.repositoriesByProjectDirectory) {
      if (projectDirectories.indexOf(projectDirectory) === -1) {
        this.repositoriesByProjectDirectory.delete(projectDirectory)
      }
    }
  }

  destroy () {
    this.subscriptions.dispose()
    this.commitPanelComponent.destroy()
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007-2010, John Mettraux, jmettraux@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * Made in Japan.
 */

var RuoteForms = function() {

  // TODO
  //
  // - [cut/]paste
  // - rform_number validate onblur

  //
  // misc

  function escapeHtml (s) {
    return s
      .replace(/&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/'/g, ''')
      .replace(/"/g, '"');
  }

  function toArray (a) {
    var aa = [];
    if (a.length) { for (var i = 0; i < a.length; i++) { aa.push(a[i]); } }
    else { for (var i in a) { aa.push(a[i]); } }
    return aa;
  }

  function dwrite () {
    var s = '';
    document.write('. ' + toArray(arguments).join(', ') + '
');
  }

  function hclone (h) {
    var n = {};
    for (var k in h) { n[k] = h[k]; }
    return n;
  }

  function byId (id) {
    return ((typeof id) == 'string') ? document.getElementById(id) : id;
  }

  function clean (elt) {
    while (elt.firstChild != null) elt.removeChild(elt.firstChild);
  }

  function create (container, tag, attributes, content) {
    if ( ! attributes) attributes = {};
    var e = document.createElement(tag);
    if (content) e.innerHTML = content;
    for (var k in attributes) e.setAttribute(k, attributes[k]);
    if (container) container.appendChild(e);
    return e;
  }

  //
  // edition

  function moveUp () {
    this.stack();
    var ps = this.previousSibling;
    if ( ! ps) return;
    this.parentNode.insertBefore(this, ps);
  }
  function moveDown () {
    this.stack();
    var ns = this.nextSibling;
    if ( ! ns) return;
    var nns = ns.nextSibling;
    if (nns) this.parentNode.insertBefore(this, nns);
    else this.parentNode.appendChild(this);
  }

  function cut () {
    this.stack();
    this.parentNode.removeChild(this);
  }

  //
  // toObject()

  // like the ruby inject, but 'return target' is implied
  //
  function inject (target, func) {
    for (var i in this) {
      var e = this[i];
      if ((typeof e) == 'function') continue;
      func(target, this[i]);
    }
    return target;
  }

  function childrenOfClass (container, className) {
    var a = [];
    for (var i in container.childNodes) {
      var n = container.childNodes[i];
      if ( ! n) continue;
      if (n.nodeType != 1) continue;
      if (n.className != className) continue;
      a.push(n);
    }
    a.inject = inject;
    return a;
    //return container.childNodes.filter(function (n) {
    //  return n.nodeType == 1 && n.className == className;
    //});
  }
  function childOfClass (container, className) {
    return childrenOfClass(container, className)[0];
  }
  function rformChild (container) {
    for (var i in container.childNodes) {
      var n = container.childNodes[i];
      if (n.nodeType != 1) continue;
      if (n.className.match(/rform\_/)) return n;
    }
    return null;
  }

  function toObject () {
    var type = this.className.match(/rform\_([^ ]*)/)[1];
    if (type == 'array') {
      return childrenOfClass(this, 'rform_item').inject([], function(a, i) {
        var v = i.toObject();
        if (v != EmptyItem) a.push(v);
      });
    }
    if (type == 'item' || type == 'key' || type == 'value') {
      var c = rformChild(this);
      return c ? c.toObject() : null;
    }
    if (type == 'hash') {
      var h = {};
      childrenOfClass(this, 'rform_entry').map(function(e) {
        var entry = e.toObject();
        var k = entry[0];
        var v = entry[1];
        if (v != EmptyItem) h[k] = v;
      });
      return h;
    }
    if (type == 'entry') {
      return [
        childOfClass(this, 'rform_key').toObject(),
        childOfClass(this, 'rform_value').toObject()
      ];
    }
    if (type == 'string') {
      return this.firstChild.value;
    }
    if (type == 'number') {
      return (new Number(this.firstChild.value)).valueOf();
    }
    if (type == 'boolean') {
      return this.firstChild.checked;
    }
    if (type == 'new') {
      return EmptyItem;
    }
    alert("unknown type '" + type + "'");
  }

  function rcreate (container, tag, attributes, content) {
    var e = create(container, tag, attributes, content);
    e.toObject = toObject;
    e.stack = stack;
    e.moveUp = moveUp;
    e.moveDown = moveDown;
    e.cut = cut;
    return e;
  }

  //
  // undo / copy / paste / reset

  function findRoot (elt) {
    if (elt.className.match(/rform_root/)) return elt;
    return findRoot(elt.parentNode);
  }

  function stack () {
    var root = findRoot(this);
    root.stack.push(root.firstChild.toObject());
  }

  function resetForm (container) {
    var root = byId(container);
    clean(root);
    render(root, root.originalData, root.originalOptions);
  }

  function undo (container) {
    var root = byId(container);
    clean(root);
    var data = root.stack.pop() || root.originalData;
    render(root, data, root.originalOptions);
  }

  //
  // focuses in the first input thing found in this element
  //
  function focusIn (elt) {
    if (elt.nodeName.toLowerCase() == 'input') {
      elt.focus();
      return true;
    }
    for (var i in elt.childNodes) {
      var n = elt.childNodes[i];
      if (n.nodeType != 1) continue;
      if (focusIn(n)) return true;
    }
    return false;
  }

  //
  // render()

  function EmptyItem () {} // a kind of 'marker'

  function createChangeFunction (render_method) {
    return function () {
      var target = this.parentNode.parentNode;
      var n = render_method.call(null, target, EmptyItem, {});
      target.replaceChild(n, this);
      return false;
    };
  }

  function addItemButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    create(e, 'a', {
      'href': '',
      'class': 'rform_button rform_button_moveup',
      'onclick': 'this.parentNode.parentNode.moveUp(); return false;'
    });
    create(e, 'a', {
      'href': '',
      'class': 'rform_button rform_button_movedown',
      'onclick': 'this.parentNode.parentNode.moveDown(); return false;'
    });
    create(e, 'a', {
      'href': '',
      'class': 'rform_button rform_button_cut',
      'onclick': 'this.parentNode.parentNode.cut(); return false;'
    });
    var ec = create(e, 'a', {
      'href': '', 'class': 'rform_button rform_button_change' });
    ec.onclick = function () {
      var target = this.parentNode.parentNode;
      var n = render_item(target.parentNode, EmptyItem, {});
      target.parentNode.replaceChild(n, target);
      return false;
    }
  }

  function addToCollection (elt) {
    //elt.stack();
    var ecollection = elt.parentNode;
    ecollection.insertBefore(elt, elt.previousSibling);
    return false;
  }

  function addArrayButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    var ea = create(e, 'a', {
      'href': '', 'class': 'rform_button rform_button_add' });
    ea.onclick = function () {
      return addToCollection(render_item(e.parentNode, EmptyItem, {}));
    }
  }

  function addEntryButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    create(e, 'a', {
      'href': '',
      'class': 'rform_button rform_button_cut',
      'onclick': 'this.parentNode.parentNode.cut(); return false;'
    });
    var ec = create(e, 'a', {
      'href': '', 'class': 'rform_button rform_button_change' });
    ec.onclick = function () {
      var target = this.parentNode.parentNode;
      var k = target.firstChild.firstChild.firstChild.value;
      var n = render_entry(target.parentNode, [ k, EmptyItem ], {});
      target.parentNode.replaceChild(n, target);
      return false;
    }
  }

  function addHashButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    var ea = create(e, 'a', {
      'href': '', 'class': 'rform_button rform_button_add' });
    ea.onclick = function () {
      var ne = render_entry(e.parentNode, [ '', EmptyItem ], {});
      var r = addToCollection(ne);
      focusIn(ne);
      return r;
    }
  }

  function render_item (elt, data, options) {
    var ei = rcreate(elt, 'div', { 'class': 'rform_item' });
    render(ei, data, options);
    addItemButtons(ei);
    return ei;
  }

  function render_array (elt, data, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_array' });
    for (var i = 0; i < data.length; i++) { render_item(e, data[i], options); }
    addArrayButtons(e);
    return e;
  }

  function render_entry (elt, data, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_entry' });
    var ek = rcreate(e, 'div', { 'class': 'rform_key' });
    var ev = rcreate(e, 'div', { 'class': 'rform_value' });
    addEntryButtons(e);
    render(ek, data[0], options);
    var evv = render(ev, data[1], options);
    return e;
  }

  function render_object (elt, data, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_hash' });
    //var ks = []; for (var kk in data) { ks.push(kk); }; ks = ks.sort();
    for (var k in data) { render_entry(e, [ k, data[k] ], options); }
    addHashButtons(e);
    return e;
  }

  function render_boolean (elt, data, options) {
    var n = Math.random().toString();
    var e = rcreate(elt, 'div', { 'class': 'rform_boolean' });
    var et = rcreate(e, 'input', { 'type': 'radio', 'name': n });
    var ett = rcreate(e, 'span', {}, 'true');
    var ef = rcreate(e, 'input', { 'type': 'radio', 'name': n });
    var eff = rcreate(e, 'span', {}, 'false');
    ett.onclick = function () { et.checked = true; }
    eff.onclick = function () { ef.checked = true; }
    if (data) et.checked = true;
    else ef.checked = true;
    return e;
  }

  function render_new_type (elt, label, initialValue) {
    var e = rcreate(elt, 'a', { 'class': 'rform_new_type', 'href': '' }, label);
    e.onclick = function () {
      var enew = this.parentNode;
      var enewp = enew.parentNode;
      var i = render(enewp, initialValue, {});
      enewp.replaceChild(i, enew);
      focusIn(i);
      return false;
    };
  }
  function render_new (elt, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_new' });
    render_new_type(e, 'string', '');
    render_new_type(e, 'number', 0);
    render_new_type(e, 'boolean', false);
    render_new_type(e, 'array', []);
    render_new_type(e, 'hash', {});
    return e;
  }

  function render_number (elt, data, options) {
    options = hclone(options);
    options['class'] = 'rform_number';
    return render_string(elt, data.toString(), options);
  }

  function render_string (elt, data, options) {
    var klass = options['class'] || 'rform_string';
    var e = rcreate(elt, 'span', { 'class': klass });
    if (options['read-only'])
      e.innerHTML = escapeHtml(data);
    else if (data.match(/\n/))
      create(e, 'textarea', { 'type': 'text' }, data);
    else
      create(e, 'input', { 'type': 'text', 'value': data });
    return e;
  }

  function render (elt, data, options) {
    if (data == EmptyItem || data == null) return render_new(elt, options);
    var t = data['__class'] || (typeof data);
    if (t == 'object') {
      var l = data.length;
      if (l || l == 0) t = 'array';
    }
    var f = eval('render_' + t);
    return f.call(null, elt, data, options);
  }

  function renderForm (container, data, options) {

    container = byId(container);

    if ( ! container.className.match(/rform_root/))
      container.className = container.className + ' rform_root';
    if ( ! options)
      options = {};

    clean(container);

    container.originalData = data;
    container.originalOptions = options;
    container.stack = [];

    render(container, data, options);
  }

  function toJson (container) {
    container = byId(container);
    return JSON.stringify(container.firstChild.toObject());
  }

  return {
    renderForm: renderForm,
    resetForm: resetForm,
    toJson: toJson,
    undo: undo
  };
}();

<commit_msg>added titles to buttons<commit_after>/*
 * Copyright (c) 2007-2010, John Mettraux, jmettraux@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * Made in Japan.
 */

var RuoteForms = function() {

  // TODO
  //
  // - [cut/]paste
  // - rform_number validate onblur

  // buttons 'title', accessible as RuoteForms.TEXTS
  //
  var TEXTS = {
    add: "add a value to this container value",
    cut: "cut/remove this value",
    change: "modify this value (and its type)",
    moveup: "move that value up in the array",
    movedown: "move that value down in the array"
  }

  //
  // misc

  function escapeHtml (s) {
    return s
      .replace(/&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/'/g, ''')
      .replace(/"/g, '"');
  }

  function toArray (a) {
    var aa = [];
    if (a.length) { for (var i = 0; i < a.length; i++) { aa.push(a[i]); } }
    else { for (var i in a) { aa.push(a[i]); } }
    return aa;
  }

  function dwrite () {
    var s = '';
    document.write('. ' + toArray(arguments).join(', ') + '
');
  }

  function hclone (h) {
    var n = {};
    for (var k in h) { n[k] = h[k]; }
    return n;
  }

  function byId (id) {
    return ((typeof id) == 'string') ? document.getElementById(id) : id;
  }

  function clean (elt) {
    while (elt.firstChild != null) elt.removeChild(elt.firstChild);
  }

  function create (container, tag, attributes, content) {
    if ( ! attributes) attributes = {};
    var e = document.createElement(tag);
    if (content) e.innerHTML = content;
    for (var k in attributes) e.setAttribute(k, attributes[k]);
    if (container) container.appendChild(e);
    return e;
  }

  //
  // edition

  function moveUp () {
    this.stack();
    var ps = this.previousSibling;
    if ( ! ps) return;
    this.parentNode.insertBefore(this, ps);
  }
  function moveDown () {
    this.stack();
    var ns = this.nextSibling;
    if ( ! ns) return;
    var nns = ns.nextSibling;
    if (nns) this.parentNode.insertBefore(this, nns);
    else this.parentNode.appendChild(this);
  }

  function cut () {
    this.stack();
    this.parentNode.removeChild(this);
  }

  //
  // toObject()

  // like the ruby inject, but 'return target' is implied
  //
  function inject (target, func) {
    for (var i in this) {
      var e = this[i];
      if ((typeof e) == 'function') continue;
      func(target, this[i]);
    }
    return target;
  }

  function childrenOfClass (container, className) {
    var a = [];
    for (var i in container.childNodes) {
      var n = container.childNodes[i];
      if ( ! n) continue;
      if (n.nodeType != 1) continue;
      if (n.className != className) continue;
      a.push(n);
    }
    a.inject = inject;
    return a;
    //return container.childNodes.filter(function (n) {
    //  return n.nodeType == 1 && n.className == className;
    //});
  }
  function childOfClass (container, className) {
    return childrenOfClass(container, className)[0];
  }
  function rformChild (container) {
    for (var i in container.childNodes) {
      var n = container.childNodes[i];
      if (n.nodeType != 1) continue;
      if (n.className.match(/rform\_/)) return n;
    }
    return null;
  }

  function toObject () {
    var type = this.className.match(/rform\_([^ ]*)/)[1];
    if (type == 'array') {
      return childrenOfClass(this, 'rform_item').inject([], function(a, i) {
        var v = i.toObject();
        if (v != EmptyItem) a.push(v);
      });
    }
    if (type == 'item' || type == 'key' || type == 'value') {
      var c = rformChild(this);
      return c ? c.toObject() : null;
    }
    if (type == 'hash') {
      var h = {};
      childrenOfClass(this, 'rform_entry').map(function(e) {
        var entry = e.toObject();
        var k = entry[0];
        var v = entry[1];
        if (v != EmptyItem) h[k] = v;
      });
      return h;
    }
    if (type == 'entry') {
      return [
        childOfClass(this, 'rform_key').toObject(),
        childOfClass(this, 'rform_value').toObject()
      ];
    }
    if (type == 'string') {
      return this.firstChild.value;
    }
    if (type == 'number') {
      return (new Number(this.firstChild.value)).valueOf();
    }
    if (type == 'boolean') {
      return this.firstChild.checked;
    }
    if (type == 'new') {
      return EmptyItem;
    }
    alert("unknown type '" + type + "'");
  }

  function rcreate (container, tag, attributes, content) {
    var e = create(container, tag, attributes, content);
    e.toObject = toObject;
    e.stack = stack;
    e.moveUp = moveUp;
    e.moveDown = moveDown;
    e.cut = cut;
    return e;
  }

  //
  // undo / copy / paste / reset

  function findRoot (elt) {
    if (elt.className.match(/rform_root/)) return elt;
    return findRoot(elt.parentNode);
  }

  function stack () {
    var root = findRoot(this);
    root.stack.push(root.firstChild.toObject());
  }

  function resetForm (container) {
    var root = byId(container);
    clean(root);
    render(root, root.originalData, root.originalOptions);
  }

  function undo (container) {
    var root = byId(container);
    clean(root);
    var data = root.stack.pop() || root.originalData;
    render(root, data, root.originalOptions);
  }

  //
  // focuses in the first input thing found in this element
  //
  function focusIn (elt) {
    if (elt.nodeName.toLowerCase() == 'input') {
      elt.focus();
      return true;
    }
    for (var i in elt.childNodes) {
      var n = elt.childNodes[i];
      if (n.nodeType != 1) continue;
      if (focusIn(n)) return true;
    }
    return false;
  }

  //
  // render()

  function EmptyItem () {} // a kind of 'marker'

  function createChangeFunction (render_method) {
    return function () {
      var target = this.parentNode.parentNode;
      var n = render_method.call(null, target, EmptyItem, {});
      target.replaceChild(n, this);
      return false;
    };
  }

  function addItemButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    create(e, 'a', {
      'href': '',
      'title': TEXTS.moveup,
      'class': 'rform_button rform_button_moveup',
      'onclick': 'this.parentNode.parentNode.moveUp(); return false;'
    });
    create(e, 'a', {
      'href': '',
      'title': TEXTS.movedown,
      'class': 'rform_button rform_button_movedown',
      'onclick': 'this.parentNode.parentNode.moveDown(); return false;'
    });
    create(e, 'a', {
      'href': '',
      'title': TEXTS.cut,
      'class': 'rform_button rform_button_cut',
      'onclick': 'this.parentNode.parentNode.cut(); return false;'
    });
    var ec = create(e, 'a', {
      'href': '',
      'title': TEXTS.change,
      'class': 'rform_button rform_button_change' });
    ec.onclick = function () {
      var target = this.parentNode.parentNode;
      var n = render_item(target.parentNode, EmptyItem, {});
      target.parentNode.replaceChild(n, target);
      return false;
    }
  }

  function addToCollection (elt) {
    //elt.stack();
    var ecollection = elt.parentNode;
    ecollection.insertBefore(elt, elt.previousSibling);
    return false;
  }

  function addArrayButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    var ea = create(e, 'a', {
      'href': '',
      'title': TEXTS.add,
      'class': 'rform_button rform_button_add' });
    ea.onclick = function () {
      return addToCollection(render_item(e.parentNode, EmptyItem, {}));
    }
  }

  function addEntryButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    create(e, 'a', {
      'href': '',
      'title': TEXTS.cut,
      'class': 'rform_button rform_button_cut',
      'onclick': 'this.parentNode.parentNode.cut(); return false;'
    });
    var ec = create(e, 'a', {
      'href': '', 'class': 'rform_button rform_button_change' });
    ec.onclick = function () {
      var target = this.parentNode.parentNode;
      var k = target.firstChild.firstChild.firstChild.value;
      var n = render_entry(target.parentNode, [ k, EmptyItem ], {});
      target.parentNode.replaceChild(n, target);
      return false;
    }
  }

  function addHashButtons (elt) {
    var e = create(elt, 'div', { 'class': 'rform_buttons', });
    var ea = create(e, 'a', {
      'href': '',
      'title': TEXTS.add,
      'class': 'rform_button rform_button_add' });
    ea.onclick = function () {
      var ne = render_entry(e.parentNode, [ '', EmptyItem ], {});
      var r = addToCollection(ne);
      focusIn(ne);
      return r;
    }
  }

  function render_item (elt, data, options) {
    var ei = rcreate(elt, 'div', { 'class': 'rform_item' });
    render(ei, data, options);
    addItemButtons(ei);
    return ei;
  }

  function render_array (elt, data, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_array' });
    for (var i = 0; i < data.length; i++) { render_item(e, data[i], options); }
    addArrayButtons(e);
    return e;
  }

  function render_entry (elt, data, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_entry' });
    var ek = rcreate(e, 'div', { 'class': 'rform_key' });
    var ev = rcreate(e, 'div', { 'class': 'rform_value' });
    addEntryButtons(e);
    render(ek, data[0], options);
    var evv = render(ev, data[1], options);
    return e;
  }

  function render_object (elt, data, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_hash' });
    //var ks = []; for (var kk in data) { ks.push(kk); }; ks = ks.sort();
    for (var k in data) { render_entry(e, [ k, data[k] ], options); }
    addHashButtons(e);
    return e;
  }

  function render_boolean (elt, data, options) {
    var n = Math.random().toString();
    var e = rcreate(elt, 'div', { 'class': 'rform_boolean' });
    var et = rcreate(e, 'input', { 'type': 'radio', 'name': n });
    var ett = rcreate(e, 'span', {}, 'true');
    var ef = rcreate(e, 'input', { 'type': 'radio', 'name': n });
    var eff = rcreate(e, 'span', {}, 'false');
    ett.onclick = function () { et.checked = true; }
    eff.onclick = function () { ef.checked = true; }
    if (data) et.checked = true;
    else ef.checked = true;
    return e;
  }

  function render_new_type (elt, label, initialValue) {
    var e = rcreate(elt, 'a', { 'class': 'rform_new_type', 'href': '' }, label);
    e.onclick = function () {
      var enew = this.parentNode;
      var enewp = enew.parentNode;
      var i = render(enewp, initialValue, {});
      enewp.replaceChild(i, enew);
      focusIn(i);
      return false;
    };
  }
  function render_new (elt, options) {
    var e = rcreate(elt, 'div', { 'class': 'rform_new' });
    render_new_type(e, 'string', '');
    render_new_type(e, 'number', 0);
    render_new_type(e, 'boolean', false);
    render_new_type(e, 'array', []);
    render_new_type(e, 'hash', {});
    return e;
  }

  function render_number (elt, data, options) {
    options = hclone(options);
    options['class'] = 'rform_number';
    return render_string(elt, data.toString(), options);
  }

  function render_string (elt, data, options) {
    var klass = options['class'] || 'rform_string';
    var e = rcreate(elt, 'span', { 'class': klass });
    if (options['read-only'])
      e.innerHTML = escapeHtml(data);
    else if (data.match(/\n/))
      create(e, 'textarea', { 'type': 'text' }, data);
    else
      create(e, 'input', { 'type': 'text', 'value': data });
    return e;
  }

  function render (elt, data, options) {
    if (data == EmptyItem || data == null) return render_new(elt, options);
    var t = data['__class'] || (typeof data);
    if (t == 'object') {
      var l = data.length;
      if (l || l == 0) t = 'array';
    }
    var f = eval('render_' + t);
    return f.call(null, elt, data, options);
  }

  function renderForm (container, data, options) {

    container = byId(container);

    if ( ! container.className.match(/rform_root/))
      container.className = container.className + ' rform_root';
    if ( ! options)
      options = {};

    clean(container);

    container.originalData = data;
    container.originalOptions = options;
    container.stack = [];

    render(container, data, options);
  }

  function toJson (container) {
    container = byId(container);
    return JSON.stringify(container.firstChild.toObject());
  }

  return {
    TEXTS: TEXTS,
    renderForm: renderForm,
    resetForm: resetForm,
    toJson: toJson,
    undo: undo
  };
}();

<|endoftext|>


<commit_before>function onInstall(e) {
  //Install triggers
  PropertiesService.getDocumentProperties().setProperty(PROPERTY_SS_ID, SpreadsheetApp.getActiveSpreadsheet().getId());

  onOpen(e);
}

function onOpen(e) {
  SpreadsheetApp.getUi()
    .createAddonMenu()//'Defect Tracker'
    .addItem('Set Up Email List', 'openListSetUpSidebar')
    .addToUi();
}

/**
 * Creates an HTML sidebar for creating/viewing mailman rules.
 *
 */
function openListSetUpSidebar() {
  var ui = HtmlService.createHtmlOutputFromFile('ListSetupSidebar')
    .setTitle('Set Up Email List')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);

  SpreadsheetApp.getUi().showSidebar(ui);
}

function onTrigger() {
  Logger.log('Running trigger function...');

  var headers = 1;

  // Get all rules (TODO Multiple rules)
  var rules = getRule();
  SPREADSHEET_ID = PropertiesService.getDocumentProperties().getProperty(PROPERTY_SS_ID);

  // Validate each rule for each row
  var ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  var sheets = ss.getSheets();

  var to = rules.to.split('!');
  var cc = rules.cc === null ? null : rules.cc.split('!');
  var bcc = rules.bcc === null ? null : rules.bcc.split('!');
  var subject = rules.subject.split('!');
  var body = rules.body.split('!');
  var comparison = Comparison[rules.comparison];
  var range = rules.range.split('!');
  var previous = rules.previous.split('!');

  var dataVisible = true;
  var rowsChecked = 0;
  while (dataVisible) {

    var rangeCell = ss.getSheetByName(range[0]).getRange(range[1]).getCell(rowsChecked + headers + 1, 1);

    if (rangeCell.getDisplayValue() === rules.value) {
      // Send emails

      var toCell = ss.getSheetByName(to[0]).getRange(to[1]).getCell(rowsChecked + headers + 1, 1);
      var ccCell = cc === null ? null : ss.getSheetByName(cc[0]).getRange(cc[1]).getCell(rowsChecked + headers + 1, 1);
      var bccCell = bcc === null ? null : ss.getSheetByName(bcc[0]).getRange(bcc[1]).getCell(rowsChecked + headers + 1, 1);
      var subjectCell = ss.getSheetByName(subject[0]).getRange(subject[1]).getCell(rowsChecked + headers + 1, 1);
      var bodyCell = ss.getSheetByName(body[0]).getRange(body[1]).getCell(rowsChecked + headers + 1, 1);

      //GMAILAPP
      GmailApp.sendEmail(toCell.getDisplayValue(), subjectCell.getDisplayValue(), bodyCell.getDisplayValue(), {
        bcc: (bccCell === null ? null : bccCell.getDisplayValue()),
        cc: (ccCell === null ? null : ccCell.getDisplayValue())
      });
      Logger.log('Send to: ' + toCell.getDisplayValue());
      Logger.log('Subject: ' + subjectCell.getDisplayValue());
      Logger.log('Body: ' + bodyCell.getDisplayValue());

      // Update Last sent:
      var previousCell = ss.getSheetByName(previous[0]).getRange(previous[1]).getCell(rowsChecked + headers + 1, 1);
      Logger.log('Previous Email: ' + previousCell.getDisplayValue());

      var now = new Date();

      // Date.getMonth is 0 indexed. January is 0.
      previousCell.setValue(now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate());
    }

    rowsChecked++;
    if (rowsChecked >= 5) {
      dataVisible = false;
    }
  }

}<commit_msg>Fixed an issue catching the Sheet id.<commit_after>function onInstall(e) {
  //Install triggers
  PropertiesService.getDocumentProperties().setProperty(PROPERTY_SS_ID, SpreadsheetApp.getActiveSpreadsheet().getId());

  onOpen(e);
}

function onOpen(e) {
  SpreadsheetApp.getUi()
    .createAddonMenu()//'Defect Tracker'
    .addItem('Set Up Email List', 'openListSetUpSidebar')
    .addToUi();

    PropertiesService.getDocumentProperties().setProperty(PROPERTY_SS_ID, SpreadsheetApp.getActiveSpreadsheet().getId());
}

/**
 * Creates an HTML sidebar for creating/viewing mailman rules.
 *
 */
function openListSetUpSidebar() {
  var ui = HtmlService.createHtmlOutputFromFile('ListSetupSidebar')
    .setTitle('Set Up Email List')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);

  SpreadsheetApp.getUi().showSidebar(ui);
}

function onTrigger() {
  Logger.log('Running trigger function...');

  var headers = 1;

  // Get all rules (TODO Multiple rules)
  var rules = getRule();
  SPREADSHEET_ID = PropertiesService.getDocumentProperties().getProperty(PROPERTY_SS_ID);

  // Validate each rule for each row
  var ss = SpreadsheetApp.openById(SPREADSHEET_ID);
  var sheets = ss.getSheets();

  var to = rules.to.split('!');
  var cc = rules.cc === null ? null : rules.cc.split('!');
  var bcc = rules.bcc === null ? null : rules.bcc.split('!');
  var subject = rules.subject.split('!');
  var body = rules.body.split('!');
  var comparison = Comparison[rules.comparison];
  var range = rules.range.split('!');
  var previous = rules.previous.split('!');

  var dataVisible = true;
  var rowsChecked = 0;
  while (dataVisible) {

    var rangeCell = ss.getSheetByName(range[0]).getRange(range[1]).getCell(rowsChecked + headers + 1, 1);

    if (rangeCell.getDisplayValue() === rules.value) {
      // Send emails

      var toCell = ss.getSheetByName(to[0]).getRange(to[1]).getCell(rowsChecked + headers + 1, 1);
      var ccCell = cc === null ? null : ss.getSheetByName(cc[0]).getRange(cc[1]).getCell(rowsChecked + headers + 1, 1);
      var bccCell = bcc === null ? null : ss.getSheetByName(bcc[0]).getRange(bcc[1]).getCell(rowsChecked + headers + 1, 1);
      var subjectCell = ss.getSheetByName(subject[0]).getRange(subject[1]).getCell(rowsChecked + headers + 1, 1);
      var bodyCell = ss.getSheetByName(body[0]).getRange(body[1]).getCell(rowsChecked + headers + 1, 1);

      //GMAILAPP
      GmailApp.sendEmail(toCell.getDisplayValue(), subjectCell.getDisplayValue(), bodyCell.getDisplayValue(), {
        bcc: (bccCell === null ? null : bccCell.getDisplayValue()),
        cc: (ccCell === null ? null : ccCell.getDisplayValue())
      });
      Logger.log('Send to: ' + toCell.getDisplayValue());
      Logger.log('Subject: ' + subjectCell.getDisplayValue());
      Logger.log('Body: ' + bodyCell.getDisplayValue());

      // Update Last sent:
      var previousCell = ss.getSheetByName(previous[0]).getRange(previous[1]).getCell(rowsChecked + headers + 1, 1);
      Logger.log('Previous Email: ' + previousCell.getDisplayValue());

      var now = new Date();

      // Date.getMonth is 0 indexed. January is 0.
      previousCell.setValue(now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate());
    }

    rowsChecked++;
    if (rowsChecked >= 5) {
      dataVisible = false;
    }
  }

}
<|endoftext|>


<commit_before>(function() {
    let objBrowser = chrome ? chrome : browser;

    //Get the blacklist domains option for the user
    objBrowser.runtime.sendMessage({func: "blacklist_domains"}, function(objResponse) {
        if(objResponse && objResponse.hasOwnProperty("resp")) {
            if(objResponse.resp == 1) {
                blacklistedDomainCheck();
            }
        }
    });

    //Detects if the current tab is in the blacklisted domains file
    function blacklistedDomainCheck() {
        let objBrowser = chrome ? chrome : browser;
        var arrBlacklistedDomains = [];
        var arrWhitelistedDomains = ["www.myetherwallet.com", "myetherwallet.com"];
        objBrowser.runtime.sendMessage({func: "blacklist_whitelist_domain_list"}, function (objResponse) {
            if (objResponse && objResponse.hasOwnProperty("resp")) {
                var objDomainLists = JSON.parse(objResponse.resp);
                var arrWhitelistedDomains = objDomainLists.whitelist;
                var arrBlacklistedDomains = objDomainLists.blacklist;
                return doBlacklistCheck(arrWhitelistedDomains, arrBlacklistedDomains);
            }
        });
    }

    function doBlacklistCheck(arrWhitelistedDomains, arrBlacklistedDomains)
    {
        //See if we are blocking all punycode domains.
        objBrowser.runtime.sendMessage({func: "block_punycode_domains"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                var strCurrentTab = window.location.hostname;
                var strCurrentTab = strCurrentTab.replace(/www\./g,'');

                if(objResponse.resp == 1) {
                    var arrDomainParts = strCurrentTab.split(".");
                    arrDomainParts.forEach(strDomainPart => {
                        if (strDomainPart.startsWith("xn--")) {
                            window.location.href = "https://harrydenley.com/EtherAddressLookup/phishing.html#" + (window.location.href) + "#punycode";
                            return false;
                        }
                    });
                }
            }
        });

        //Domain is whitelisted, don't check the blacklist.
        var strCurrentTab = window.location.hostname;
        strCurrentTab = strCurrentTab.replace(/www\./g,'');
        if(arrWhitelistedDomains.indexOf(strCurrentTab) >= 0) {
            console.log("Domain "+ strCurrentTab +" is whitelisted on EAL!");
            return false;
        }

        if(arrBlacklistedDomains.length > 0) {
            var isBlacklisted = arrBlacklistedDomains.indexOf(strCurrentTab) >= 0 ? true : false;

            //Only do Levenshtein if it's not blacklisted
            //Levenshtein - @sogoiii
            var blHolisticStatus = false;
            if(isBlacklisted === false && arrWhitelistedDomains.indexOf(strCurrentTab) < 0) {
                var strCurrentTab = punycode.toUnicode(strCurrentTab);
                var source = strCurrentTab.replace(/\./g, '');
                var intHolisticMetric = levenshtein(source, 'myetherwallet');
                var intHolisticLimit = 7 // How different can the word be?
                blHolisticStatus = (intHolisticMetric > 0 && intHolisticMetric < intHolisticLimit) ? true : false;
                if(blHolisticStatus === false) {
                    //Do edit distance against mycrypto
                    var intHolisticMetric = levenshtein(source, 'mycrypto');
                    blHolisticStatus = (intHolisticMetric > 0 && intHolisticMetric < 3) ? true : false;
                }
            }

            //If it's not in the whitelist and it is blacklisted or levenshtien wants to blacklist it.
            if ( arrWhitelistedDomains.indexOf(strCurrentTab) < 0 && (isBlacklisted === true || blHolisticStatus === true)) {
                console.warn(window.location.href + " is blacklisted by EAL - "+ (isBlacklisted ? "Blacklisted" : "Levenshtein Logic"));
                window.location.href = "https://harrydenley.com/EtherAddressLookup/phishing.html#"+ (window.location.href);
                return false;
            }
        }

        //Now do the 3rd party domain list check if they have that option enabled.
        objBrowser.runtime.sendMessage({func: "3rd_party_blacklist_domains"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                if(objResponse.resp == 1) {
                    objBrowser.runtime.sendMessage({func: "3p_blacklist_domain_list"}, function(objResponse) {
                        if(objResponse && objResponse.hasOwnProperty("resp")) {
                            var obj3rdPartyLists = JSON.parse(objResponse.resp);
                            var strCurrentTab = window.location.hostname;
                            var strCurrentTab = strCurrentTab.replace(/www\./g,'');

                            for(var str3rdPartyIdentifier in obj3rdPartyLists) {

                                if(obj3rdPartyLists[str3rdPartyIdentifier].format == "sha256") {
                                    strCurrentTab = sha256(strCurrentTab);
                                }

                                if(obj3rdPartyLists[str3rdPartyIdentifier].domains.indexOf(strCurrentTab) >= 0) {
                                    console.warn(window.location.href + " is blacklisted by "+ str3rdPartyIdentifier);
                                    window.location.href = "https://harrydenley.com/EtherAddressLookup/phishing-"+ str3rdPartyIdentifier +".html#"+ (window.location.href);
                                    return false;
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    function levenshtein(a, b) {
        if(a.length == 0) return b.length;
        if(b.length == 0) return a.length;

        // swap to save some memory O(min(a,b)) instead of O(a)
        if(a.length > b.length) {
            var tmp = a;
            a = b;
            b = tmp;
        }

        var row = [];
        // init the row
        for(var i = 0; i <= a.length; i++){
            row[i] = i;
        }

        // fill in the rest
        for(var i = 1; i <= b.length; i++){
            var prev = i;
            for(var j = 1; j <= a.length; j++){
                var val;
                if(b.charAt(i-1) == a.charAt(j-1)){
                    val = row[j-1]; // match
                } else {
                    val = Math.min(row[j-1] + 1, // substitution
                        prev + 1,     // insertion
                        row[j] + 1);  // deletion
                }
                row[j - 1] = prev;
                prev = val;
            }
            row[a.length] = prev;
        }

        return row[a.length];
    }
})();
<commit_msg>Added logic to show the type of block<commit_after>(function() {
    let objBrowser = chrome ? chrome : browser;

    //Get the blacklist domains option for the user
    objBrowser.runtime.sendMessage({func: "blacklist_domains"}, function(objResponse) {
        if(objResponse && objResponse.hasOwnProperty("resp")) {
            if(objResponse.resp == 1) {
                blacklistedDomainCheck();
            }
        }
    });

    //Detects if the current tab is in the blacklisted domains file
    function blacklistedDomainCheck() {
        let objBrowser = chrome ? chrome : browser;
        var arrBlacklistedDomains = [];
        var arrWhitelistedDomains = ["www.myetherwallet.com", "myetherwallet.com"];
        objBrowser.runtime.sendMessage({func: "blacklist_whitelist_domain_list"}, function (objResponse) {
            if (objResponse && objResponse.hasOwnProperty("resp")) {
                var objDomainLists = JSON.parse(objResponse.resp);
                var arrWhitelistedDomains = objDomainLists.whitelist;
                var arrBlacklistedDomains = objDomainLists.blacklist;
                return doBlacklistCheck(arrWhitelistedDomains, arrBlacklistedDomains);
            }
        });
    }

    function doBlacklistCheck(arrWhitelistedDomains, arrBlacklistedDomains)
    {
        //See if we are blocking all punycode domains.
        objBrowser.runtime.sendMessage({func: "block_punycode_domains"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                var strCurrentTab = window.location.hostname;
                var strCurrentTab = strCurrentTab.replace(/www\./g,'');

                if(objResponse.resp == 1) {
                    var arrDomainParts = strCurrentTab.split(".");
                    arrDomainParts.forEach(strDomainPart => {
                        if (strDomainPart.startsWith("xn--")) {
                            window.location.href = "https://harrydenley.com/EtherAddressLookup/phishing.html#" + (window.location.href) + "#punycode";
                            return false;
                        }
                    });
                }
            }
        });

        //Domain is whitelisted, don't check the blacklist.
        var strCurrentTab = window.location.hostname;
        strCurrentTab = strCurrentTab.replace(/www\./g,'');
        if(arrWhitelistedDomains.indexOf(strCurrentTab) >= 0) {
            console.log("Domain "+ strCurrentTab +" is whitelisted on EAL!");
            return false;
        }

        if(arrBlacklistedDomains.length > 0) {
            var isBlacklisted = arrBlacklistedDomains.indexOf(strCurrentTab) >= 0 ? true : false;

            //Only do Levenshtein if it's not blacklisted
            //Levenshtein - @sogoiii
            var blHolisticStatus = false;
            if(isBlacklisted === false && arrWhitelistedDomains.indexOf(strCurrentTab) < 0) {
                var strCurrentTab = punycode.toUnicode(strCurrentTab);
                var source = strCurrentTab.replace(/\./g, '');
                var intHolisticMetric = levenshtein(source, 'myetherwallet');
                var intHolisticLimit = 7 // How different can the word be?
                blHolisticStatus = (intHolisticMetric > 0 && intHolisticMetric < intHolisticLimit) ? true : false;
                if(blHolisticStatus === false) {
                    //Do edit distance against mycrypto
                    var intHolisticMetric = levenshtein(source, 'mycrypto');
                    blHolisticStatus = (intHolisticMetric > 0 && intHolisticMetric < 3) ? true : false;
                }
            }

            //If it's not in the whitelist and it is blacklisted or levenshtien wants to blacklist it.
            if ( arrWhitelistedDomains.indexOf(strCurrentTab) < 0 && (isBlacklisted === true || blHolisticStatus === true)) {
                console.warn(window.location.href + " is blacklisted by EAL - "+ (isBlacklisted ? "Blacklisted" : "Levenshtein Logic"));
                window.location.href = "https://harrydenley.com/EtherAddressLookup/phishing.html#"+ (window.location.href) +"#"+ (isBlacklisted ? "blacklisted" : "levenshtein");
                return false;
            }
        }

        //Now do the 3rd party domain list check if they have that option enabled.
        objBrowser.runtime.sendMessage({func: "3rd_party_blacklist_domains"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                if(objResponse.resp == 1) {
                    objBrowser.runtime.sendMessage({func: "3p_blacklist_domain_list"}, function(objResponse) {
                        if(objResponse && objResponse.hasOwnProperty("resp")) {
                            var obj3rdPartyLists = JSON.parse(objResponse.resp);
                            var strCurrentTab = window.location.hostname;
                            var strCurrentTab = strCurrentTab.replace(/www\./g,'');

                            for(var str3rdPartyIdentifier in obj3rdPartyLists) {

                                if(obj3rdPartyLists[str3rdPartyIdentifier].format == "sha256") {
                                    strCurrentTab = sha256(strCurrentTab);
                                }

                                if(obj3rdPartyLists[str3rdPartyIdentifier].domains.indexOf(strCurrentTab) >= 0) {
                                    console.warn(window.location.href + " is blacklisted by "+ str3rdPartyIdentifier);
                                    window.location.href = "https://harrydenley.com/EtherAddressLookup/phishing-"+ str3rdPartyIdentifier +".html#"+ (window.location.href);
                                    return false;
                                }
                            }
                        }
                    });
                }
            }
        });
    }

    function levenshtein(a, b) {
        if(a.length == 0) return b.length;
        if(b.length == 0) return a.length;

        // swap to save some memory O(min(a,b)) instead of O(a)
        if(a.length > b.length) {
            var tmp = a;
            a = b;
            b = tmp;
        }

        var row = [];
        // init the row
        for(var i = 0; i <= a.length; i++){
            row[i] = i;
        }

        // fill in the rest
        for(var i = 1; i <= b.length; i++){
            var prev = i;
            for(var j = 1; j <= a.length; j++){
                var val;
                if(b.charAt(i-1) == a.charAt(j-1)){
                    val = row[j-1]; // match
                } else {
                    val = Math.min(row[j-1] + 1, // substitution
                        prev + 1,     // insertion
                        row[j] + 1);  // deletion
                }
                row[j - 1] = prev;
                prev = val;
            }
            row[a.length] = prev;
        }

        return row[a.length];
    }
})();
<|endoftext|>


<commit_before>(function() {
  if (document.location.hostname === "josephduffy.co.uk") {
    // Don't load analytics for noanalytics.josephduffy.co.uk or onion service
    return;
  }

  var _paq = window._paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(["disableCookies"]);
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="https://analytics.josephduffy.co.uk/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
})();
<commit_msg>Correct logic for loading analytics<commit_after>(function() {
  if (document.location.hostname !== "josephduffy.co.uk") {
    // Don't load analytics for noanalytics.josephduffy.co.uk or onion service
    return;
  }

  var _paq = window._paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(["disableCookies"]);
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="https://analytics.josephduffy.co.uk/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
})();
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Audio player for the various sounds that are commonly used in PhET games.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Sound = require( 'VIBE/Sound' );
  var dingSound = require( 'audio!VEGAS/ding' );
  var boingSound = require( 'audio!VEGAS/boing' );
  var trumpetSound = require( 'audio!VEGAS/trumpet' );
  var cheerSound = require( 'audio!VEGAS/cheer' );

  // constants
  var CORRECT_ANSWER = new Sound( dingSound );
  var WRONG_ANSWER = new Sound( boingSound );
  var IMPERFECT_SCORE = new Sound( trumpetSound );
  var PERFECT_SCORE = new Sound( cheerSound );

  /**
   * @param soundEnabledProperty
   * @constructor
   */
  function GameAudioPlayer( soundEnabledProperty ) {
    this.soundEnabledProperty = soundEnabledProperty;
  }

  return inherit( Object, GameAudioPlayer, {

    correctAnswer: function() {
      if ( this.soundEnabledProperty.value ) {
        CORRECT_ANSWER.play();
      }
    },

    wrongAnswer: function() {
      if ( this.soundEnabledProperty.value ) {
        WRONG_ANSWER.play();
      }
    },
    gameOverZeroScore: function() {
      if ( this.soundEnabledProperty.value ) {
        WRONG_ANSWER.play();
      }
    },

    gameOverImperfectScore: function() {
      if ( this.soundEnabledProperty.value ) {
        IMPERFECT_SCORE.play();
      }
    },

    gameOverPerfectScore: function() {
      if ( this.soundEnabledProperty.value ) {
        PERFECT_SCORE.play();
      }
    }
  } );
} );<commit_msg>Minor cleanup.<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Audio player for the various sounds that are commonly used in PhET games.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Sound = require( 'VIBE/Sound' );
  var dingSound = require( 'audio!VEGAS/ding' );
  var boingSound = require( 'audio!VEGAS/boing' );
  var trumpetSound = require( 'audio!VEGAS/trumpet' );
  var cheerSound = require( 'audio!VEGAS/cheer' );

  // constants
  var CORRECT_ANSWER = new Sound( dingSound );
  var WRONG_ANSWER = new Sound( boingSound );
  var IMPERFECT_SCORE = new Sound( trumpetSound );
  var PERFECT_SCORE = new Sound( cheerSound );

  /**
   * @param soundEnabledProperty
   * @constructor
   */
  function GameAudioPlayer( soundEnabledProperty ) {
    this.soundEnabledProperty = soundEnabledProperty;
  }

  return inherit( Object, GameAudioPlayer, {

    correctAnswer: function() {
      if ( this.soundEnabledProperty.value ) {
        CORRECT_ANSWER.play();
      }
    },

    wrongAnswer: function() {
      if ( this.soundEnabledProperty.value ) {
        WRONG_ANSWER.play();
      }
    },

    gameOverZeroScore: function() {
      if ( this.soundEnabledProperty.value ) {
        WRONG_ANSWER.play();
      }
    },

    gameOverImperfectScore: function() {
      if ( this.soundEnabledProperty.value ) {
        IMPERFECT_SCORE.play();
      }
    },

    gameOverPerfectScore: function() {
      if ( this.soundEnabledProperty.value ) {
        PERFECT_SCORE.play();
      }
    }
  } );
} );<|endoftext|>