<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var error = require('../lib/error');

var BookCopyModelSchema = new Schema({
  date: { type: Date, default: Date.now, index: true },
},{
  toObject:  { virtuals: true },
  toJSON:    { virtuals: true }
});

BookCopyModelSchema.virtual('bookCopyId').get(function(){
  return this.id;
});

BookCopyModelSchema.pre('save', function (next) {
  if ('invalid' == this.name) return next(new error.HttpResponseError('Invalid Book Copy'));
  next();
});

module.exports = mongoose.model('BookCopyModel', BookCopyModelSchema);<commit_msg>BookCopy status<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var error = require('../lib/error');

var BookCopyModelSchema = new Schema({
  date: { type: Date, default: Date.now, index: true },
  status: { type: String, default: 'available', required: true, index: true },
},{
  toObject:  { virtuals: true },
  toJSON:    { virtuals: true }
});

BookCopyModelSchema.virtual('bookCopyId').get(function(){
  return this.id;
});

BookCopyModelSchema.pre('save', function (next) {
  if ('invalid' == this.name) return next(new error.HttpResponseError('Invalid Book Copy'));
  next();
});

module.exports = mongoose.model('BookCopyModel', BookCopyModelSchema);<|endoftext|>


<commit_before><commit_msg>Added more unit tests for  method of Task class<commit_after><|endoftext|>


<commit_before><commit_msg>Added test for Bird.friends.list<commit_after><|endoftext|>


<commit_before>
var TrigGrammerListener = function(trigStr, trig, ruleHandler, options) {
  this.trigStr = trigStr;
  this.parser = trig.parser;
  this.ruleHandler = ruleHandler;
  this.prefixMap = { _prefixes: {}};
  this.prefixSymbolMap = { };
  var prefixUsageMap = {};
  this.prefixMap.get = function(prefixName){
    if(!(prefixName in this.prefixMap._prefixes)) return undefined;
    var count = prefixUsageMap[prefixName] || 0;
    prefixUsageMap[prefixName] = count + 1;
    return this.prefixMap._prefixes[prefixName];
  }.bind(this)
  this.prefixMap.put = function(prefix, ctx){
    if(this.finalized) throw new Error("Listener fired after finalization.");
    this.prefixMap._prefixes[prefix.name] = prefix;
    this.prefixSymbolMap[prefix.name] = ctx;
  }.bind(this)
  this.prefixMap.getUnusedAsError = function(prefixName){
    return Object.keys(this.prefixMap._prefixes).filter(function(prefix){
      return !prefixUsageMap[prefix]
    }.bind(this)).map(function(prefix){
      prefix = this.prefixMap._prefixes[prefix]
      return this.ruleHandler.createErrorFromNode(prefix.name_symbol,
         "Unused prefix: " + prefix.name, prefix.name.length);
    }.bind(this))
  }.bind(this)

  this.graphs = [];
  this.macros = [];
  this.errors = [];
  this.defaultStmts = [];
  this.finalized = false;
  this.syntaxErrors = trig.syntaxErrors;
  this.analysisErrors = [];
  this.options = options || {
    allowEmptyDefaultGraph: false
  };
};

TrigGrammerListener.prototype.handleDefaultTriples = function(subjectOrLabel, predicateObjectList){
  if(!subjectOrLabel || !predicateObjectList) return;
  var results = []
  subjectOrLabel = this.ruleHandler.createNode(subjectOrLabel)
  predicateObjectList = this.ruleHandler.createNode(predicateObjectList)
  var results = this.ruleHandler.createTriples(subjectOrLabel, predicateObjectList, results);
  this.defaultStmts = this.defaultStmts.concat(results);

};
TrigGrammerListener.prototype.handleGraphTriples = function(rootTriplesBlock, iri, graphToken){

    var flattenedTriples = this.flattenTriplesBlock(rootTriplesBlock);

    if(iri){
      this.graphs.push(this.ruleHandler.handleGraph(flattenedTriples, iri, graphToken));
    }else{
      flattenedTriples.forEach(function(triplesBlock){
        triplesBlock.children.forEach(function(triples){
          if(!triples.children && triples.symbol.type === 2){
            //the type here is: triplesOrGraph which is strange...
            return;
          }
          var s = this.ruleHandler.createNode(triples.children[0]);
          var po = this.ruleHandler.createNode(triples.children[1]);
          var results = this.ruleHandler.createTriples(s, po);
          this.defaultStmts = this.defaultStmts.concat(results);
        }.bind(this));
      }.bind(this));
    }

}

TrigGrammerListener.prototype.flattenTriplesBlock = function(triplesBlock, results){
  results = results || [ triplesBlock ];
  triplesBlock.children.forEach(function(child, i){
    var ruleName = this.parser.ruleNames[child.ruleIndex];
    if(ruleName === 'triplesBlock'){
      results.push(child);
      triplesBlock.children.splice(i, 1);
      this.flattenTriplesBlock(child, results);
    }
  }.bind(this));
  return results;
};

TrigGrammerListener.prototype.finalize = function(){
  try{
    this.finalized = true;
    var errors = [];
    this.allGraphs.forEach(function(graph){
        errors = errors.concat(graph.finalize(this.prefixMap));
    }.bind(this));
    var unusedPrefixes = this.prefixMap.getUnusedAsError()
    errors = errors.concat(unusedPrefixes)
    return errors;
  }catch(e){
    console.error("Error finalizing trig doc")
    console.error(e);
  }
};

TrigGrammerListener.prototype.handleWrappedGraph = function(wrappedGraph, iri){
  var rootTriplesBlock = wrappedGraph.children.find(function(child){
    return this.parser.ruleNames[child.ruleIndex] === 'triplesBlock';
  }.bind(this));
  this.handleGraphTriples(rootTriplesBlock, iri, this.ruleHandler.createNode(wrappedGraph));

}

TrigGrammerListener.prototype.handleBlock = function(ctx){

    var ruleName = this.parser.ruleNames[ctx.ruleIndex];
    if(!ruleName) return;
    var labelOrSubject = ctx.children.filter(function(child){
      return this.parser.ruleNames[child.ruleIndex] === 'labelOrSubject';
    }.bind(this))[0]

    if(labelOrSubject){
        var iri = labelOrSubject.children.filter(function(child){
          return this.parser.ruleNames[child.ruleIndex] === 'iri';
        }.bind(this))[0];
        var blank_node = labelOrSubject.children.filter(function(child){
          return this.parser.ruleNames[child.ruleIndex] === 'BlankNode';
        }.bind(this))[0];

    }

    var wrappedGraph = ctx.children.filter(function(child){
      return this.parser.ruleNames[child.ruleIndex] === 'wrappedGraph';
    }.bind(this))[0];

    var predicateObjectList = ctx.children.find(function(child){
      return this.parser.ruleNames[child.ruleIndex] === 'predicateObjectList';
    }.bind(this));

    if(wrappedGraph){
      this.handleWrappedGraph(wrappedGraph, iri);
    }
    else if(labelOrSubject && predicateObjectList){
      this.handleDefaultTriples(labelOrSubject, predicateObjectList);
    }

}
TrigGrammerListener.prototype.enterEveryRule = function(ctx){
  if(this.finalized) throw new Error("Listener fired after finalization.");
  var ruleName = this.parser.ruleNames[ctx.ruleIndex];

  try{
    switch(ruleName){

      case 'prefixID':
        var prefix = this.ruleHandler.handlePrefixID(ctx, this.analysisErrors);
        if(prefix){
          if(prefix.name in this.prefixMap){
            var e = this.ruleHandler.createErrorFromNode(prefix.name_symbol,
               "Prefix already declared: " + prefix.name, prefix.name.length);
            this.analysisErrors.push(e);
          }else{
            this.prefixMap.put(prefix, ctx);
          }
        }

        break;

      case 'block':
        this.handleBlock(ctx.children[0]);
        break;

      case 'wrappedGraph':
        if(this.parser.ruleNames[ctx.parentCtx.ruleIndex] === 'block'){
          this.handleWrappedGraph(ctx);
        }
        break;

      case 'triplesBlock':
        var parentType = ctx.parser.ruleNames[ctx.parentCtx.ruleIndex];
        if(parentType === 'trigDoc'){
            this.handleDefaultTriples(ctx);
        }
        break;
      case 'macro':
        this.macros.push(this.ruleHandler.handleMacro(ctx));
        break;

      default:
        break;

    }
  }catch(e){
    this.handleError(e)
    console.error(e);
  }

};
TrigGrammerListener.prototype.handleError = function(){}
TrigGrammerListener.prototype.getDocument = function(){

  var graphs = this.graphs;
  var defaultGraph;

  if(this.defaultStmts.length !== 0 || this.options.allowEmptyDefaultGraph){
    var trigDoc = this.parser.trigDoc();
    defaultGraph = this.ruleHandler.createDefaultGraph(this.defaultStmts, trigDoc);
  }

  var allGraphs = defaultGraph ? [].concat.apply([], [graphs, [ defaultGraph ]]) : graphs;
  this.allGraphs = allGraphs;
  var result =  {
    prefixes: this.prefixMap,
    graphs: graphs,
    macros: this.macros,
    errors: this.errors,
    syntaxErrors: this.syntaxErrors,
    allGraphs: this.allGraphs,
    defaultGraph: defaultGraph,
    analysisErrors: this.analysisErrors,
    getStatements: function(){
      return allGraphs.reduce(function(acc, graph){
        acc = acc.concat(graph.getStatements());
        return acc;
      },[]);
      //return [].concat.apply([], [stmts, this.defaultGraph ? this.defaultGraph.getStatements() : []]);
    }
  };
  result.analysisErrors = result.analysisErrors.concat(this.finalize());

  return result;
};
TrigGrammerListener.prototype.prefixId = function(ctx){};
TrigGrammerListener.prototype.prefixID = function(ctx){};
TrigGrammerListener.prototype.graph = function(ctx){};
TrigGrammerListener.prototype.triplesBlock = function(ctx){};
TrigGrammerListener.prototype.macro = function(ctx){};
TrigGrammerListener.prototype.visitTerminal = function(){};
TrigGrammerListener.prototype.exitEveryRule = function(){};
TrigGrammerListener.prototype.exitRule = function(){};
TrigGrammerListener.prototype.visitErrorNode = function(ctx){
  this.errors.push(ctx);
};
module.exports = TrigGrammerListener;
<commit_msg>fixes unused prefix analysiserror<commit_after>
var TrigGrammerListener = function(trigStr, trig, ruleHandler, options) {
  this.trigStr = trigStr;
  this.parser = trig.parser;
  this.ruleHandler = ruleHandler;
  this.prefixMap = { _prefixes: {}};
  this.prefixSymbolMap = { };
  var prefixUsageMap = {};
  this.prefixMap.get = function(prefixName){
    if(!(prefixName in this.prefixMap._prefixes)) return undefined;
    var count = prefixUsageMap[prefixName] || 0;
    prefixUsageMap[prefixName] = count + 1;
    return this.prefixMap._prefixes[prefixName];
  }.bind(this)
  this.prefixMap.put = function(prefix, ctx){
    if(this.finalized) throw new Error("Listener fired after finalization.");
    this.prefixMap._prefixes[prefix.name] = prefix;
    this.prefixSymbolMap[prefix.name] = ctx;
  }.bind(this)
  this.prefixMap.getUnusedAsError = function(prefixName){
    return Object.keys(this.prefixMap._prefixes).filter(function(prefix){
      return !prefixUsageMap[prefix]
    }.bind(this)).map(function(prefix){
      prefix = this.prefixMap._prefixes[prefix]
      return this.ruleHandler.createErrorFromNode(prefix.name_symbol,
         "Unused prefix: " + prefix.name, prefix.name.length);
    }.bind(this))
  }.bind(this)

  this.graphs = [];
  this.macros = [];
  this.errors = [];
  this.defaultStmts = [];
  this.finalized = false;
  this.syntaxErrors = trig.syntaxErrors;
  this.analysisErrors = [];
  this.options = options || {
    allowEmptyDefaultGraph: false
  };
};

TrigGrammerListener.prototype.handleDefaultTriples = function(subjectOrLabel, predicateObjectList){
  if(!subjectOrLabel || !predicateObjectList) return;
  var results = []
  subjectOrLabel = this.ruleHandler.createNode(subjectOrLabel)
  predicateObjectList = this.ruleHandler.createNode(predicateObjectList)
  var results = this.ruleHandler.createTriples(subjectOrLabel, predicateObjectList, results);
  this.defaultStmts = this.defaultStmts.concat(results);

};
TrigGrammerListener.prototype.handleGraphTriples = function(rootTriplesBlock, iri, graphToken){

    var flattenedTriples = this.flattenTriplesBlock(rootTriplesBlock);

    if(iri){
      this.graphs.push(this.ruleHandler.handleGraph(flattenedTriples, iri, graphToken));
    }else{
      flattenedTriples.forEach(function(triplesBlock){
        triplesBlock.children.forEach(function(triples){
          if(!triples.children && triples.symbol.type === 2){
            //the type here is: triplesOrGraph which is strange...
            return;
          }
          var s = this.ruleHandler.createNode(triples.children[0]);
          var po = this.ruleHandler.createNode(triples.children[1]);
          var results = this.ruleHandler.createTriples(s, po);
          this.defaultStmts = this.defaultStmts.concat(results);
        }.bind(this));
      }.bind(this));
    }

}

TrigGrammerListener.prototype.flattenTriplesBlock = function(triplesBlock, results){
  results = results || [ triplesBlock ];
  triplesBlock.children.forEach(function(child, i){
    var ruleName = this.parser.ruleNames[child.ruleIndex];
    if(ruleName === 'triplesBlock'){
      results.push(child);
      triplesBlock.children.splice(i, 1);
      this.flattenTriplesBlock(child, results);
    }
  }.bind(this));
  return results;
};

TrigGrammerListener.prototype.finalize = function(){
  try{
    this.finalized = true;
    var errors = [];
    this.allGraphs.forEach(function(graph){
        errors = errors.concat(graph.finalize(this.prefixMap));
    }.bind(this));
    var unusedPrefixes = this.prefixMap.getUnusedAsError()
    errors = errors.concat(unusedPrefixes)
    return errors;
  }catch(e){
    console.error("Error finalizing trig doc")
    console.error(e);
  }
};

TrigGrammerListener.prototype.handleWrappedGraph = function(wrappedGraph, iri){
  var rootTriplesBlock = wrappedGraph.children.find(function(child){
    return this.parser.ruleNames[child.ruleIndex] === 'triplesBlock';
  }.bind(this));
  this.handleGraphTriples(rootTriplesBlock, iri, this.ruleHandler.createNode(wrappedGraph));

}

TrigGrammerListener.prototype.handleBlock = function(ctx){

    var ruleName = this.parser.ruleNames[ctx.ruleIndex];
    if(!ruleName) return;
    var labelOrSubject = ctx.children.filter(function(child){
      return this.parser.ruleNames[child.ruleIndex] === 'labelOrSubject';
    }.bind(this))[0]

    if(labelOrSubject){
        var iri = labelOrSubject.children.filter(function(child){
          return this.parser.ruleNames[child.ruleIndex] === 'iri';
        }.bind(this))[0];
        var blank_node = labelOrSubject.children.filter(function(child){
          return this.parser.ruleNames[child.ruleIndex] === 'BlankNode';
        }.bind(this))[0];

    }

    var wrappedGraph = ctx.children.filter(function(child){
      return this.parser.ruleNames[child.ruleIndex] === 'wrappedGraph';
    }.bind(this))[0];

    var predicateObjectList = ctx.children.find(function(child){
      return this.parser.ruleNames[child.ruleIndex] === 'predicateObjectList';
    }.bind(this));

    if(wrappedGraph){
      this.handleWrappedGraph(wrappedGraph, iri);
    }
    else if(labelOrSubject && predicateObjectList){
      this.handleDefaultTriples(labelOrSubject, predicateObjectList);
    }

}
TrigGrammerListener.prototype.enterEveryRule = function(ctx){
  if(this.finalized) throw new Error("Listener fired after finalization.");
  var ruleName = this.parser.ruleNames[ctx.ruleIndex];

  try{
    switch(ruleName){

      case 'prefixID':
        var prefix = this.ruleHandler.handlePrefixID(ctx, this.analysisErrors);
        if(prefix){
          if(this.prefixMap.get(prefix.name)){
            var e = this.ruleHandler.createErrorFromNode(prefix.name_symbol,
               "Prefix already declared: " + prefix.name, prefix.name.length);
            this.analysisErrors.push(e);
          }else{
            this.prefixMap.put(prefix, ctx);
          }
        }

        break;

      case 'block':
        this.handleBlock(ctx.children[0]);
        break;

      case 'wrappedGraph':
        if(this.parser.ruleNames[ctx.parentCtx.ruleIndex] === 'block'){
          this.handleWrappedGraph(ctx);
        }
        break;

      case 'triplesBlock':
        var parentType = ctx.parser.ruleNames[ctx.parentCtx.ruleIndex];
        if(parentType === 'trigDoc'){
            this.handleDefaultTriples(ctx);
        }
        break;
      case 'macro':
        this.macros.push(this.ruleHandler.handleMacro(ctx));
        break;

      default:
        break;

    }
  }catch(e){
    this.handleError(e)
    console.error(e);
  }

};
TrigGrammerListener.prototype.handleError = function(){}
TrigGrammerListener.prototype.getDocument = function(){

  var graphs = this.graphs;
  var defaultGraph;

  if(this.defaultStmts.length !== 0 || this.options.allowEmptyDefaultGraph){
    var trigDoc = this.parser.trigDoc();
    defaultGraph = this.ruleHandler.createDefaultGraph(this.defaultStmts, trigDoc);
  }

  var allGraphs = defaultGraph ? [].concat.apply([], [graphs, [ defaultGraph ]]) : graphs;
  this.allGraphs = allGraphs;
  var result =  {
    prefixes: this.prefixMap,
    graphs: graphs,
    macros: this.macros,
    errors: this.errors,
    syntaxErrors: this.syntaxErrors,
    allGraphs: this.allGraphs,
    defaultGraph: defaultGraph,
    analysisErrors: this.analysisErrors,
    getStatements: function(){
      return allGraphs.reduce(function(acc, graph){
        acc = acc.concat(graph.getStatements());
        return acc;
      },[]);
      //return [].concat.apply([], [stmts, this.defaultGraph ? this.defaultGraph.getStatements() : []]);
    }
  };
  result.analysisErrors = result.analysisErrors.concat(this.finalize());

  return result;
};
TrigGrammerListener.prototype.prefixId = function(ctx){};
TrigGrammerListener.prototype.prefixID = function(ctx){};
TrigGrammerListener.prototype.graph = function(ctx){};
TrigGrammerListener.prototype.triplesBlock = function(ctx){};
TrigGrammerListener.prototype.macro = function(ctx){};
TrigGrammerListener.prototype.visitTerminal = function(){};
TrigGrammerListener.prototype.exitEveryRule = function(){};
TrigGrammerListener.prototype.exitRule = function(){};
TrigGrammerListener.prototype.visitErrorNode = function(ctx){
  this.errors.push(ctx);
};
module.exports = TrigGrammerListener;
<|endoftext|>


<commit_before>//Need to do this before requiring moongose, tungus is tingodb
var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    uuidPplugin = require('../lib/mongoose-uuid'),
    timestamps = require('mongoose-timestamp');

var Location = new Schema({
    uuid        : { type: String/*, required: true*/, index: { unique: true, sparse: true } },
    name        : {type: String, trim: true},
    description : {type: String, trim: true},
    geolocation : {
        lng: Number,
        lat: Number
    }
});

Location.plugin(uuidPplugin);
Location.plugin(timestamps);

module.exports = mongoose.model('Location', Location);
<commit_msg>MODEL: Locations added slug<commit_after>//Need to do this before requiring moongose, tungus is tingodb
var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    uuidPplugin = require('../lib/mongoose-uuid'),
    timestamps = require('mongoose-timestamp'),
    URLSlugs = require('mongoose-url-slugs');

var Location = new Schema({
    uuid        : { type: String/*, required: true*/, index: { unique: true, sparse: true } },
    name        : {type: String, trim: true},
    description : {type: String, trim: true},
    geolocation : {
        lng: Number,
        lat: Number
    }
});

Location.plugin(uuidPplugin);
Location.plugin(timestamps);
Location.plugin(URLSlugs('name', {field: 'slug'}));

module.exports = mongoose.model('Location', Location);
<|endoftext|>


<commit_before>module.exports = function ( mongoose ) {
  var Packages = new mongoose.Schema({
    name : { type: String, required: true, unique: true, index: true, lowercase: true },
    repo : { type: String, required: true },
    script : { type: String, required: true },
    description : { type: String, required: true },
    keywords : { type: Array },
    ui : { type: Boolean }
  });

  Packages.path('name').validate(function ( v ) {
    return /^[a-zA-Z][a-zA-Z0-9\-]{0,29}$/.test( v );
  }, 'Package names must be between 1 and 30 characters, and contain only letters, numbers and dashes, and must begin with a letter.' );

  Packages.path('repo').validate(function ( v ) {
    return /^[a-zA-Z0-9-_]*\/[a-zA-Z0-9-_]*$/.test( v );
  }, 'Repos must be of the GitHub format "owner/reponame"');

  // TODO More efficient querying???
  Packages.statics.search = function ( query, callback ) {
    this.find({}).or([
      { name : { $regex : query, $options : '-i' }},
      { keywords : query },
      { description : { $regex : query, $options : '-i' }}
    ]).exec( callback );
  };

  return Packages;
};
<commit_msg>Add iso formatter for Dates, add dummy booleans for instrument/effects<commit_after>module.exports = function ( mongoose ) {
  var Packages = new mongoose.Schema({
    name : { type: String, required: true, unique: true, index: true, lowercase: true },
    repo : { type: String, required: true },
    script : { type: String, required: true },
    scriptFile : { type: Buffer, require: true },
    description : { type: String, required: true },
    keywords : { type: Array },
    updated : { type: Date, default: Date.now, set: isoToDate },

    // Not yet implemented
    ui : { type: Boolean },
    instrument : { type: Boolean },
    effect : { type: Boolean }
  });

  // Package name must be between 1 and 30 chars, only letters
  // numbers, dashes and must begin with a letter
  Packages.path('name').validate(function ( v ) {
    return /^[a-zA-Z][a-zA-Z0-9\-]{0,29}$/.test( v );
  }, 'Package names must be between 1 and 30 characters, and contain only letters, numbers and dashes, and must begin with a letter.' );

  // Repo must be of GitHub repo format "account/reponame"
  Packages.path('repo').validate(function ( v ) {
    return /^[a-zA-Z0-9-_]*\/[a-zA-Z0-9-_]*$/.test( v );
  }, 'Repos must be of the GitHub format "owner/reponame"');

  // TODO More efficient querying???
  // TODO Better matching???
  Packages.statics.search = function ( query, callback ) {
    this.find({}).or([
      { name : { $regex : query, $options : '-i' }},
      { keywords : query },
      { description : { $regex : query, $options : '-i' }}
    ]).exec( callback );
  };

  return Packages;
};

// Takes an ISO6801 string and converts it to a date object
function isoToDate( s ) {
  if ( s instanceof Date ) { return s; }
  if ( typeof s === 'string' ) { return new Date( s ); }
};
<|endoftext|>


<commit_before>function clampIntRange(num, min, max) {
	num = Math.floor(num);
	if (num < min) num = min;
	if (typeof max !== 'undefined' && num > max) num = max;
	return num;
}
exports.BattleMovedex = {
	beatup: {
		inherit: true,
		basePower: 10,
		basePowerCallback: undefined,
		desc: "Does one hit for the user and each other unfainted non-egg active and non-active Pokemon on the user's side without a status problem."
	},
	bind: {
		inherit: true,
		accuracy: 75
	},
	bonerush: {
		inherit: true,
		accuracy: 80
	},
	bulletseed: {
		inherit: true,
		basePower: 10
	},
	clamp: {
		inherit: true,
		accuracy: 75,
		pp: 10
	},
	cottonspore: {
		inherit: true,
		accuracy: 85
	},
	covet: {
		inherit: true,
		basePower: 40
	},
	crabhammer: {
		inherit: true,
		accuracy: 85
	},
	detect: {
		inherit: true,
		//desc: "",
		priority: 3
	},
	disable: {
		inherit: true,
		accuracy: 80
	},
	doomdesire: {
		inherit: true,
		accuracy: 85,
		basePower: 120
	},
	drainpunch: {
		inherit: true,
		basePower: 60,
		pp: 5
	},
	extremespeed: {
		inherit: true,
		shortDesc: "Usually goes first.",
		priority: 1
	},
	fakeout: {
		inherit: true,
		shortDesc: "Usually hits first; first turn out only; target flinch.",
		priority: 1
	},
	feint: {
		inherit: true,
		basePower: 50
	},
	firespin: {
		inherit: true,
		accuracy: 70,
		basePower: 15
	},
	furycutter: {
		inherit: true,
		basePower: 10
	},
	futuresight: {
		inherit: true,
		accuracy: 90,
		basePower: 80,
		pp: 15
	},
	gigadrain: {
		inherit: true,
		basePower: 60
	},
	glare: {
		inherit: true,
		accuracy: 75
	},
	growth: {
		inherit: true,
		desc: "Raises the user's Special Attack by 1 stage.",
		shortDesc: "Boosts the user's Sp. Atk by 1.",
		onModifyMove: undefined,
		boosts: {
			spa: 1
		}
	},
	hijumpkick: {
		inherit: true,
		basePower: 100,
		desc: "If this attack misses the target, the user takes half of the damage it would have dealt in recoil damage.",
		shortDesc: "User takes half damage it would have dealt if miss.",
		pp: 20,
		onMoveFail: function(target, source, move) {
			var damage = this.getDamage(source, target, move, true);
			this.damage(clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
		}
	},
	iciclespear: {
		inherit: true,
		basePower: 10
	},
	jumpkick: {
		inherit: true,
		basePower: 85,
		desc: "If this attack misses the target, the user takes half of the damage it would have dealt in recoil damage.",
		shortDesc: "User takes half damage it would have dealt if miss.",
		pp: 25,
		onMoveFail: function(target, source, move) {
			var damage = this.getDamage(source, target, move, true);
			this.damage(clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
		}
	},
	lastresort: {
		inherit: true,
		basePower: 130
	},
	magmastorm: {
		inherit: true,
		accuracy: 70
	},
	petaldance: {
		inherit: true,
		basePower: 90,
		pp: 20
	},
	poisongas: {
		inherit: true,
		accuracy: 55
	},
	protect: {
		inherit: true,
		//desc: "",
		priority: 3
	},
	rockblast: {
		inherit: true,
		accuracy: 80
	},
	sandtomb: {
		inherit: true,
		accuracy: 70,
		basePower: 15
	},
	scaryface: {
		inherit: true,
		accuracy: 90
	},
	tackle: {
		inherit: true,
		accuracy: 95,
		basePower: 35
	},
	tailglow: {
		inherit: true,
		desc: "Raises the user's Special Attack by 2 stages.",
		shortDesc: "Boosts the user's Sp. Atk by 2.",
		boosts: {
			spa: 2
		}
	},
	thrash: {
		inherit: true,
		basePower: 90,
		pp: 20
	},
	toxic: {
		inherit: true,
		accuracy: 85
	},
	uproar: {
		inherit: true,
		basePower: 50
	},
	whirlpool: {
		inherit: true,
		accuracy: 70,
		basePower: 15
	},
	wish: {
		inherit: true,
		//desc: "",
		shortDesc: "Next turn, heals 50% of the recipient's max HP.",
		sideCondition: 'Wish',
		effect: {
			duration: 2,
			onResidualOrder: 2,
			onEnd: function(side) {
				var target = side.active[this.effectData.sourcePosition];
				if (!target.fainted) {
					var source = this.effectData.source;
					var damage = this.heal(target.maxhp/2, target, target);
					if (damage) this.add('-heal', target, target.hpChange(damage), '[from] move: Wish', '[wisher] '+source.name);
				}
			}
		}
	},
	wrap: {
		inherit: true,
		accuracy: 85
	},
	magikarpsrevenge: null
};
<commit_msg>Stopgap implementation of Explosion/Selfdestruct todo: do it properly later<commit_after>function clampIntRange(num, min, max) {
	num = Math.floor(num);
	if (num < min) num = min;
	if (typeof max !== 'undefined' && num > max) num = max;
	return num;
}
exports.BattleMovedex = {
	beatup: {
		inherit: true,
		basePower: 10,
		basePowerCallback: undefined,
		desc: "Does one hit for the user and each other unfainted non-egg active and non-active Pokemon on the user's side without a status problem."
	},
	bind: {
		inherit: true,
		accuracy: 75
	},
	bonerush: {
		inherit: true,
		accuracy: 80
	},
	bulletseed: {
		inherit: true,
		basePower: 10
	},
	clamp: {
		inherit: true,
		accuracy: 75,
		pp: 10
	},
	cottonspore: {
		inherit: true,
		accuracy: 85
	},
	covet: {
		inherit: true,
		basePower: 40
	},
	crabhammer: {
		inherit: true,
		accuracy: 85
	},
	detect: {
		inherit: true,
		//desc: "",
		priority: 3
	},
	disable: {
		inherit: true,
		accuracy: 80
	},
	doomdesire: {
		inherit: true,
		accuracy: 85,
		basePower: 120
	},
	drainpunch: {
		inherit: true,
		basePower: 60,
		pp: 5
	},
	explosion: {
		inherit: true,
		basePower: 500
	},
	extremespeed: {
		inherit: true,
		shortDesc: "Usually goes first.",
		priority: 1
	},
	fakeout: {
		inherit: true,
		shortDesc: "Usually hits first; first turn out only; target flinch.",
		priority: 1
	},
	feint: {
		inherit: true,
		basePower: 50
	},
	firespin: {
		inherit: true,
		accuracy: 70,
		basePower: 15
	},
	furycutter: {
		inherit: true,
		basePower: 10
	},
	futuresight: {
		inherit: true,
		accuracy: 90,
		basePower: 80,
		pp: 15
	},
	gigadrain: {
		inherit: true,
		basePower: 60
	},
	glare: {
		inherit: true,
		accuracy: 75
	},
	growth: {
		inherit: true,
		desc: "Raises the user's Special Attack by 1 stage.",
		shortDesc: "Boosts the user's Sp. Atk by 1.",
		onModifyMove: undefined,
		boosts: {
			spa: 1
		}
	},
	hijumpkick: {
		inherit: true,
		basePower: 100,
		desc: "If this attack misses the target, the user takes half of the damage it would have dealt in recoil damage.",
		shortDesc: "User takes half damage it would have dealt if miss.",
		pp: 20,
		onMoveFail: function(target, source, move) {
			var damage = this.getDamage(source, target, move, true);
			this.damage(clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
		}
	},
	iciclespear: {
		inherit: true,
		basePower: 10
	},
	jumpkick: {
		inherit: true,
		basePower: 85,
		desc: "If this attack misses the target, the user takes half of the damage it would have dealt in recoil damage.",
		shortDesc: "User takes half damage it would have dealt if miss.",
		pp: 25,
		onMoveFail: function(target, source, move) {
			var damage = this.getDamage(source, target, move, true);
			this.damage(clampIntRange(damage/2, 1, Math.floor(target.maxhp/2)), source);
		}
	},
	lastresort: {
		inherit: true,
		basePower: 130
	},
	magmastorm: {
		inherit: true,
		accuracy: 70
	},
	petaldance: {
		inherit: true,
		basePower: 90,
		pp: 20
	},
	poisongas: {
		inherit: true,
		accuracy: 55
	},
	protect: {
		inherit: true,
		//desc: "",
		priority: 3
	},
	rockblast: {
		inherit: true,
		accuracy: 80
	},
	sandtomb: {
		inherit: true,
		accuracy: 70,
		basePower: 15
	},
	scaryface: {
		inherit: true,
		accuracy: 90
	},
	selfdestruct: {
		inherit: true,
		basePower: 400
	},
	tackle: {
		inherit: true,
		accuracy: 95,
		basePower: 35
	},
	tailglow: {
		inherit: true,
		desc: "Raises the user's Special Attack by 2 stages.",
		shortDesc: "Boosts the user's Sp. Atk by 2.",
		boosts: {
			spa: 2
		}
	},
	thrash: {
		inherit: true,
		basePower: 90,
		pp: 20
	},
	toxic: {
		inherit: true,
		accuracy: 85
	},
	uproar: {
		inherit: true,
		basePower: 50
	},
	whirlpool: {
		inherit: true,
		accuracy: 70,
		basePower: 15
	},
	wish: {
		inherit: true,
		//desc: "",
		shortDesc: "Next turn, heals 50% of the recipient's max HP.",
		sideCondition: 'Wish',
		effect: {
			duration: 2,
			onResidualOrder: 2,
			onEnd: function(side) {
				var target = side.active[this.effectData.sourcePosition];
				if (!target.fainted) {
					var source = this.effectData.source;
					var damage = this.heal(target.maxhp/2, target, target);
					if (damage) this.add('-heal', target, target.hpChange(damage), '[from] move: Wish', '[wisher] '+source.name);
				}
			}
		}
	},
	wrap: {
		inherit: true,
		accuracy: 85
	},
	magikarpsrevenge: null
};
<|endoftext|>


<commit_before>import { LightningElement, api, track, wire } from 'lwc';
import { fireEvent } from 'c/pubsubNoPageRef';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

import { getNestedProperty } from 'c/utilCommon';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getRecord} from 'lightning/uiRecordApi';

import RECURRING_DONATION_INFO from '@salesforce/schema/npe03__Recurring_Donation__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import CONTACT_OBJECT from '@salesforce/schema/Contact';

import FIELD_NAME from '@salesforce/schema/npe03__Recurring_Donation__c.Name';
import FIELD_ACCOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Organization__c';
import FIELD_CONTACT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Contact__c';
import FIELD_DATE_ESTABLISHED from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Date_Established__c';
import FIELD_STATUS from '@salesforce/schema/npe03__Recurring_Donation__c.Status__c';
import FIELD_RECURRING_TYPE from '@salesforce/schema/npe03__Recurring_Donation__c.RecurringType__c';
import FIELD_INSTALLMENT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installments__c';
import FIELD_AMOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Amount__c';
import FIELD_PAYMENT_METHOD from '@salesforce/schema/npe03__Recurring_Donation__c.PaymentMethod__c';
import FIELD_INSTALLMENT_PERIOD from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installment_Period__c';
import FIELD_INSTALLMENT_FREQUENCY from '@salesforce/schema/npe03__Recurring_Donation__c.InstallmentFrequency__c';
import FIELD_DAY_OF_MONTH from '@salesforce/schema/npe03__Recurring_Donation__c.Day_of_Month__c';
import FIELD_START_DATE from '@salesforce/schema/npe03__Recurring_Donation__c.StartDate__c';
import FIELD_CAMPAIGN from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Recurring_Donation_Campaign__c';

import cancelButtonLabel from '@salesforce/label/c.stgBtnCancel';
import saveButtonLabel from '@salesforce/label/c.stgBtnSave';
import unknownErrorLabel from '@salesforce/label/c.commonUnknownError';
import newHeaderLabel from '@salesforce/label/c.RD2_EntryFormHeader';
import editHeaderLabel from '@salesforce/label/c.commonEdit';
import currencyFieldLabel from '@salesforce/label/c.lblCurrency';
import donationSectionHeader from '@salesforce/label/c.RD2_EntryFormDonationSectionHeader';
import donorSectionHeader from '@salesforce/label/c.RD2_EntryFormDonorSectionHeader';
import otherSectionHeader from '@salesforce/label/c.RD2_EntryFormOtherSectionHeader';
import insertSuccessMessage from '@salesforce/label/c.RD2_EntryFormInsertSuccessMessage';
import updateSuccessMessage from '@salesforce/label/c.RD2_EntryFormUpdateSuccessMessage';

import getSetting from '@salesforce/apex/RD2_entryFormController.getSetting';

export default class rdEntryForm extends LightningElement {

    @api parentId;
    @api recordId;
    listenerEvent = 'rdEntryFormEvent';

    customLabels = Object.freeze({
        cancelButtonLabel,
        saveButtonLabel,
        donationSectionHeader,
        donorSectionHeader,
        otherSectionHeader
    });

    @track fields = {};
    @track record;
    recurringDonationInfo;
    fieldInfos;

    @track header = newHeaderLabel;

    @track isAutoNamingEnabled;
    @track isMultiCurrencyEnabled;

    @track contactId;
    @track accountId;

    @track isLoading = true;
    @track isRecordReady = false;
    isSettingReady = false;

    @track hasError = false;
    @track errorMessage = {};

    /*******************************************************************************
    * @description Dynamic render edit form CSS to show/hide the edit form
    */
    get cssEditForm() {
        return (!this.isLoading && this.isSettingReady && this.isRecordReady)
            ? ''
            : 'slds-hide';
    }

    /*******************************************************************************
    * @description Get Recurring Donation SObject API name
    */
    get recurringDonationName() {
        return getNestedProperty(RECURRING_DONATION_INFO, 'objectApiName');
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation Object info
    */
    @wire(getObjectInfo, {objectApiName: '$recurringDonationName' })
    wiredRDObjectInfo(response) {
        if (response.data) {
            this.recurringDonationInfo = response.data;
            this.buildDisplayedFields(this.recurringDonationInfo.fields);
            this.fieldInfos = this.buildFieldDescribesForWiredMethod(
                this.recurringDonationInfo.fields,
                this.recurringDonationInfo.apiName);

            if (this.recordId == null) {
                this.isRecordReady = true;
            }
        }

        if (response.error) {
            this.isRecordReady = true;
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Method converts field describe info into objects that the
    * getRecord method can accept into its 'fields' parameter.
    */
    buildFieldDescribesForWiredMethod(fields, objectApiName) {
        return Object.keys(fields).map((fieldApiName) => {
            return {
                fieldApiName: fieldApiName,
                objectApiName: objectApiName
            }
        });
    }

    /*******************************************************************************
    * @description Contrcut any needed field info from the Sobject Info
    */
    buildDisplayedFields(fieldInfos) {
        this.fields.name = this.extractFieldInfo(fieldInfos[FIELD_NAME.fieldApiName]);
        this.fields.account = this.extractFieldInfo(fieldInfos[FIELD_ACCOUNT.fieldApiName]);
        this.fields.contact = this.extractFieldInfo(fieldInfos[FIELD_CONTACT.fieldApiName]);
        this.fields.recurringType = this.extractFieldInfo(fieldInfos[FIELD_RECURRING_TYPE.fieldApiName]);
        this.fields.dateEstablished = this.extractFieldInfo(fieldInfos[FIELD_DATE_ESTABLISHED.fieldApiName]);
        this.fields.status = this.extractFieldInfo(fieldInfos[FIELD_STATUS.fieldApiName]);
        this.fields.amount = this.extractFieldInfo(fieldInfos[FIELD_AMOUNT.fieldApiName]);
        this.fields.paymentMethod = this.extractFieldInfo(fieldInfos[FIELD_PAYMENT_METHOD.fieldApiName]);
        this.fields.period = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_PERIOD.fieldApiName]);
        this.fields.installmentFrequency = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_FREQUENCY.fieldApiName]);
        this.fields.dayOfMonth = this.extractFieldInfo(fieldInfos[FIELD_DAY_OF_MONTH.fieldApiName]);
        this.fields.startDate = this.extractFieldInfo(fieldInfos[FIELD_START_DATE.fieldApiName]);
        this.fields.campaign = this.extractFieldInfo(fieldInfos[FIELD_CAMPAIGN.fieldApiName]);
        this.fields.currency = {label: currencyFieldLabel, apiName: 'CurrencyIsoCode'};
        this.fields.installment = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT.fieldApiName]);
    }

    /*******************************************************************************
    * @description Method converts field describe info into a object that is easily accessiable from the front end
    */
    extractFieldInfo(field) {
        return {
            apiName : field.apiName,
            label : field.label,
            inlineHelpText : field.inlineHelpText,
            dataType : field.dataType
        };
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation record value
    */
    @wire(getRecord, { recordId: '$recordId', fields: '$fieldInfos' })
    wiredRecurringDonationRecord(response) {
        if (response.data) {
            this.record = response.data;
            this.modidifyEditHeader();
            this.isRecordReady = true;
        }

        if (response.error) {
            this.isRecordReady = true;
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Modify edit modal header
    */
    modidifyEditHeader() {
        this.header = editHeaderLabel + ' ' + this.record.fields.Name.value;
    }

    /*******************************************************************************
    * @description Get org setting on init of the component
    */
    connectedCallback() {
        getSetting({parentId: this.parentId})
        .then(response => {
            this.isAutoNamingEnabled = response.isAutoNamingEnabled;
            this.isMultiCurrencyEnabled = response.isMultiCurrencyEnabled;
            this.handleParentIdType(response.parentSObjectType);
            this.isSettingReady = true;
            this.isLoading = false;
        })
        .catch((error) => {
            this.isSettingReady = true;
            this.handleError(error);
        });
    }

    /*******************************************************************************
    * @description Determine the parentId Sobject Type
    */
    handleParentIdType(parentSObjecType) {
        if (parentSObjecType == null) {
            return;
        }

        if (parentSObjecType === ACCOUNT_OBJECT.objectApiName) {
            this.accountId = this.parentId;
        } else if (parentSObjecType === CONTACT_OBJECT.objectApiName) {
            this.contactId = this.parentId;
        }
    }

    /*******************************************************************************
    * @description Override the standard submit. Add any fields before the submittion
    */
    handleSubmit(event){
        this.isLoading = true;
        this.template.querySelector("[data-id='submitButton']").disabled = true;

        event.preventDefault();
        const fields = event.detail.fields;
        this.template.querySelector('lightning-record-edit-form').submit(fields);
    }

    /*******************************************************************************
    * @description Handle all types of server error
    *   error.body is the error from apex calls
    *   error.body.output.errors is for AuraHandledException messages
    *   error.body.message errors is the error from wired service
    *   error.detail.output.errors is the error from record-edit-forms
    */
    handleError(error) {
        this.hasError = true;
        this.errorMessage.header = unknownErrorLabel;
        let message = unknownErrorLabel;

        if (typeof error === 'string' || error instanceof String) {
            message = error;

        } else if (error.message) {
            message = error.message;

        } else if ((error.body && error.body.output)) {
            if (Array.isArray(error.body) &&
                !error.body.output.errors) {
                message = error.body.map(e => e.message).join(', ');

            } else if (typeof error.body.message === 'string' &&
                !error.body.output.errors) {
                message = error.body.message;

            } else if (error.body.output &&
                Array.isArray(error.body.output.errors)) {
                message = error.body.output.errors.map(e => e.message).join(', ');

            }

        } else if (error.detail && error.detail.output && Array.isArray(error.detail.output.errors)) {
            this.errorMessage.header = error.detail.message;
            message = error.detail.output.errors.map(e => e.message).join(', ');

        } else if (error.body && error.body.message) {
            message = error.body.message;
        }

        this.errorMessage.detail = message;
        this.isLoading = false;
        this.template.querySelector("[data-id='submitButton']").disabled = false;

        this.template.querySelector(".slds-modal__header").scrollIntoView();

    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the cancel action
    */
    handleCancel() {
        fireEvent(this.pageRef, this.listenerEvent, { action: 'cancel', recordId : this.recordId });
    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the success action
    */
    handleSuccess(event) {
        this.showToast(event.detail.fields.Name.value);
        fireEvent(this.pageRef, this.listenerEvent, { action: 'success', recordId: event.detail.id});
    }

    /*******************************************************************************
    * @description Fires a toast event to display success message
    */
    showToast(recordName) {
        let succeedMessage = (this.recordId)
            ? updateSuccessMessage.replace("{0}", recordName)
            : insertSuccessMessage.replace("{0}", recordName);

        const event = new ShowToastEvent({
            title: succeedMessage,
            variant: 'success',
        });
        this.dispatchEvent(event);
    }
}<commit_msg>remove space<commit_after>import { LightningElement, api, track, wire } from 'lwc';
import { fireEvent } from 'c/pubsubNoPageRef';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

import { getNestedProperty } from 'c/utilCommon';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getRecord} from 'lightning/uiRecordApi';

import RECURRING_DONATION_INFO from '@salesforce/schema/npe03__Recurring_Donation__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import CONTACT_OBJECT from '@salesforce/schema/Contact';

import FIELD_NAME from '@salesforce/schema/npe03__Recurring_Donation__c.Name';
import FIELD_ACCOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Organization__c';
import FIELD_CONTACT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Contact__c';
import FIELD_DATE_ESTABLISHED from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Date_Established__c';
import FIELD_STATUS from '@salesforce/schema/npe03__Recurring_Donation__c.Status__c';
import FIELD_RECURRING_TYPE from '@salesforce/schema/npe03__Recurring_Donation__c.RecurringType__c';
import FIELD_INSTALLMENT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installments__c';
import FIELD_AMOUNT from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Amount__c';
import FIELD_PAYMENT_METHOD from '@salesforce/schema/npe03__Recurring_Donation__c.PaymentMethod__c';
import FIELD_INSTALLMENT_PERIOD from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Installment_Period__c';
import FIELD_INSTALLMENT_FREQUENCY from '@salesforce/schema/npe03__Recurring_Donation__c.InstallmentFrequency__c';
import FIELD_DAY_OF_MONTH from '@salesforce/schema/npe03__Recurring_Donation__c.Day_of_Month__c';
import FIELD_START_DATE from '@salesforce/schema/npe03__Recurring_Donation__c.StartDate__c';
import FIELD_CAMPAIGN from '@salesforce/schema/npe03__Recurring_Donation__c.npe03__Recurring_Donation_Campaign__c';

import cancelButtonLabel from '@salesforce/label/c.stgBtnCancel';
import saveButtonLabel from '@salesforce/label/c.stgBtnSave';
import unknownErrorLabel from '@salesforce/label/c.commonUnknownError';
import newHeaderLabel from '@salesforce/label/c.RD2_EntryFormHeader';
import editHeaderLabel from '@salesforce/label/c.commonEdit';
import currencyFieldLabel from '@salesforce/label/c.lblCurrency';
import donationSectionHeader from '@salesforce/label/c.RD2_EntryFormDonationSectionHeader';
import donorSectionHeader from '@salesforce/label/c.RD2_EntryFormDonorSectionHeader';
import otherSectionHeader from '@salesforce/label/c.RD2_EntryFormOtherSectionHeader';
import insertSuccessMessage from '@salesforce/label/c.RD2_EntryFormInsertSuccessMessage';
import updateSuccessMessage from '@salesforce/label/c.RD2_EntryFormUpdateSuccessMessage';

import getSetting from '@salesforce/apex/RD2_entryFormController.getSetting';

export default class rdEntryForm extends LightningElement {

    @api parentId;
    @api recordId;
    listenerEvent = 'rdEntryFormEvent';

    customLabels = Object.freeze({
        cancelButtonLabel,
        saveButtonLabel,
        donationSectionHeader,
        donorSectionHeader,
        otherSectionHeader
    });

    @track fields = {};
    @track record;
    recurringDonationInfo;
    fieldInfos;

    @track header = newHeaderLabel;

    @track isAutoNamingEnabled;
    @track isMultiCurrencyEnabled;

    @track contactId;
    @track accountId;

    @track isLoading = true;
    @track isRecordReady = false;
    isSettingReady = false;

    @track hasError = false;
    @track errorMessage = {};

    /*******************************************************************************
    * @description Dynamic render edit form CSS to show/hide the edit form
    */
    get cssEditForm() {
        return (!this.isLoading && this.isSettingReady && this.isRecordReady)
            ? ''
            : 'slds-hide';
    }

    /*******************************************************************************
    * @description Get Recurring Donation SObject API name
    */
    get recurringDonationName() {
        return getNestedProperty(RECURRING_DONATION_INFO, 'objectApiName');
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation Object info
    */
    @wire(getObjectInfo, {objectApiName: '$recurringDonationName' })
    wiredRDObjectInfo(response) {
        if (response.data) {
            this.recurringDonationInfo = response.data;
            this.buildDisplayedFields(this.recurringDonationInfo.fields);
            this.fieldInfos = this.buildFieldDescribesForWiredMethod(
                this.recurringDonationInfo.fields,
                this.recurringDonationInfo.apiName);

            if (this.recordId == null) {
                this.isRecordReady = true;
            }
        }

        if (response.error) {
            this.isRecordReady = true;
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Method converts field describe info into objects that the
    * getRecord method can accept into its 'fields' parameter.
    */
    buildFieldDescribesForWiredMethod(fields, objectApiName) {
        return Object.keys(fields).map((fieldApiName) => {
            return {
                fieldApiName: fieldApiName,
                objectApiName: objectApiName
            }
        });
    }

    /*******************************************************************************
    * @description Contrcut any needed field info from the Sobject Info
    */
    buildDisplayedFields(fieldInfos) {
        this.fields.name = this.extractFieldInfo(fieldInfos[FIELD_NAME.fieldApiName]);
        this.fields.account = this.extractFieldInfo(fieldInfos[FIELD_ACCOUNT.fieldApiName]);
        this.fields.contact = this.extractFieldInfo(fieldInfos[FIELD_CONTACT.fieldApiName]);
        this.fields.recurringType = this.extractFieldInfo(fieldInfos[FIELD_RECURRING_TYPE.fieldApiName]);
        this.fields.dateEstablished = this.extractFieldInfo(fieldInfos[FIELD_DATE_ESTABLISHED.fieldApiName]);
        this.fields.status = this.extractFieldInfo(fieldInfos[FIELD_STATUS.fieldApiName]);
        this.fields.amount = this.extractFieldInfo(fieldInfos[FIELD_AMOUNT.fieldApiName]);
        this.fields.paymentMethod = this.extractFieldInfo(fieldInfos[FIELD_PAYMENT_METHOD.fieldApiName]);
        this.fields.period = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_PERIOD.fieldApiName]);
        this.fields.installmentFrequency = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT_FREQUENCY.fieldApiName]);
        this.fields.dayOfMonth = this.extractFieldInfo(fieldInfos[FIELD_DAY_OF_MONTH.fieldApiName]);
        this.fields.startDate = this.extractFieldInfo(fieldInfos[FIELD_START_DATE.fieldApiName]);
        this.fields.campaign = this.extractFieldInfo(fieldInfos[FIELD_CAMPAIGN.fieldApiName]);
        this.fields.currency = {label: currencyFieldLabel, apiName: 'CurrencyIsoCode'};
        this.fields.installment = this.extractFieldInfo(fieldInfos[FIELD_INSTALLMENT.fieldApiName]);
    }

    /*******************************************************************************
    * @description Method converts field describe info into a object that is easily accessiable from the front end
    */
    extractFieldInfo(field) {
        return {
            apiName : field.apiName,
            label : field.label,
            inlineHelpText : field.inlineHelpText,
            dataType : field.dataType
        };
    }

    /*******************************************************************************
    * @description Retrieve Recurring Donation record value
    */
    @wire(getRecord, { recordId: '$recordId', fields: '$fieldInfos' })
    wiredRecurringDonationRecord(response) {
        if (response.data) {
            this.record = response.data;
            this.modidifyEditHeader();
            this.isRecordReady = true;
        }

        if (response.error) {
            this.isRecordReady = true;
            handleError(response.error);
        }
    }

    /*******************************************************************************
    * @description Modify edit modal header
    */
    modidifyEditHeader() {
        this.header = editHeaderLabel + ' ' + this.record.fields.Name.value;
    }

    /*******************************************************************************
    * @description Get org setting on init of the component
    */
    connectedCallback() {
        getSetting({parentId: this.parentId})
        .then(response => {
            this.isAutoNamingEnabled = response.isAutoNamingEnabled;
            this.isMultiCurrencyEnabled = response.isMultiCurrencyEnabled;
            this.handleParentIdType(response.parentSObjectType);
            this.isSettingReady = true;
            this.isLoading = false;
        })
        .catch((error) => {
            this.isSettingReady = true;
            this.handleError(error);
        });
    }

    /*******************************************************************************
    * @description Determine the parentId Sobject Type
    */
    handleParentIdType(parentSObjecType) {
        if (parentSObjecType == null) {
            return;
        }

        if (parentSObjecType === ACCOUNT_OBJECT.objectApiName) {
            this.accountId = this.parentId;
        } else if (parentSObjecType === CONTACT_OBJECT.objectApiName) {
            this.contactId = this.parentId;
        }
    }

    /*******************************************************************************
    * @description Override the standard submit. Add any fields before the submittion
    */
    handleSubmit(event){
        this.isLoading = true;
        this.template.querySelector("[data-id='submitButton']").disabled = true;

        event.preventDefault();
        const fields = event.detail.fields;
        this.template.querySelector('lightning-record-edit-form').submit(fields);
    }

    /*******************************************************************************
    * @description Handle all types of server error
    *   error.body is the error from apex calls
    *   error.body.output.errors is for AuraHandledException messages
    *   error.body.message errors is the error from wired service
    *   error.detail.output.errors is the error from record-edit-forms
    */
    handleError(error) {
        this.hasError = true;
        this.errorMessage.header = unknownErrorLabel;
        let message = unknownErrorLabel;

        if (typeof error === 'string' || error instanceof String) {
            message = error;

        } else if (error.message) {
            message = error.message;

        } else if ((error.body && error.body.output)) {
            if (Array.isArray(error.body) &&
                !error.body.output.errors) {
                message = error.body.map(e => e.message).join(', ');

            } else if (typeof error.body.message === 'string' &&
                !error.body.output.errors) {
                message = error.body.message;

            } else if (error.body.output &&
                Array.isArray(error.body.output.errors)) {
                message = error.body.output.errors.map(e => e.message).join(', ');

            }

        } else if (error.detail && error.detail.output && Array.isArray(error.detail.output.errors)) {
            this.errorMessage.header = error.detail.message;
            message = error.detail.output.errors.map(e => e.message).join(', ');

        } else if (error.body && error.body.message) {
            message = error.body.message;
        }

        this.errorMessage.detail = message;
        this.isLoading = false;

        this.template.querySelector("[data-id='submitButton']").disabled = false;

        this.template.querySelector(".slds-modal__header").scrollIntoView();
    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the cancel action
    */
    handleCancel() {
        fireEvent(this.pageRef, this.listenerEvent, { action: 'cancel', recordId : this.recordId });
    }

    /*******************************************************************************
    * @description Fires an event to utilDedicatedListener with the success action
    */
    handleSuccess(event) {
        this.showToast(event.detail.fields.Name.value);
        fireEvent(this.pageRef, this.listenerEvent, { action: 'success', recordId: event.detail.id});
    }

    /*******************************************************************************
    * @description Fires a toast event to display success message
    */
    showToast(recordName) {
        let succeedMessage = (this.recordId)
            ? updateSuccessMessage.replace("{0}", recordName)
            : insertSuccessMessage.replace("{0}", recordName);

        const event = new ShowToastEvent({
            title: succeedMessage,
            variant: 'success',
        });
        this.dispatchEvent(event);
    }
}<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import useQueries from 'history/lib/useQueries'
import {
  history as historyType,
  location as locationType
} from './PropTypes'

const warning = () => {}

const isBrowserEnvironment = typeof window === 'object'

const controlledLocationType = (props, propName, componentName) => {
  if (props[propName]) {
    const error = locationType(props, propName, componentName)

    if (error)
      return error

    if (typeof props.onChange !== 'function' && isBrowserEnvironment) {
      return new Error(
        'You provided a `location` prop to a <History> component without an `onChange` handler. ' +
        'This will make the back/forward buttons and the address bar unusable. If you intend to ' +
        'let the user navigate using the browser\'s built-in controls, use `defaultLocation` with ' +
        'a `history` prop. Otherwise, set `onChange`.'
      )
    }
  }
}

class History extends React.Component {
  static propTypes = {
    history: historyType,
    location: controlledLocationType,
    onChange: PropTypes.func,
    children: PropTypes.oneOfType([ PropTypes.node, PropTypes.func ]),
    render: PropTypes.func,
    component: PropTypes.func
  }

  static defaultProps = {
    history: useQueries(createBrowserHistory)()
  }

  static childContextTypes = {
    location: locationType
  }

  getChildContext() {
    const { location } = this.isControlled() ? this.props : this.state

    return {
      location
    }
  }

  state = {
    location: null
  }

  unlisten = null

  unlistenBefore = null

  // need to teardown and setup in cWRP too
  componentWillMount() {
    if (this.isControlled()) {
      this.listenBefore()
    } else {
      this.listen()
    }
  }

  componentWillReceiveProps(nextProps) {
    warning(
      nextProps.history === this.props.history,
      'Don’t change the history please. Thanks.'
    )

    if (nextProps.location && this.props.location == null) {
      this.switchToControlled()
    } else if (!nextProps.location && this.props.location) {
      this.switchToUncontrolled()
    }

    if (nextProps.location !== this.props.location) {
      this.transitioning = true

      const { location } = nextProps
      const { history } = this.props

      if (location.action === 'PUSH') {
        history.push(location)
      } else {
        history.replace(location)
      }
    }
  }

  isControlled() {
    return !!this.props.location
  }

  listen() {
    const { history } = this.props

    this.setState({
      location: history.getCurrentLocation()
    })

    this.unlisten = history.listen(location => {
      this.setState({ location })
    })
  }

  listenBefore() {
    const { history, onChange } = this.props

    this.unlistenBefore = history.listenBefore((location) => {
      if (!this.transitioning) {
        if (onChange)
          onChange(location)

        return false
      } else {
        this.transitioning = false
        return true
      }
    })
  }

  switchToControlled() {
    this.unlisten()
    this.unlisten = null
    this.listen()
  }

  switchToUncontrolled() {
    this.unlistenBefore()
    this.unlistenBefore = null
    this.listen()
  }

  render() {
    const { children } = this.props
    const { location } = this.isControlled() ? this.props : this.state

    return (
      typeof children === 'function' ? children({ location }) : children
    )
  }
}

export default History
<commit_msg>Use real warning instead of stub<commit_after>import warning from 'warning'
import React, { PropTypes } from 'react'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import useQueries from 'history/lib/useQueries'
import {
  history as historyType,
  location as locationType
} from './PropTypes'

const isBrowserEnvironment = typeof window === 'object'

const controlledLocationType = (props, propName, componentName) => {
  if (props[propName]) {
    const error = locationType(props, propName, componentName)

    if (error)
      return error

    if (typeof props.onChange !== 'function' && isBrowserEnvironment) {
      return new Error(
        'You provided a `location` prop to a <History> component without an `onChange` handler. ' +
        'This will make the back/forward buttons and the address bar unusable. If you intend to ' +
        'let the user navigate using the browser\'s built-in controls, use `defaultLocation` with ' +
        'a `history` prop. Otherwise, set `onChange`.'
      )
    }
  }
}

class History extends React.Component {
  static propTypes = {
    history: historyType,
    location: controlledLocationType,
    onChange: PropTypes.func,
    children: PropTypes.oneOfType([ PropTypes.node, PropTypes.func ]),
    render: PropTypes.func,
    component: PropTypes.func
  }

  static defaultProps = {
    history: useQueries(createBrowserHistory)()
  }

  static childContextTypes = {
    location: locationType
  }

  getChildContext() {
    const { location } = this.isControlled() ? this.props : this.state

    return {
      location
    }
  }

  state = {
    location: null
  }

  unlisten = null

  unlistenBefore = null

  // need to teardown and setup in cWRP too
  componentWillMount() {
    if (this.isControlled()) {
      this.listenBefore()
    } else {
      this.listen()
    }
  }

  componentWillReceiveProps(nextProps) {
    warning(
      nextProps.history === this.props.history,
      'Don’t change the history please. Thanks.'
    )

    if (nextProps.location && this.props.location == null) {
      this.switchToControlled()
    } else if (!nextProps.location && this.props.location) {
      this.switchToUncontrolled()
    }

    if (nextProps.location !== this.props.location) {
      this.transitioning = true

      const { location } = nextProps
      const { history } = this.props

      if (location.action === 'PUSH') {
        history.push(location)
      } else {
        history.replace(location)
      }
    }
  }

  isControlled() {
    return !!this.props.location
  }

  listen() {
    const { history } = this.props

    this.setState({
      location: history.getCurrentLocation()
    })

    this.unlisten = history.listen(location => {
      this.setState({ location })
    })
  }

  listenBefore() {
    const { history, onChange } = this.props

    this.unlistenBefore = history.listenBefore((location) => {
      if (!this.transitioning) {
        if (onChange)
          onChange(location)

        return false
      } else {
        this.transitioning = false
        return true
      }
    })
  }

  switchToControlled() {
    this.unlisten()
    this.unlisten = null
    this.listen()
  }

  switchToUncontrolled() {
    this.unlistenBefore()
    this.unlistenBefore = null
    this.listen()
  }

  render() {
    const { children } = this.props
    const { location } = this.isControlled() ? this.props : this.state

    return (
      typeof children === 'function' ? children({ location }) : children
    )
  }
}

export default History
<|endoftext|>


<commit_before>"use strict";

const attempt = require("./attempt.js").attempt;

const modFs = require("fs"),
      modPath = require("path"),
      modMime = require("./mime.js"),
      modThumbnail = attempt(function () { return require("./thumbnail.js"); });

const MIME_INFO = {
    "application/java-archive": { "icon": "package.png" },
    "application/pdf": { "icon": "pdf.png" },
    "application/vnd.oasis.opendocument.text": { "icon": "document.png" },
    "application/x-gzip": { "icon": "package.png" },
    "application/x-iso9660-image": { "icon": "optical.png" },
    "application/zip": { "icon": "package.png" },
    "audio/mp3": { "icon": "audio.png" },
    "image/gif": { "icon": "image.png", "viewer": "viewImage" },
    "image/jpeg": { "icon": "image.png", "viewer": "viewImage" },
    "image/png": { "icon": "image.png", "viewer": "viewImage" },
    "image/svg+xml": { "icon": "image.png", "viewer": "viewImage" },
    "text/html": { "icon": "html.png" },
    "text/plain": { "icon": "text.png" },
    "text/rtf": { "icon": "document.png" },
    "text/vcard": { "icon": "contacts.png", "viewer": "viewVCard" },
    "video/mp4": { "icon": "video.png" }
};

function getIcon(mimeType)
{
    var info = MIME_INFO[mimeType];
    if (info)
    {
        return "/::res/file-icons/" + info.icon;
    }
    else
    {
        return "/::res/file-icons/text.png"
    }
}

function prepareClipboard(home, callback)
{
    var path = modPath.join(home, ".clipboard");

    // create clipboard if missing
    modFs.stat(path, function (err, stats)
    {
        if (err)
        {
            modFs.mkdir(path, function (err)
            {
                callback();
            });
        }
        else
        {
            callback();
        }
    });
}

function readStats(path, callback)
{
    modFs.readdir(path, function (err, files)
    {
        if (err || files.length === 0)
        {
            callback([]);
            return;
        }

        var result = [];
        for (var i = 0; i < files.length; ++i)
        {
            var file = files[i];
            modFs.stat(modPath.join(path, file), function (file) { return function (err, stat)
            {
                result.push([file, stat]);
                if (result.length === files.length)
                {
                    result.sort(function (a, b)
                    {
                        if (! a[1] || ! b[1])
                        {
                            return 0;
                        }
                        else if (a[1].isDirectory() && ! b[1].isDirectory())
                        {
                            return -1;
                        }
                        else if (! a[1].isDirectory() && b[1].isDirectory())
                        {
                            return 1;
                        }
                        else
                        {
                            return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
                        }
                    });

                    callback(result);
                }
            }; } (file));
        }
    });
}

function makeInfo(file, stat)
{
    var info = (stat.size / (1024 * 1024)).toFixed(2) + " MB, " +
            stat.mtime.toDateString();
    return info;
}

function makeIcon(icon)
{
    return "";
}

function makeThumbnail(icon, path, file)
{
    var imageFile = modPath.join(path, file);

    return "";
}

function makeItem(path, file, stat, active)
{
    var out = "";

    var mimeType = modMime.mimeType(file);
    var mimeInfo = MIME_INFO[mimeType];
    var name = file;
    var icon = getIcon(mimeType);
    var href = "";
    var info = "";
    var ajaxMode = "";
    var action = "";

    var iconHtml = "";

    if (active && mimeInfo && mimeInfo.viewer)
    {
        action = "onclick='" + mimeInfo.viewer +
                "(\"" + encodeURIComponent(file) + "\");'";
        href="#";
    }
    else
    {
        href = active ? encodeURIComponent(file)
                      : "";
    }

    if (stat.isDirectory())
    {
        href = active ? modPath.join(file, "index.html")
                      : "#";
        icon = "/::res/file-icons/folder.png";
        iconHtml = makeIcon(icon);
        ajaxMode = "data-ajax='false'";
    }
    else if (mimeType.indexOf("image/") == 0)
    {
        href = "#";
        if (! modThumbnail || mimeType === "image/svg+xml")
        {
            iconHtml = makeIcon(icon);
        }
        else
        {
            iconHtml = makeThumbnail(icon, path, file);
        }

        info = makeInfo(file, stat);
        ajaxMode = "data-ajax='false'";
    }
    else
    {
        info = makeInfo(file, stat);
        ajaxMode = "data-ajax='false'";
        iconHtml = makeIcon(icon);
    }

    out += "";
    out += iconHtml;
    out += "
" + name + "
";
    out += "
" + info + "
";
    out += "";
    if (active)
    {
        out += "";
    }

    return out;
}

function makeFiles(path, stats, active)
{
    var out = "";
    out += "
";
    for (var i = 0; i < stats.length; ++i)
    {
        var file = stats[i][0];
        var stat = stats[i][1];

        if (! stat || file.indexOf(".") === 0)
        {
            continue;
        }

        out += "
";
        out += makeItem(path, file, stat, active);
        out += "
";
    }
    out += "
";

    return out;
}

function makeHtmlHead()
{
    var out = "" +
              "  <title></title>" +
              "  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'></meta>" +
              "  <meta name='viewport' content='width=device-width, initial-scale=1'></meta>" +
              "  <link rel='stylesheet' href='https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css'/>" +
              "  " +
              "  " +
              "  " +
              "  " +
              "  " +
              "";

    return out;
}

function makeBreadcrumbs(path)
{
    var pathParts = path.split("/");

    var out = "
" +
              "
/
";

    var breadcrumbPath = "";
    for (var i = 0; i < pathParts.length; ++i)
    {
        if (pathParts[i] === "")
        {
            continue;
        }

        breadcrumbPath += "/" + pathParts[i]
        out += "
" + pathParts[i] + "
";
    }

    out += "
";

    return out;
}

function makeMoreMenu()
{
    var out = "
" +
              "
" +
              "
Upload Files
" +
              "
New Directory
" +
              "

" +
              "
Paste
" +
              "
Cut
" +
              "
Copy
" +
              "
Delete
" +
              "

" +
              "
Select All
" +
              "
Unselect All
" +
              "

" +
              "
Show Clipboard
" +
              "
" +
              "
";
    return out;
}

function makeMessageDialog()
{
    var out = "
" +

              "

" +

              "
" +
              "

" +

              "    OK" +
              "
" +

              "
";
    return out;
}

function makeNewDirDialog()
{
    var out = "
" +

              "

New directory

" +

              "
" +
              "    <form>" +
              "      Name:" +
              "      <input type='text'>" +
              "    </form>" +

              "    Create" +
              "    Cancel" +
              "
" +

              "
";

    return out;
}

function makeMainPage(path, stats)
{
    var out = "
" +

              makeMoreMenu() +

              "
" +
              makeBreadcrumbs(path) +
              "
" +

              makeMessageDialog() +
              makeNewDirDialog() +

              "
" +
              "
" + path + "
" +
              (path !== "/" ? "    Up" : "") +
              "    More" +
              "
" +

              "
" +
              makeFiles(path, stats, true) +
              "
" +

              "
";

    return out;
}

function makeClipboardPage(clipboardStats)
{
    var out = "
" +

              "
" +
              "
Clipboard
" +
              "    Back" +
              "
" +

              "
" +
              makeFiles("", clipboardStats, false) +
              "
" +

              "
";

    return out;
}

function makeViewerPage()
{
    var out = "
" +

              "
" +
              "

" +
              "    Back" +
              "
" +

              "
" +
              "
" +

              "
";

    return out;
}

function makeHtml(path, stats, clipboardStats)
{
    var out = "<!DOCTYPE html>" +

              "" +
              makeHtmlHead() +
              "" +

              "<input id='upload' type='file' multiple style='display: none;'/>" +

              makeMainPage(path, stats) +
              makeViewerPage() +
              makeClipboardPage(clipboardStats) +

              "" +
              "";

    return out;
}

function makeIndex(href, home, callback)
{
    var path = decodeURIComponent(href);
    var fullPath = modPath.join(home, decodeURIComponent(href));

    console.debug("User Path: " + path + "\n" +
                  "Full path: " + fullPath);

    prepareClipboard(home, function ()
    {
        readStats(fullPath, function (stats)
        {
            readStats(modPath.join(home, ".clipboard"), function (clipboardStats)
            {
                var html = makeHtml(path, stats, clipboardStats);
                callback(true, html);
            });
        });
    });
}
exports.makeIndex = makeIndex;
<commit_msg>fixed browser URI encoding bug<commit_after>"use strict";

const attempt = require("./attempt.js").attempt;

const modFs = require("fs"),
      modPath = require("path"),
      modMime = require("./mime.js"),
      modThumbnail = attempt(function () { return require("./thumbnail.js"); });

const MIME_INFO = {
    "application/java-archive": { "icon": "package.png" },
    "application/pdf": { "icon": "pdf.png" },
    "application/vnd.oasis.opendocument.text": { "icon": "document.png" },
    "application/x-gzip": { "icon": "package.png" },
    "application/x-iso9660-image": { "icon": "optical.png" },
    "application/zip": { "icon": "package.png" },
    "audio/mp3": { "icon": "audio.png" },
    "image/gif": { "icon": "image.png", "viewer": "viewImage" },
    "image/jpeg": { "icon": "image.png", "viewer": "viewImage" },
    "image/png": { "icon": "image.png", "viewer": "viewImage" },
    "image/svg+xml": { "icon": "image.png", "viewer": "viewImage" },
    "text/html": { "icon": "html.png" },
    "text/plain": { "icon": "text.png" },
    "text/rtf": { "icon": "document.png" },
    "text/vcard": { "icon": "contacts.png", "viewer": "viewVCard" },
    "video/mp4": { "icon": "video.png" }
};

function getIcon(mimeType)
{
    var info = MIME_INFO[mimeType];
    if (info)
    {
        return "/::res/file-icons/" + info.icon;
    }
    else
    {
        return "/::res/file-icons/text.png"
    }
}

function prepareClipboard(home, callback)
{
    var path = modPath.join(home, ".clipboard");

    // create clipboard if missing
    modFs.stat(path, function (err, stats)
    {
        if (err)
        {
            modFs.mkdir(path, function (err)
            {
                callback();
            });
        }
        else
        {
            callback();
        }
    });
}

function readStats(path, callback)
{
    modFs.readdir(path, function (err, files)
    {
        if (err || files.length === 0)
        {
            callback([]);
            return;
        }

        var result = [];
        for (var i = 0; i < files.length; ++i)
        {
            var file = files[i];
            modFs.stat(modPath.join(path, file), function (file) { return function (err, stat)
            {
                result.push([file, stat]);
                if (result.length === files.length)
                {
                    result.sort(function (a, b)
                    {
                        if (! a[1] || ! b[1])
                        {
                            return 0;
                        }
                        else if (a[1].isDirectory() && ! b[1].isDirectory())
                        {
                            return -1;
                        }
                        else if (! a[1].isDirectory() && b[1].isDirectory())
                        {
                            return 1;
                        }
                        else
                        {
                            return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
                        }
                    });

                    callback(result);
                }
            }; } (file));
        }
    });
}

function makeInfo(file, stat)
{
    var info = (stat.size / (1024 * 1024)).toFixed(2) + " MB, " +
            stat.mtime.toDateString();
    return info;
}

function makeIcon(icon)
{
    return "";
}

function makeThumbnail(icon, path, file)
{
    var imageFile = modPath.join(path, file);

    return "";
}

function makeItem(path, file, stat, active)
{
    var out = "";

    var mimeType = modMime.mimeType(file);
    var mimeInfo = MIME_INFO[mimeType];
    var name = file;
    var icon = getIcon(mimeType);
    var href = "";
    var info = "";
    var ajaxMode = "";
    var action = "";

    var iconHtml = "";

    if (active && mimeInfo && mimeInfo.viewer)
    {
        action = "onclick='" + mimeInfo.viewer +
                "(\"" + encodeURI(file) + "\");'";
        href="#";
    }
    else
    {
        href = active ? encodeURI(file)
                      : "";
    }

    if (stat.isDirectory())
    {
        href = active ? modPath.join(file, "index.html")
                      : "#";
        icon = "/::res/file-icons/folder.png";
        iconHtml = makeIcon(icon);
        ajaxMode = "data-ajax='false'";
    }
    else if (mimeType.indexOf("image/") == 0)
    {
        href = "#";
        if (! modThumbnail || mimeType === "image/svg+xml")
        {
            iconHtml = makeIcon(icon);
        }
        else
        {
            iconHtml = makeThumbnail(icon, path, file);
        }

        info = makeInfo(file, stat);
        ajaxMode = "data-ajax='false'";
    }
    else
    {
        info = makeInfo(file, stat);
        ajaxMode = "data-ajax='false'";
        iconHtml = makeIcon(icon);
    }

    out += "";
    out += iconHtml;
    out += "
" + name + "
";
    out += "
" + info + "
";
    out += "";
    if (active)
    {
        out += "";
    }

    return out;
}

function makeFiles(path, stats, active)
{
    var out = "";
    out += "
";
    for (var i = 0; i < stats.length; ++i)
    {
        var file = stats[i][0];
        var stat = stats[i][1];

        if (! stat || file.indexOf(".") === 0)
        {
            continue;
        }

        out += "
";
        out += makeItem(path, file, stat, active);
        out += "
";
    }
    out += "
";

    return out;
}

function makeHtmlHead()
{
    var out = "" +
              "  <title></title>" +
              "  <meta http-equiv='Content-Type' content='text/html; charset=utf-8'></meta>" +
              "  <meta name='viewport' content='width=device-width, initial-scale=1'></meta>" +
              "  <link rel='stylesheet' href='https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css'/>" +
              "  " +
              "  " +
              "  " +
              "  " +
              "  " +
              "";

    return out;
}

function makeBreadcrumbs(path)
{
    var pathParts = path.split("/");

    var out = "
" +
              "
/
";

    var breadcrumbPath = "";
    for (var i = 0; i < pathParts.length; ++i)
    {
        if (pathParts[i] === "")
        {
            continue;
        }

        breadcrumbPath += "/" + pathParts[i]
        out += "
" + pathParts[i] + "
";
    }

    out += "
";

    return out;
}

function makeMoreMenu()
{
    var out = "
" +
              "
" +
              "
Upload Files
" +
              "
New Directory
" +
              "

" +
              "
Paste
" +
              "
Cut
" +
              "
Copy
" +
              "
Delete
" +
              "

" +
              "
Select All
" +
              "
Unselect All
" +
              "

" +
              "
Show Clipboard
" +
              "
" +
              "
";
    return out;
}

function makeMessageDialog()
{
    var out = "
" +

              "

" +

              "
" +
              "

" +

              "    OK" +
              "
" +

              "
";
    return out;
}

function makeNewDirDialog()
{
    var out = "
" +

              "

New directory

" +

              "
" +
              "    <form>" +
              "      Name:" +
              "      <input type='text'>" +
              "    </form>" +

              "    Create" +
              "    Cancel" +
              "
" +

              "
";

    return out;
}

function makeMainPage(path, stats)
{
    var out = "
" +

              makeMoreMenu() +

              "
" +
              makeBreadcrumbs(path) +
              "
" +

              makeMessageDialog() +
              makeNewDirDialog() +

              "
" +
              "
" + path + "
" +
              (path !== "/" ? "    Up" : "") +
              "    More" +
              "
" +

              "
" +
              makeFiles(path, stats, true) +
              "
" +

              "
";

    return out;
}

function makeClipboardPage(clipboardStats)
{
    var out = "
" +

              "
" +
              "
Clipboard
" +
              "    Back" +
              "
" +

              "
" +
              makeFiles("", clipboardStats, false) +
              "
" +

              "
";

    return out;
}

function makeViewerPage()
{
    var out = "
" +

              "
" +
              "

" +
              "    Back" +
              "
" +

              "
" +
              "
" +

              "
";

    return out;
}

function makeHtml(path, stats, clipboardStats)
{
    var out = "<!DOCTYPE html>" +

              "" +
              makeHtmlHead() +
              "" +

              "<input id='upload' type='file' multiple style='display: none;'/>" +

              makeMainPage(path, stats) +
              makeViewerPage() +
              makeClipboardPage(clipboardStats) +

              "" +
              "";

    return out;
}

function makeIndex(href, home, callback)
{
    var path = decodeURIComponent(href);
    var fullPath = modPath.join(home, decodeURIComponent(href));

    console.debug("User Path: " + path + "\n" +
                  "Full path: " + fullPath);

    prepareClipboard(home, function ()
    {
        readStats(fullPath, function (stats)
        {
            readStats(modPath.join(home, ".clipboard"), function (clipboardStats)
            {
                var html = makeHtml(path, stats, clipboardStats);
                callback(true, html);
            });
        });
    });
}
exports.makeIndex = makeIndex;
<|endoftext|>


<commit_before>(function() {
  "use strict";
  var isArray = Array.isArray;

  Ember.Object.reopen({
    onInit: function() {
      this.setDelegatedProperties();
    }.on('init'),

    onDelegatesChange: function() {
      this.removeOldDelegations();
      this.setDelegatedProperties();
    }.observes('delegations'),

    removeOldDelegations: function() {
      var oldProps = this.get('oldDelegatedProperties');
      if (!oldProps) return;

      var self = this;
      var removeProps = function(props) {
        var arr = props.properties.split(' ');

        arr.forEach(function(propertyName) {
          self.set(propertyName, undefined);
        });
      };

      if (oldProps) {
        if (isArray(oldProps)) {
          oldProps.forEach(removeProps);
        } else {
          removeProps(oldProps);
        }
      }

      this.set('oldDelegatedProperties', null);
    },

    setDelegatedProperties: function() {
      if (!this.isValidDelegation()) return;

      var delegations = this.get('delegations');
      var self = this;
      var setDelegate = function(delegate) {
        var properties = delegate.properties.split(' ');

        properties.forEach(function(property) {
          Ember.defineProperty(this, property, Ember.computed(function() {
            var target = this.get(delegate.to);
            return target && target.get(property);
          }).property(delegate.to + '.' + property));
        }, self);
      };

      if (delegations) {
        if (isArray(delegations)) {
          delegations.forEach(setDelegate);
        } else {
          setDelegate(delegations);
        }
      }

      this.set('oldDelegatedProperties', delegations);
    },

    isValidDelegation: function() {
      if (this && this.get('delegations')) {
        var delegations = this.get('delegations');

        if (isArray(delegations)) delegations = delegations.get('firstObject');
        return delegations.properties && delegations.to;
      }
    }
  });
})();<commit_msg>Improve validations<commit_after>(function() {
  "use strict";
  var isArray = Array.isArray;

  Ember.Object.reopen({
    onInit: function() {
      this.setDelegatedProperties();
    }.on('init'),

    onDelegatesChange: function() {
      this.removeOldDelegations();
      this.setDelegatedProperties();
    }.observes('delegations'),

    removeOldDelegations: function() {
      var oldProps = this.get('oldDelegatedProperties');
      if (!this.isValidDelegation(oldProps)) return;

      var self = this;
      var removeProps = function(props) {
        var arr = props.properties.split(' ');

        arr.forEach(function(propertyName) {
          self.set(propertyName, undefined);
        });
      };

      if (oldProps) {
        if (isArray(oldProps)) {
          oldProps.forEach(removeProps);
        } else {
          removeProps(oldProps);
        }
      }

      this.set('oldDelegatedProperties', null);
    },

    setDelegatedProperties: function() {
      var delegations = this.get('delegations');
      if (!this.isValidDelegation(delegations)) return;

      var self = this;
      var setDelegate = function(delegate) {
        var properties = delegate.properties.split(' ');

        properties.forEach(function(property) {
          Ember.defineProperty(this, property, Ember.computed(function() {
            var target = this.get(delegate.to);
            return target && target.get(property);
          }).property(delegate.to + '.' + property));
        }, self);
      };

      if (delegations) {
        if (isArray(delegations)) {
          delegations.forEach(setDelegate);
        } else {
          setDelegate(delegations);
        }
      }

      this.set('oldDelegatedProperties', delegations);
    },

    isValidDelegation: function(delegations) {
      if (this && delegations) {
        if (isArray(delegations)) delegations = delegations.get('firstObject');
        return delegations.properties && delegations.to;
      }
    }
  });
})();<|endoftext|>