entities listlengths 1 8.61k | max_stars_repo_path stringlengths 7 172 | max_stars_repo_name stringlengths 5 89 | max_stars_count int64 0 82k | content stringlengths 14 1.05M | id stringlengths 2 6 | new_content stringlengths 15 1.05M | modified bool 1 class | references stringlengths 29 1.05M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n\nroot = exports ? ",
"end": 36,
"score": 0.999884307384491,
"start": 18,
"tag": "NAME",
"value": "Christopher Joakim"
},
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.co... | m26-js/src/m26_run_walk_calculator.coffee | cjoakim/oss | 0 | # Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>
root = exports ? this
class RunWalkCalculator
# these are "class methods", not "instance methods".
@calculate: (run_hhmmss, run_ppm, walk_hhmmss, walk_ppm, miles) ->
result = {}
if run_hhmmss and run_ppm and walk_hhmmss and walk_ppm
run_duration_elapsed_time = new ElapsedTime(run_hhmmss)
run_ppm_elapsed_time = new ElapsedTime(run_ppm)
walk_duration_elapsed_time = new ElapsedTime(walk_hhmmss)
walk_ppm_elapsed_time = new ElapsedTime(walk_ppm)
distance = new Distance(miles)
mile = new Distance(1.0)
total_secs = run_duration_elapsed_time.seconds() + walk_duration_elapsed_time.seconds()
run_pct = run_duration_elapsed_time.seconds() / total_secs
walk_pct = 1.0 - run_pct
run_secs = run_pct * run_ppm_elapsed_time.seconds()
walk_secs = walk_pct * walk_ppm_elapsed_time.seconds()
avg_secs = run_secs + walk_secs
avg_time = new ElapsedTime(avg_secs)
avg_speed = new Speed(mile, avg_time)
mph = avg_speed.mph()
proj_time = avg_speed.projected_time(distance)
result.avg_mph = avg_speed.mph()
result.avg_ppm = avg_speed.pace_per_mile()
result.proj_time = avg_speed.projected_time(distance)
result.proj_miles = distance.as_miles()
result
root.RunWalkCalculator = RunWalkCalculator
| 133713 | # Copyright 2015, <NAME> <<EMAIL>>
root = exports ? this
class RunWalkCalculator
# these are "class methods", not "instance methods".
@calculate: (run_hhmmss, run_ppm, walk_hhmmss, walk_ppm, miles) ->
result = {}
if run_hhmmss and run_ppm and walk_hhmmss and walk_ppm
run_duration_elapsed_time = new ElapsedTime(run_hhmmss)
run_ppm_elapsed_time = new ElapsedTime(run_ppm)
walk_duration_elapsed_time = new ElapsedTime(walk_hhmmss)
walk_ppm_elapsed_time = new ElapsedTime(walk_ppm)
distance = new Distance(miles)
mile = new Distance(1.0)
total_secs = run_duration_elapsed_time.seconds() + walk_duration_elapsed_time.seconds()
run_pct = run_duration_elapsed_time.seconds() / total_secs
walk_pct = 1.0 - run_pct
run_secs = run_pct * run_ppm_elapsed_time.seconds()
walk_secs = walk_pct * walk_ppm_elapsed_time.seconds()
avg_secs = run_secs + walk_secs
avg_time = new ElapsedTime(avg_secs)
avg_speed = new Speed(mile, avg_time)
mph = avg_speed.mph()
proj_time = avg_speed.projected_time(distance)
result.avg_mph = avg_speed.mph()
result.avg_ppm = avg_speed.pace_per_mile()
result.proj_time = avg_speed.projected_time(distance)
result.proj_miles = distance.as_miles()
result
root.RunWalkCalculator = RunWalkCalculator
| true | # Copyright 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
root = exports ? this
class RunWalkCalculator
# these are "class methods", not "instance methods".
@calculate: (run_hhmmss, run_ppm, walk_hhmmss, walk_ppm, miles) ->
result = {}
if run_hhmmss and run_ppm and walk_hhmmss and walk_ppm
run_duration_elapsed_time = new ElapsedTime(run_hhmmss)
run_ppm_elapsed_time = new ElapsedTime(run_ppm)
walk_duration_elapsed_time = new ElapsedTime(walk_hhmmss)
walk_ppm_elapsed_time = new ElapsedTime(walk_ppm)
distance = new Distance(miles)
mile = new Distance(1.0)
total_secs = run_duration_elapsed_time.seconds() + walk_duration_elapsed_time.seconds()
run_pct = run_duration_elapsed_time.seconds() / total_secs
walk_pct = 1.0 - run_pct
run_secs = run_pct * run_ppm_elapsed_time.seconds()
walk_secs = walk_pct * walk_ppm_elapsed_time.seconds()
avg_secs = run_secs + walk_secs
avg_time = new ElapsedTime(avg_secs)
avg_speed = new Speed(mile, avg_time)
mph = avg_speed.mph()
proj_time = avg_speed.projected_time(distance)
result.avg_mph = avg_speed.mph()
result.avg_ppm = avg_speed.pace_per_mile()
result.proj_time = avg_speed.projected_time(distance)
result.proj_miles = distance.as_miles()
result
root.RunWalkCalculator = RunWalkCalculator
|
[
{
"context": "ect containing properties to be set e.g. { name: 'my name' }\n set: (properties) =>\n _.each properties, ",
"end": 8566,
"score": 0.8635609745979309,
"start": 8559,
"tag": "NAME",
"value": "my name"
}
] | src/model/baseModel.coffee | BlackBalloon/hapi-simple-orm | 2 | 'use strict'
Joi = require 'joi'
_ = require 'underscore'
fs = require 'fs'
knexConf = require process.cwd() + '/knexfile'
knex = require('knex')(knexConf[process.env.NODE_ENV])
Promise = require 'bluebird'
ForeignKey = require '../fields/foreignKey'
BaseField = require '../fields/baseField'
ManyToMany = require '../fields/manyToMany'
ManyToOne = require '../fields/manyToOne'
BaseDAO = require './../dao/baseDao'
moduleKeywords = ['extended', 'included']
acceptableMetadataAttributes = [
'model' # name of current Model
'singular' # singular name of the database table e.g. account_category
'tableName' # name of table in database
'primaryKey' # pk of table
'timestamps' # boolean defining if timestamp fields should be included
'dao' # DAO object of current Model
'errorLogger' # if you want to log errors, pass the log4js error logger object
]
class BaseModel
@injectDao: (obj) ->
@objects = ->
return obj
obj.extended?.apply(@)
this
@extend: (obj) ->
# add 'metadata' attribute to the model and apply parameters to it
@metadata = {}
for key, value of obj when key not in moduleKeywords
if key not in acceptableMetadataAttributes
throw new Error "The '#{key}' attribute in Model's metadata is not acceptable.\n
Acceptable attributes are #{acceptableMetadataAttributes}."
@metadata[key] = value
# default 'model' value is name of the Class e.g. AccountCategory
if not @metadata.model?
@metadata.model = @name
# collection name used in case of MongoDB logging, translates e.g. AccountCategory to accountCategory
@metadata.collectionName = @name.substring(0, 1).toLowerCase() + @name.substring(1)
# default 'singular' value is snake_case of Class e.g. account_category
if not @metadata.singular?
@metadata.singular = @_camelToSnakeCase @name
# default 'tableName' is snake_case of Class + 's' e.g. users (User)
if not @metadata.tableName?
@metadata.tableName = @_camelToSnakeCase(@name) + 's'
# default 'primaryKey' is set to 'id'
if not @metadata.primaryKey?
@metadata.primaryKey = 'id'
# if 'timestamps' attribute was not passed, we set its default val to true
if not @metadata.timestamps?
@metadata.timestamps = true
# default 'dao' is set to BaseDAO if not passed
if not @metadata.dao?
@metadata.dao = BaseDAO
dao = @metadata.dao
@objects = =>
return new @metadata.dao @
obj.extended?.apply(@)
this
@include: (obj) ->
@::['attributes'] = {}
@::['fields'] = []
for key, value of obj when key not in moduleKeywords
@::['fields'].push key
@::['attributes'][key] = value
_.extend @::['attributes'], @::timestampAttributes
obj.included?.apply(@)
this
timestampAttributes:
createdAt: new BaseField(
schema: Joi.date().format('YYYY-MM-DD HH:mm:ss')
name: 'createdAt'
)
whoCreated: new BaseField(
schema: Joi.number().integer().positive()
name: 'whoCreated'
dbField: 'who_created_id'
)
deletedAt: new BaseField(
schema: Joi.date().format('YYYY-MM-DD HH:mm:ss')
name: 'deletedAt'
)
whoDeleted: new BaseField(
schema: Joi.number().integer().positive()
name: 'whoDeleted'
dbField: 'who_deleted_id'
)
isDeleted: new BaseField(
schema: Joi.boolean()
name: 'isDeleted'
)
# Class Method used to convert passed parameter to 'camelCase'
# @param [String] string value to be translated to camelCase
# @param [Object] attributes current model's attributes used to define foreign keys
@_snakeToCamelCase: (string, attributes) ->
camelCase = string.replace /(_\w)/g, (m) ->
return m[1].toUpperCase()
if attributes?
# if passed attribute is a foreign key in given model
# then we need to cut the 'Id' part of resulting string
if attributes[camelCase] instanceof ForeignKey
camelCase.slice 0, -2
camelCase
# Class Method used to convert passed parameter to 'snake_case'
# @param [String] string value to be translated to snake_case
# @param [Object] attributes current model's attributes used to define foreign keys
@_camelToSnakeCase: (string, attributes) ->
snakeCase = (string.replace /\.?([A-Z])/g, (m, n) ->
return '_' + n.toLowerCase()
).replace /^_/, ''
if attributes?
# if passed attribute is a foreign key of given model
# then we need to add the '_id' part to resulting string
if attributes[string] instanceof ForeignKey
snakeCase += '_id'
snakeCase
# simple Class Method which returns object containing all keys of the Model
# and 'schema' (Joi validation objects) as value for every key
@getSchema: (fields, partial) ->
attributesWithSchema = _.pick @::attributes, (val, key) =>
val.attributes.schema? and not (key of BaseModel::timestampAttributes) and key in @::fields
_.mapObject attributesWithSchema, (val, key) ->
schema = val.attributes.schema
if val.attributes.required and not partial
schema = schema.required()
else if not val.attributes.required
schema = schema.allow(null)
schema
# constructor for Model
# @param [Object] properties properties passed to create new Model instance
constructor: (properties) ->
manyToOneManager = ManyToOne.getManyToOneManager()
manyToManyManager = ManyToMany.getManyToManyManager()
_.each @attributes, (val, key) =>
# adding many to many related attributes to model's instance
if val instanceof ManyToMany
if not (_.has val.attributes, 'throughFields')
toModel = require val.attributes.toModel
throughFields = []
throughFields.push @constructor.metadata.singular + '_' + @constructor.metadata.primaryKey
throughFields.push toModel.metadata.singular + '_' + toModel.metadata.primaryKey
val.attributes.throughFields = throughFields
@[key] = new manyToManyManager @, key, val
# adding many to one related attributes to model's instance
if val instanceof ManyToOne
if not (_.has val.attributes, 'referenceField')
val.attributes.referenceField = @constructor.metadata.singular + '_' + @constructor.metadata.primaryKey
@[key] = new manyToOneManager @, key, val
try
@set properties
catch error
throw error
# translate JSON object to database format (camelCase to snake_case)
# operates on Model instance, applies setter on every field if it was set
_toDatabaseFields: =>
databaseObject = {}
for key, value of @attributes
# we check if value for specified key was set
# we also check if the attribute has 'dbField' assigned
# otherwise it is a virtual attribute which is not saved in the DB
if @[key] isnt undefined and value.attributes.dbField and not value.attributes.abstract
# apply all setters
databaseObject[value.attributes.dbField] = if value.attributes.set? then value.attributes.set @ else @[key]
databaseObject
# retrieve Model instance's value for specified key
# @param [String] key returns value of field of model's instance for specified key
# @param [Boolean] toObject boolean value which defines if related FK should be returned as model instance
get: (key, toObject) =>
if key of @attributes
if @attributes[key].attributes.get?
return @attributes[key].attributes.get @
# we check if desired attribute is a foreign key
# if it is, we need to return referenced Model's instance from DB
if @attributes[key] instanceof ForeignKey and @[key]?
lookup = {}
lookup[@attributes[key].attributes.referenceField] = @[key]
return @attributes[key].attributes.referenceModel.objects().get({ lookup: lookup, toObject: toObject })
.then (result) ->
return result
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
else
# otherwise we just return value for specified key
return @[key]
else
throw new TypeError "The '#{key}' field does not match any attribute of model #{@constructor.metadata.model}!"
# set specified keys of the Model instance with given values
# @param [Object] properties object containing properties to be set e.g. { name: 'my name' }
set: (properties) =>
_.each properties, (value, key) =>
if key of @attributes
if @attributes[key] instanceof ForeignKey
if value instanceof BaseModel
if value instanceof @attributes[key].attributes.referenceModel
@[key] = value.get(@attributes[key].attributes.referenceModel.metadata.primaryKey)
else
throw new TypeError "Value for '#{key}' of #{@constructor.metadata.model} should be FK value or instance of #{@attributes[key].attributes.referenceModel.metadata.model}!"
else
@[key] = value
else
@[key] = value
else
throw new TypeError "The '#{key}' field does not match any attribute of model #{@constructor.metadata.model}!"
@
# translate Object retrieved from database to JSON readable format
# initially it would return all fields from Model, however it is able
# to pass 'attributes' param, which defines which fields should be returned
# this method operations on Model instance
# @param [Array] attributes array of attributes to be returned from model
toJSON: ({ attributes } = {}) =>
attributes ?= _.keys @attributes
jsonObject = {}
_.each attributes, (key, val) =>
if not (@attributes[key] instanceof ManyToMany) and not (@attributes[key] instanceof ManyToOne)
if @attributes[key] instanceof ForeignKey
jsonObject[key] = @[key]
else
jsonObject[key] = if @get(key) isnt undefined then @get(key)
jsonObject
# method validating every attribute of model's instance
# @param [Object] trx - transaction object in case when multiple records will be impacted
validate: ({ trx } = {}) =>
promises = []
_.each @attributes, (value, key) =>
if not value.attributes.abstract?
promises.push value.validate @, { primaryKey: @[@constructor.metadata.primaryKey], trx: trx }
Promise.all(promises).then (values) ->
validationResultObject = {}
# get rid of elements that are 'undefined'
# change array format of the validation result to object
_.each (_.compact values), (val, key) ->
_.extend validationResultObject, val
finalValidationError = {}
if not (_.isEmpty(validationResultObject))
_.extend finalValidationError, { error: 'ValidationError', fields: validationResultObject }
finalValidationError
# Instance method which performs Model save to the database
# First, the validation is performed - if it passes, then model is saved
save: ({ returning, toObject } = {}) =>
@validate().then (validationResult) =>
# we check if 'validationResult' is an empty object
# if it is not, it means that validation returned errors
if not (_.isEmpty validationResult)
throw validationResult
# we check if the instance has primary key set
# if it does, then method should be 'update'
# otherwise it is 'create'
if @[@constructor.metadata.primaryKey]?
@constructor.objects().update({ obj: @, returning: returning, toObject: toObject }).then (res) ->
return res
else
@constructor.objects().create({ data: @_toDatabaseFields(), returning: returning, toObject: toObject, direct: false }).then (res) ->
return res
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
# Instance method used to delete current Model's instance
# before deleting, the primary key of the instance must be checked
# whether it exists - otherwise it means that instance wasnt saved to DB before
delete: (whoDeleted) =>
primaryKey = @constructor.metadata.primaryKey
if @[primaryKey]?
@constructor.objects().delete(@[primaryKey], whoDeleted).then (result) ->
return result
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
else
throw new Error "This #{@constructor.metadata.model} does not have primary key set!"
module.exports = BaseModel
| 86029 | 'use strict'
Joi = require 'joi'
_ = require 'underscore'
fs = require 'fs'
knexConf = require process.cwd() + '/knexfile'
knex = require('knex')(knexConf[process.env.NODE_ENV])
Promise = require 'bluebird'
ForeignKey = require '../fields/foreignKey'
BaseField = require '../fields/baseField'
ManyToMany = require '../fields/manyToMany'
ManyToOne = require '../fields/manyToOne'
BaseDAO = require './../dao/baseDao'
moduleKeywords = ['extended', 'included']
acceptableMetadataAttributes = [
'model' # name of current Model
'singular' # singular name of the database table e.g. account_category
'tableName' # name of table in database
'primaryKey' # pk of table
'timestamps' # boolean defining if timestamp fields should be included
'dao' # DAO object of current Model
'errorLogger' # if you want to log errors, pass the log4js error logger object
]
class BaseModel
@injectDao: (obj) ->
@objects = ->
return obj
obj.extended?.apply(@)
this
@extend: (obj) ->
# add 'metadata' attribute to the model and apply parameters to it
@metadata = {}
for key, value of obj when key not in moduleKeywords
if key not in acceptableMetadataAttributes
throw new Error "The '#{key}' attribute in Model's metadata is not acceptable.\n
Acceptable attributes are #{acceptableMetadataAttributes}."
@metadata[key] = value
# default 'model' value is name of the Class e.g. AccountCategory
if not @metadata.model?
@metadata.model = @name
# collection name used in case of MongoDB logging, translates e.g. AccountCategory to accountCategory
@metadata.collectionName = @name.substring(0, 1).toLowerCase() + @name.substring(1)
# default 'singular' value is snake_case of Class e.g. account_category
if not @metadata.singular?
@metadata.singular = @_camelToSnakeCase @name
# default 'tableName' is snake_case of Class + 's' e.g. users (User)
if not @metadata.tableName?
@metadata.tableName = @_camelToSnakeCase(@name) + 's'
# default 'primaryKey' is set to 'id'
if not @metadata.primaryKey?
@metadata.primaryKey = 'id'
# if 'timestamps' attribute was not passed, we set its default val to true
if not @metadata.timestamps?
@metadata.timestamps = true
# default 'dao' is set to BaseDAO if not passed
if not @metadata.dao?
@metadata.dao = BaseDAO
dao = @metadata.dao
@objects = =>
return new @metadata.dao @
obj.extended?.apply(@)
this
@include: (obj) ->
@::['attributes'] = {}
@::['fields'] = []
for key, value of obj when key not in moduleKeywords
@::['fields'].push key
@::['attributes'][key] = value
_.extend @::['attributes'], @::timestampAttributes
obj.included?.apply(@)
this
timestampAttributes:
createdAt: new BaseField(
schema: Joi.date().format('YYYY-MM-DD HH:mm:ss')
name: 'createdAt'
)
whoCreated: new BaseField(
schema: Joi.number().integer().positive()
name: 'whoCreated'
dbField: 'who_created_id'
)
deletedAt: new BaseField(
schema: Joi.date().format('YYYY-MM-DD HH:mm:ss')
name: 'deletedAt'
)
whoDeleted: new BaseField(
schema: Joi.number().integer().positive()
name: 'whoDeleted'
dbField: 'who_deleted_id'
)
isDeleted: new BaseField(
schema: Joi.boolean()
name: 'isDeleted'
)
# Class Method used to convert passed parameter to 'camelCase'
# @param [String] string value to be translated to camelCase
# @param [Object] attributes current model's attributes used to define foreign keys
@_snakeToCamelCase: (string, attributes) ->
camelCase = string.replace /(_\w)/g, (m) ->
return m[1].toUpperCase()
if attributes?
# if passed attribute is a foreign key in given model
# then we need to cut the 'Id' part of resulting string
if attributes[camelCase] instanceof ForeignKey
camelCase.slice 0, -2
camelCase
# Class Method used to convert passed parameter to 'snake_case'
# @param [String] string value to be translated to snake_case
# @param [Object] attributes current model's attributes used to define foreign keys
@_camelToSnakeCase: (string, attributes) ->
snakeCase = (string.replace /\.?([A-Z])/g, (m, n) ->
return '_' + n.toLowerCase()
).replace /^_/, ''
if attributes?
# if passed attribute is a foreign key of given model
# then we need to add the '_id' part to resulting string
if attributes[string] instanceof ForeignKey
snakeCase += '_id'
snakeCase
# simple Class Method which returns object containing all keys of the Model
# and 'schema' (Joi validation objects) as value for every key
@getSchema: (fields, partial) ->
attributesWithSchema = _.pick @::attributes, (val, key) =>
val.attributes.schema? and not (key of BaseModel::timestampAttributes) and key in @::fields
_.mapObject attributesWithSchema, (val, key) ->
schema = val.attributes.schema
if val.attributes.required and not partial
schema = schema.required()
else if not val.attributes.required
schema = schema.allow(null)
schema
# constructor for Model
# @param [Object] properties properties passed to create new Model instance
constructor: (properties) ->
manyToOneManager = ManyToOne.getManyToOneManager()
manyToManyManager = ManyToMany.getManyToManyManager()
_.each @attributes, (val, key) =>
# adding many to many related attributes to model's instance
if val instanceof ManyToMany
if not (_.has val.attributes, 'throughFields')
toModel = require val.attributes.toModel
throughFields = []
throughFields.push @constructor.metadata.singular + '_' + @constructor.metadata.primaryKey
throughFields.push toModel.metadata.singular + '_' + toModel.metadata.primaryKey
val.attributes.throughFields = throughFields
@[key] = new manyToManyManager @, key, val
# adding many to one related attributes to model's instance
if val instanceof ManyToOne
if not (_.has val.attributes, 'referenceField')
val.attributes.referenceField = @constructor.metadata.singular + '_' + @constructor.metadata.primaryKey
@[key] = new manyToOneManager @, key, val
try
@set properties
catch error
throw error
# translate JSON object to database format (camelCase to snake_case)
# operates on Model instance, applies setter on every field if it was set
_toDatabaseFields: =>
databaseObject = {}
for key, value of @attributes
# we check if value for specified key was set
# we also check if the attribute has 'dbField' assigned
# otherwise it is a virtual attribute which is not saved in the DB
if @[key] isnt undefined and value.attributes.dbField and not value.attributes.abstract
# apply all setters
databaseObject[value.attributes.dbField] = if value.attributes.set? then value.attributes.set @ else @[key]
databaseObject
# retrieve Model instance's value for specified key
# @param [String] key returns value of field of model's instance for specified key
# @param [Boolean] toObject boolean value which defines if related FK should be returned as model instance
get: (key, toObject) =>
if key of @attributes
if @attributes[key].attributes.get?
return @attributes[key].attributes.get @
# we check if desired attribute is a foreign key
# if it is, we need to return referenced Model's instance from DB
if @attributes[key] instanceof ForeignKey and @[key]?
lookup = {}
lookup[@attributes[key].attributes.referenceField] = @[key]
return @attributes[key].attributes.referenceModel.objects().get({ lookup: lookup, toObject: toObject })
.then (result) ->
return result
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
else
# otherwise we just return value for specified key
return @[key]
else
throw new TypeError "The '#{key}' field does not match any attribute of model #{@constructor.metadata.model}!"
# set specified keys of the Model instance with given values
# @param [Object] properties object containing properties to be set e.g. { name: '<NAME>' }
set: (properties) =>
_.each properties, (value, key) =>
if key of @attributes
if @attributes[key] instanceof ForeignKey
if value instanceof BaseModel
if value instanceof @attributes[key].attributes.referenceModel
@[key] = value.get(@attributes[key].attributes.referenceModel.metadata.primaryKey)
else
throw new TypeError "Value for '#{key}' of #{@constructor.metadata.model} should be FK value or instance of #{@attributes[key].attributes.referenceModel.metadata.model}!"
else
@[key] = value
else
@[key] = value
else
throw new TypeError "The '#{key}' field does not match any attribute of model #{@constructor.metadata.model}!"
@
# translate Object retrieved from database to JSON readable format
# initially it would return all fields from Model, however it is able
# to pass 'attributes' param, which defines which fields should be returned
# this method operations on Model instance
# @param [Array] attributes array of attributes to be returned from model
toJSON: ({ attributes } = {}) =>
attributes ?= _.keys @attributes
jsonObject = {}
_.each attributes, (key, val) =>
if not (@attributes[key] instanceof ManyToMany) and not (@attributes[key] instanceof ManyToOne)
if @attributes[key] instanceof ForeignKey
jsonObject[key] = @[key]
else
jsonObject[key] = if @get(key) isnt undefined then @get(key)
jsonObject
# method validating every attribute of model's instance
# @param [Object] trx - transaction object in case when multiple records will be impacted
validate: ({ trx } = {}) =>
promises = []
_.each @attributes, (value, key) =>
if not value.attributes.abstract?
promises.push value.validate @, { primaryKey: @[@constructor.metadata.primaryKey], trx: trx }
Promise.all(promises).then (values) ->
validationResultObject = {}
# get rid of elements that are 'undefined'
# change array format of the validation result to object
_.each (_.compact values), (val, key) ->
_.extend validationResultObject, val
finalValidationError = {}
if not (_.isEmpty(validationResultObject))
_.extend finalValidationError, { error: 'ValidationError', fields: validationResultObject }
finalValidationError
# Instance method which performs Model save to the database
# First, the validation is performed - if it passes, then model is saved
save: ({ returning, toObject } = {}) =>
@validate().then (validationResult) =>
# we check if 'validationResult' is an empty object
# if it is not, it means that validation returned errors
if not (_.isEmpty validationResult)
throw validationResult
# we check if the instance has primary key set
# if it does, then method should be 'update'
# otherwise it is 'create'
if @[@constructor.metadata.primaryKey]?
@constructor.objects().update({ obj: @, returning: returning, toObject: toObject }).then (res) ->
return res
else
@constructor.objects().create({ data: @_toDatabaseFields(), returning: returning, toObject: toObject, direct: false }).then (res) ->
return res
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
# Instance method used to delete current Model's instance
# before deleting, the primary key of the instance must be checked
# whether it exists - otherwise it means that instance wasnt saved to DB before
delete: (whoDeleted) =>
primaryKey = @constructor.metadata.primaryKey
if @[primaryKey]?
@constructor.objects().delete(@[primaryKey], whoDeleted).then (result) ->
return result
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
else
throw new Error "This #{@constructor.metadata.model} does not have primary key set!"
module.exports = BaseModel
| true | 'use strict'
Joi = require 'joi'
_ = require 'underscore'
fs = require 'fs'
knexConf = require process.cwd() + '/knexfile'
knex = require('knex')(knexConf[process.env.NODE_ENV])
Promise = require 'bluebird'
ForeignKey = require '../fields/foreignKey'
BaseField = require '../fields/baseField'
ManyToMany = require '../fields/manyToMany'
ManyToOne = require '../fields/manyToOne'
BaseDAO = require './../dao/baseDao'
moduleKeywords = ['extended', 'included']
acceptableMetadataAttributes = [
'model' # name of current Model
'singular' # singular name of the database table e.g. account_category
'tableName' # name of table in database
'primaryKey' # pk of table
'timestamps' # boolean defining if timestamp fields should be included
'dao' # DAO object of current Model
'errorLogger' # if you want to log errors, pass the log4js error logger object
]
class BaseModel
@injectDao: (obj) ->
@objects = ->
return obj
obj.extended?.apply(@)
this
@extend: (obj) ->
# add 'metadata' attribute to the model and apply parameters to it
@metadata = {}
for key, value of obj when key not in moduleKeywords
if key not in acceptableMetadataAttributes
throw new Error "The '#{key}' attribute in Model's metadata is not acceptable.\n
Acceptable attributes are #{acceptableMetadataAttributes}."
@metadata[key] = value
# default 'model' value is name of the Class e.g. AccountCategory
if not @metadata.model?
@metadata.model = @name
# collection name used in case of MongoDB logging, translates e.g. AccountCategory to accountCategory
@metadata.collectionName = @name.substring(0, 1).toLowerCase() + @name.substring(1)
# default 'singular' value is snake_case of Class e.g. account_category
if not @metadata.singular?
@metadata.singular = @_camelToSnakeCase @name
# default 'tableName' is snake_case of Class + 's' e.g. users (User)
if not @metadata.tableName?
@metadata.tableName = @_camelToSnakeCase(@name) + 's'
# default 'primaryKey' is set to 'id'
if not @metadata.primaryKey?
@metadata.primaryKey = 'id'
# if 'timestamps' attribute was not passed, we set its default val to true
if not @metadata.timestamps?
@metadata.timestamps = true
# default 'dao' is set to BaseDAO if not passed
if not @metadata.dao?
@metadata.dao = BaseDAO
dao = @metadata.dao
@objects = =>
return new @metadata.dao @
obj.extended?.apply(@)
this
@include: (obj) ->
@::['attributes'] = {}
@::['fields'] = []
for key, value of obj when key not in moduleKeywords
@::['fields'].push key
@::['attributes'][key] = value
_.extend @::['attributes'], @::timestampAttributes
obj.included?.apply(@)
this
timestampAttributes:
createdAt: new BaseField(
schema: Joi.date().format('YYYY-MM-DD HH:mm:ss')
name: 'createdAt'
)
whoCreated: new BaseField(
schema: Joi.number().integer().positive()
name: 'whoCreated'
dbField: 'who_created_id'
)
deletedAt: new BaseField(
schema: Joi.date().format('YYYY-MM-DD HH:mm:ss')
name: 'deletedAt'
)
whoDeleted: new BaseField(
schema: Joi.number().integer().positive()
name: 'whoDeleted'
dbField: 'who_deleted_id'
)
isDeleted: new BaseField(
schema: Joi.boolean()
name: 'isDeleted'
)
# Class Method used to convert passed parameter to 'camelCase'
# @param [String] string value to be translated to camelCase
# @param [Object] attributes current model's attributes used to define foreign keys
@_snakeToCamelCase: (string, attributes) ->
camelCase = string.replace /(_\w)/g, (m) ->
return m[1].toUpperCase()
if attributes?
# if passed attribute is a foreign key in given model
# then we need to cut the 'Id' part of resulting string
if attributes[camelCase] instanceof ForeignKey
camelCase.slice 0, -2
camelCase
# Class Method used to convert passed parameter to 'snake_case'
# @param [String] string value to be translated to snake_case
# @param [Object] attributes current model's attributes used to define foreign keys
@_camelToSnakeCase: (string, attributes) ->
snakeCase = (string.replace /\.?([A-Z])/g, (m, n) ->
return '_' + n.toLowerCase()
).replace /^_/, ''
if attributes?
# if passed attribute is a foreign key of given model
# then we need to add the '_id' part to resulting string
if attributes[string] instanceof ForeignKey
snakeCase += '_id'
snakeCase
# simple Class Method which returns object containing all keys of the Model
# and 'schema' (Joi validation objects) as value for every key
@getSchema: (fields, partial) ->
attributesWithSchema = _.pick @::attributes, (val, key) =>
val.attributes.schema? and not (key of BaseModel::timestampAttributes) and key in @::fields
_.mapObject attributesWithSchema, (val, key) ->
schema = val.attributes.schema
if val.attributes.required and not partial
schema = schema.required()
else if not val.attributes.required
schema = schema.allow(null)
schema
# constructor for Model
# @param [Object] properties properties passed to create new Model instance
constructor: (properties) ->
manyToOneManager = ManyToOne.getManyToOneManager()
manyToManyManager = ManyToMany.getManyToManyManager()
_.each @attributes, (val, key) =>
# adding many to many related attributes to model's instance
if val instanceof ManyToMany
if not (_.has val.attributes, 'throughFields')
toModel = require val.attributes.toModel
throughFields = []
throughFields.push @constructor.metadata.singular + '_' + @constructor.metadata.primaryKey
throughFields.push toModel.metadata.singular + '_' + toModel.metadata.primaryKey
val.attributes.throughFields = throughFields
@[key] = new manyToManyManager @, key, val
# adding many to one related attributes to model's instance
if val instanceof ManyToOne
if not (_.has val.attributes, 'referenceField')
val.attributes.referenceField = @constructor.metadata.singular + '_' + @constructor.metadata.primaryKey
@[key] = new manyToOneManager @, key, val
try
@set properties
catch error
throw error
# translate JSON object to database format (camelCase to snake_case)
# operates on Model instance, applies setter on every field if it was set
_toDatabaseFields: =>
databaseObject = {}
for key, value of @attributes
# we check if value for specified key was set
# we also check if the attribute has 'dbField' assigned
# otherwise it is a virtual attribute which is not saved in the DB
if @[key] isnt undefined and value.attributes.dbField and not value.attributes.abstract
# apply all setters
databaseObject[value.attributes.dbField] = if value.attributes.set? then value.attributes.set @ else @[key]
databaseObject
# retrieve Model instance's value for specified key
# @param [String] key returns value of field of model's instance for specified key
# @param [Boolean] toObject boolean value which defines if related FK should be returned as model instance
get: (key, toObject) =>
if key of @attributes
if @attributes[key].attributes.get?
return @attributes[key].attributes.get @
# we check if desired attribute is a foreign key
# if it is, we need to return referenced Model's instance from DB
if @attributes[key] instanceof ForeignKey and @[key]?
lookup = {}
lookup[@attributes[key].attributes.referenceField] = @[key]
return @attributes[key].attributes.referenceModel.objects().get({ lookup: lookup, toObject: toObject })
.then (result) ->
return result
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
else
# otherwise we just return value for specified key
return @[key]
else
throw new TypeError "The '#{key}' field does not match any attribute of model #{@constructor.metadata.model}!"
# set specified keys of the Model instance with given values
# @param [Object] properties object containing properties to be set e.g. { name: 'PI:NAME:<NAME>END_PI' }
set: (properties) =>
_.each properties, (value, key) =>
if key of @attributes
if @attributes[key] instanceof ForeignKey
if value instanceof BaseModel
if value instanceof @attributes[key].attributes.referenceModel
@[key] = value.get(@attributes[key].attributes.referenceModel.metadata.primaryKey)
else
throw new TypeError "Value for '#{key}' of #{@constructor.metadata.model} should be FK value or instance of #{@attributes[key].attributes.referenceModel.metadata.model}!"
else
@[key] = value
else
@[key] = value
else
throw new TypeError "The '#{key}' field does not match any attribute of model #{@constructor.metadata.model}!"
@
# translate Object retrieved from database to JSON readable format
# initially it would return all fields from Model, however it is able
# to pass 'attributes' param, which defines which fields should be returned
# this method operations on Model instance
# @param [Array] attributes array of attributes to be returned from model
toJSON: ({ attributes } = {}) =>
attributes ?= _.keys @attributes
jsonObject = {}
_.each attributes, (key, val) =>
if not (@attributes[key] instanceof ManyToMany) and not (@attributes[key] instanceof ManyToOne)
if @attributes[key] instanceof ForeignKey
jsonObject[key] = @[key]
else
jsonObject[key] = if @get(key) isnt undefined then @get(key)
jsonObject
# method validating every attribute of model's instance
# @param [Object] trx - transaction object in case when multiple records will be impacted
validate: ({ trx } = {}) =>
promises = []
_.each @attributes, (value, key) =>
if not value.attributes.abstract?
promises.push value.validate @, { primaryKey: @[@constructor.metadata.primaryKey], trx: trx }
Promise.all(promises).then (values) ->
validationResultObject = {}
# get rid of elements that are 'undefined'
# change array format of the validation result to object
_.each (_.compact values), (val, key) ->
_.extend validationResultObject, val
finalValidationError = {}
if not (_.isEmpty(validationResultObject))
_.extend finalValidationError, { error: 'ValidationError', fields: validationResultObject }
finalValidationError
# Instance method which performs Model save to the database
# First, the validation is performed - if it passes, then model is saved
save: ({ returning, toObject } = {}) =>
@validate().then (validationResult) =>
# we check if 'validationResult' is an empty object
# if it is not, it means that validation returned errors
if not (_.isEmpty validationResult)
throw validationResult
# we check if the instance has primary key set
# if it does, then method should be 'update'
# otherwise it is 'create'
if @[@constructor.metadata.primaryKey]?
@constructor.objects().update({ obj: @, returning: returning, toObject: toObject }).then (res) ->
return res
else
@constructor.objects().create({ data: @_toDatabaseFields(), returning: returning, toObject: toObject, direct: false }).then (res) ->
return res
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
# Instance method used to delete current Model's instance
# before deleting, the primary key of the instance must be checked
# whether it exists - otherwise it means that instance wasnt saved to DB before
delete: (whoDeleted) =>
primaryKey = @constructor.metadata.primaryKey
if @[primaryKey]?
@constructor.objects().delete(@[primaryKey], whoDeleted).then (result) ->
return result
.catch (error) =>
if @constructor.metadata.errorLogger?
@constructor.metadata.errorLogger.error error
throw error
else
throw new Error "This #{@constructor.metadata.model} does not have primary key set!"
module.exports = BaseModel
|
[
{
"context": "me\" placeholder=\"Name (Required)\" ng-model=\"model.name\" focus-me=\"step=='model'\" required>\n ",
"end": 3862,
"score": 0.8192542791366577,
"start": 3858,
"tag": "NAME",
"value": "name"
},
{
"context": "text\" class=\"form-control\" id=\"name\" placehol... | ModelCatalogueCorePlugin/grails-app/assets/javascripts/modelcatalogue/core/ui/bs/modelWizard.coffee | tumtumtree/tumtumtree | 0 | angular.module('mc.core.ui.bs.modelWizard', ['mc.util.messages', 'mc.util.ui.focusMe']).config ['messagesProvider', (messagesProvider)->
factory = [ '$modal', '$q', 'messages', '$rootScope', ($modal, $q, messages,$rootScope) ->
(title, body, args) ->
# TODO: add add classifications step
$rootScope.createModelWizard ?= $modal.open {
windowClass: 'create-model-wizard'
backdrop: 'static'
keyboard: false
size: 'lg'
resolve:
args: -> args
#language=HTML
template: '''
<div class="modal-header">
<button type="button" class="close" ng-click="dismiss()"><span aria-hidden="true">×</span><span class="sr-only">Cancel</span></button>
<h4>Model Wizard</span></h4>
<ul class="tutorial-steps">
<li>
<button id="step-previous" ng-disabled="step == 'model' || step == 'summary'" ng-click="previous()" class="btn btn-default"><span class="glyphicon glyphicon-chevron-left"></span></button>
</li>
<li>
<button id="step-model" ng-disabled="step == 'summary'" ng-click="select('model')" class="btn btn-default" ng-class="{'btn-primary': step == 'model'}">1. Model</button>
</li>
<li>
<button id="step-metadata" ng-disabled="!model.name || step == 'summary'" ng-click="select('metadata')" class="btn btn-default" ng-class="{'btn-primary': step == 'metadata', 'btn-info': step != 'metadata' && hasMetadata()}">2. Metadata</button>
</li>
<li>
<button id="step-parents" ng-disabled="!model.name || step == 'summary'" ng-click="select('parents')" class="btn btn-default" ng-class="{'btn-primary': step == 'parents', 'btn-info': step != 'parents' && parents.length > 0}">3. Parents</button>
</li>
<li>
<button id="step-children" ng-disabled="!model.name || step == 'summary'" ng-click="select('children')" class="btn btn-default" ng-class="{'btn-primary': step == 'children', 'btn-info': step != 'children' && children.length > 0}">4. Children</button>
</li>
<li>
<button id="step-elements" ng-disabled="!model.name || step == 'summary'" ng-click="select('elements')" class="btn btn-default" ng-class="{'btn-primary': step == 'elements', 'btn-info': step != 'elements' && dataElements.length > 0}">5. Elements</button>
</li>
<li>
<button id="step-classifications" ng-disabled="!model.name || step == 'summary'" ng-click="select('classifications')" class="btn btn-default" ng-class="{'btn-primary': step == 'classifications', 'btn-info': step != 'classifications' && classifications.length > 0}">6. Classifications</button>
</li>
<li>
<button id="step-next" ng-disabled="!model.name || step == 'classifications' || step == 'summary'" ng-click="next()" class="btn btn-default" ><span class="glyphicon glyphicon-chevron-right"></span></button>
</li>
<li>
<button id="step-finish" ng-disabled="!model.name || !isModelCatalogueIdValid()" ng-click="finish()" class="btn btn-default btn-success"><span class="glyphicon glyphicon-ok"></span></button>
</li>
</ul>
</div>
<div class="modal-body" ng-switch="step">
<div ng-switch-when="model" id="model">
<form role="form" ng-submit="select('metadata')">
<div class="form-group">
<label for="name" class="">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="Name (Required)" ng-model="model.name" focus-me="step=='model'" required>
<span class="input-group-btn">
<a class="btn btn-default" ng-click="prefillFrom()"><span class="fa fa-fw fa-copy"></span></a>
</span>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': !isModelCatalogueIdValid() }">
<label for="modelCatalogueId" class="">Catalogue ID (URL)</label>
<input type="text" class="form-control" id="modelCatalogueId" placeholder="e.g. external ID, namespace (leave blank for generated)" ng-model="model.modelCatalogueId">
</div>
<div class="form-group">
<label for="description" class="">Description</label>
<textarea rows="10" ng-model="model.description" placeholder="Description (Optional)" class="form-control" id="description" ng-keydown="navigateOnKey($event, 9, 'metadata')"></textarea>
</div>
</form>
</div>
<div ng-switch-when="metadata" id="metadata">
<form ng-submit="select('parents')">
<div>
<h4>Metadata</h4>
<ordered-map-editor title="Key" value-title="Value" object="metadata"></ordered-map-editor>
</div>
</form>
</div>
<div ng-switch-when="parents" id="parents">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Parent Model</label>
<elements-as-tags elements="parents"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="Name" ng-model="parent.element" focus-me="step=='parents'" catalogue-element-picker="model" typeahead-on-select="push('parents', 'parent')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('parents', 'parent')" ng-disabled="isEmpty(parent.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Parent model is source for the hierarchy relationship</p>
</div>
<ordered-map-editor object="parent.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</div>
<div ng-switch-when="children" id="children">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Child Model</label>
<elements-as-tags elements="children"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="Name" ng-model="child.element" focus-me="step=='children'" catalogue-element-picker="model" typeahead-on-select="push('children', 'child')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('children', 'child')" ng-disabled="isEmpty(child.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Child model is destination for the hierarchy relationship</p>
</div>
<div ng-click="importChildModelsFromCSV()">
<alert type="info">
<strong>Hint:</strong> If you have CSV file with sample data you can <a class="alert-link"><span class="fa fa-magic"></span> import child models from CSV file headers</a>.
</alert>
</div>
<ordered-map-editor object="child.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</div>
<div ng-switch-when="elements" id="elements">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Data Element</label>
<elements-as-tags elements="dataElements"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="Name" ng-model="dataElement.element" focus-me="step=='elements'" catalogue-element-picker="dataElement" typeahead-on-select="push('dataElements', 'dataElement')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('dataElements', 'dataElement')" ng-disabled="isEmpty(dataElement.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Data element is destination for the containment relationship</p>
</div>
<div ng-click="importFromCSV()">
<alert type="info">
<strong>Hint:</strong> If you have CSV file with sample data you can <a class="alert-link"><span class="fa fa-magic"></span> import data elements from CSV file headers</a>.
</alert>
</div>
<ordered-map-editor object="dataElement.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</tab>
</div>
<div ng-switch-when="classifications" id="classifications">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Classifications</label>
<elements-as-tags elements="classifications"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="Name" ng-model="classification.element" focus-me="step=='classifications'" catalogue-element-picker="classification" typeahead-on-select="push('classifications', 'classification')" status="draft">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('classifications', 'classification')" ng-disabled="isEmpty(classification.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
</div>
</form>
</tab>
</div>
<div ng-switch-when="summary" id="summary">
<h4 ng-show="model.name && !finished">Creating new model <strong>{{model.name}}</strong></h4>
<h4 ng-show="model.name && finished">Model <strong>{{model.name}} created</strong></h4>
<progressbar type="{{finished ? 'success' : 'primary'}}" value="pendingActionsCount == 0 ? 100 : Math.round(100 * (totalActions - pendingActionsCount) / totalActions)">{{totalActions - pendingActionsCount}} / {{totalActions}}</progressbar>
</div>
</div>
<div class="modal-footer" ng-if="step == 'summary'">
<button ng-disabled="!finished" class="btn btn-success" ng-click="reset()"><span class="glyphicon glyphicon-plus"></span> Create Another</button>
<button ng-disabled="!finished" class="btn btn-default" ng-click="$close(model)" id="exit-wizard"><span class="glyphicon glyphicon-remove"></span> Close</button>
</div>
'''
controller: ['$scope', '$state', '$window', 'messages', 'names', 'catalogueElementResource', '$modalInstance', '$timeout', 'args', 'delayedQueueExecutor', '$q', '$log', 'enhance', ($scope, $state, $window, messages, names, catalogueElementResource, $modalInstance, $timeout, args, delayedQueueExecutor, $q, $log, enhance) ->
execAfter50 = delayedQueueExecutor(500)
orderedMapEnhancer = enhance.getEnhancer('orderedMap')
$scope.reset = ->
$scope.args = args
$scope.model = {classifications: []}
$scope.metadata = orderedMapEnhancer.emptyOrderedMap()
$scope.parent = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.parents = []
$scope.child = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.children = []
$scope.dataElement = args.dataElement ? {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.dataElements = []
$scope.classification = {}
$scope.classifications = []
$scope.messages = messages.createNewMessages()
$scope.steps = ['model', 'metadata', 'parents', 'children', 'elements', 'classifications']
$scope.step = 'model'
$scope.pendingActions = []
$scope.pendingActionsCount = 0
$scope.totalActions = 0
$scope.finishInProgress = false
$scope.finished = false
$scope.parentsVisited = false
$scope.classificationsVisited = false
if args.parent
$scope.parents.push {element: args.parent, name: args.parent.name, metadata: orderedMapEnhancer.emptyOrderedMap()}
$scope.reset()
$scope.isEmpty = (object) ->
return true if not object
angular.equals object, {}
$scope.isString = (object) ->
angular.isString object
$scope.push = (arrayName, propertyName) ->
value = $scope[propertyName]
unless value
$log.warn "no scope value for #{propertyName}", $scope
return
if angular.isString value.element
value.name = value.element
value.create = true
else
value.name = value.element.name
$scope[arrayName].push value
$scope[propertyName] = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.openElementInNewWindow = (element) ->
url = $state.href('mc.resource.show', {resource: names.getPropertyNameFromType(element.elementType), id: element.id})
$window.open(url,'_blank')
$scope.finish = () ->
return if $scope.finishInProgress
$scope.finishInProgress = true
$scope.parents.push($scope.parent) if angular.isString($scope.parent?.element)
$scope.children.push($scope.child) if angular.isString($scope.child?.element)
$scope.dataElements.push($scope.dataElement) if angular.isString($scope.dataElement?.element)
$scope.classifications.push($scope.classification) if angular.isString($scope.classification?.element)
unless $scope.isEmpty($scope.metadata)
$scope.pendingActions.push (model)->
model.ext = $scope.metadata
execAfter50.submit -> catalogueElementResource('model').update(model)
angular.forEach $scope.parents, (parent) ->
if angular.isString parent.element
$scope.pendingActions.push (model) ->
catalogueElementResource("model").save({name: parent.element}).then (parentModel) ->
parent.element = parentModel
model
$scope.pendingActions.push (model) ->
parent.element.metadata = parent.ext
execAfter50.submit -> model.childOf.add parent.element
model
angular.forEach $scope.children, (child) ->
if angular.isString child.element
$scope.pendingActions.push (model) ->
catalogueElementResource("model").save({name: child.element}).then (childModel) ->
child.element = childModel
model
$scope.pendingActions.push (model) ->
child.element.metadata = child.ext
execAfter50.submit -> model.parentOf.add child.element
model
angular.forEach $scope.dataElements, (element) ->
if angular.isString element.element
$scope.pendingActions.push (model) ->
catalogueElementResource("dataElement").save({name: element.element}).then (newElement) ->
element.element = newElement
model
$scope.pendingActions.push (model) ->
element.element.metadata = element.ext
execAfter50.submit -> model.contains.add element.element
model
angular.forEach $scope.classifications, (classification) ->
if angular.isString classification.element
$scope.pendingActions.push (model) ->
catalogueElementResource('classification').save({name: classification.element}).then (newClassification) ->
model.classifications.push newClassification
execAfter50.submit -> catalogueElementResource('model').update(model)
else
$scope.pendingActions.push (model) ->
model.classifications.push classification.element
execAfter50.submit -> catalogueElementResource('model').update(model)
$scope.totalActions = $scope.pendingActionsCount = $scope.pendingActions.length + 1
$scope.step = 'summary'
decreasePendingActionsCount = (model) ->
$scope.pendingActionsCount--
# not very effective but otherwise lot of "entity updated by another transactions" occurs
model.refresh().then (fresh) ->
$timeout((-> fresh), 200)
promise = catalogueElementResource('model').save($scope.model).then decreasePendingActionsCount
for action in $scope.pendingActions
promise = promise.then(action).then decreasePendingActionsCount, (errorResponse) ->
if errorResponse.data.errors
for error in errorResponse.data.errors
messages.error(error.message)
else if errorResponse.data.error
messages.error(errorResponse.data.error)
else
messages.error('Unknown expection happened while creating new model. See application logs for details.')
$scope.finishInProgress = false
$q.reject errorResponse.data
promise.then (model) ->
messages.success "Model #{model.name} created"
$scope.finished = true
$scope.model = model
$scope.select = (step) ->
$scope.parentsVisited |= step == 'parents'
$scope.classificationsVisited |= step == 'classifications'
return if step != 'model' and not $scope.model.name
$scope.step = step
$scope.next = ->
return if not $scope.model.name
for step, i in $scope.steps
if step == $scope.step and i < $scope.steps.length - 1
nextStep = $scope.steps[i + 1]
if nextStep == 'summary'
$scope.finish()
else
$scope.step = nextStep
break
$scope.previous = ->
return if not $scope.model.name
for step, i in $scope.steps
if step == $scope.step and i != 0
$scope.step = $scope.steps[i - 1]
break
$scope.navigateOnKey = ($event, key, step) ->
$scope.select(step) if $event.keyCode == key
$scope.select('model')
$scope.importFromCSV = ->
messages.prompt("Import Data Elements", null, {type: 'data-element-suggestions-from-csv'}).then (result) ->
angular.forEach result, (element) ->
value = {element : element}
if angular.isString(value.element)
value = {name: value.element, create: true, element: value.element}
else
value.name = value.element.name
value.elementType = value.element.elementType
value.id = value.element.id
$scope.dataElements.push value
$scope.importChildModelsFromCSV = ->
messages.prompt("Import Child Models", null, {type: 'child-model-suggestions-from-csv'}).then (result) ->
angular.forEach result, (element) ->
value = {element : element}
if angular.isString(value.element)
value = {name: value.element, create: true, element: value.element}
else
value.name = value.element.name
value.elementType = value.element.elementType
value.id = value.element.id
$scope.children.push value
$scope.dismiss = (reason) ->
return $modalInstance.dismiss(reason) if $scope.finished
if $scope.model.name or $scope.model.description or not $scope.isEmpty($scope.metadata) or $scope.parents.length > 0 or $scope.children.length > 0 or $scope.dataElements.length > 0 or $scope.classifications.length > 0
messages.confirm("Close Model Wizard", "Do you want to discard all changes?").then ->
$modalInstance.dismiss(reason)
else
$modalInstance.dismiss(reason)
$scope.prefillFrom = ->
modelPromise = messages.prompt('Clone Model', 'Please, select from which Model should be the properties cloned', type: 'catalogue-element', resource: 'model')
modelPromise.then (model) ->
promises = []
$scope.model.name = model.name
$scope.model.description = model.description
$scope.metadata = angular.copy model.ext
angular.forEach model.classifications, (classification) ->
$scope.classifications.push {element: classification, name: classification.name}
push = (container, property) ->
(result) ->
angular.forEach result.list, (relation) ->
$scope[property] = element: relation.relation, ext: relation.ext
$scope.push container, property
$scope[property] = {ext: orderedMapEnhancer.emptyOrderedMap()}
promises.push model.parentOf(null, max: 100).then push('children', 'child')
promises.push model.contains(null, max: 100).then push('dataElements', 'dataElement')
$q.all promises
$scope.hasMetadata = ->
return $scope.metadata.values.length > 0 and $scope.metadata.values[0].key
$scope.isModelCatalogueIdValid = ->
return true if not $scope.model.modelCatalogueId
return new RegExp(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/).test($scope.model.modelCatalogueId)
]
}
$rootScope.createModelWizard.result.finally ->
$rootScope.createModelWizard = undefined
]
messagesProvider.setPromptFactory 'create-model', factory
] | 20365 | angular.module('mc.core.ui.bs.modelWizard', ['mc.util.messages', 'mc.util.ui.focusMe']).config ['messagesProvider', (messagesProvider)->
factory = [ '$modal', '$q', 'messages', '$rootScope', ($modal, $q, messages,$rootScope) ->
(title, body, args) ->
# TODO: add add classifications step
$rootScope.createModelWizard ?= $modal.open {
windowClass: 'create-model-wizard'
backdrop: 'static'
keyboard: false
size: 'lg'
resolve:
args: -> args
#language=HTML
template: '''
<div class="modal-header">
<button type="button" class="close" ng-click="dismiss()"><span aria-hidden="true">×</span><span class="sr-only">Cancel</span></button>
<h4>Model Wizard</span></h4>
<ul class="tutorial-steps">
<li>
<button id="step-previous" ng-disabled="step == 'model' || step == 'summary'" ng-click="previous()" class="btn btn-default"><span class="glyphicon glyphicon-chevron-left"></span></button>
</li>
<li>
<button id="step-model" ng-disabled="step == 'summary'" ng-click="select('model')" class="btn btn-default" ng-class="{'btn-primary': step == 'model'}">1. Model</button>
</li>
<li>
<button id="step-metadata" ng-disabled="!model.name || step == 'summary'" ng-click="select('metadata')" class="btn btn-default" ng-class="{'btn-primary': step == 'metadata', 'btn-info': step != 'metadata' && hasMetadata()}">2. Metadata</button>
</li>
<li>
<button id="step-parents" ng-disabled="!model.name || step == 'summary'" ng-click="select('parents')" class="btn btn-default" ng-class="{'btn-primary': step == 'parents', 'btn-info': step != 'parents' && parents.length > 0}">3. Parents</button>
</li>
<li>
<button id="step-children" ng-disabled="!model.name || step == 'summary'" ng-click="select('children')" class="btn btn-default" ng-class="{'btn-primary': step == 'children', 'btn-info': step != 'children' && children.length > 0}">4. Children</button>
</li>
<li>
<button id="step-elements" ng-disabled="!model.name || step == 'summary'" ng-click="select('elements')" class="btn btn-default" ng-class="{'btn-primary': step == 'elements', 'btn-info': step != 'elements' && dataElements.length > 0}">5. Elements</button>
</li>
<li>
<button id="step-classifications" ng-disabled="!model.name || step == 'summary'" ng-click="select('classifications')" class="btn btn-default" ng-class="{'btn-primary': step == 'classifications', 'btn-info': step != 'classifications' && classifications.length > 0}">6. Classifications</button>
</li>
<li>
<button id="step-next" ng-disabled="!model.name || step == 'classifications' || step == 'summary'" ng-click="next()" class="btn btn-default" ><span class="glyphicon glyphicon-chevron-right"></span></button>
</li>
<li>
<button id="step-finish" ng-disabled="!model.name || !isModelCatalogueIdValid()" ng-click="finish()" class="btn btn-default btn-success"><span class="glyphicon glyphicon-ok"></span></button>
</li>
</ul>
</div>
<div class="modal-body" ng-switch="step">
<div ng-switch-when="model" id="model">
<form role="form" ng-submit="select('metadata')">
<div class="form-group">
<label for="name" class="">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="Name (Required)" ng-model="model.<NAME>" focus-me="step=='model'" required>
<span class="input-group-btn">
<a class="btn btn-default" ng-click="prefillFrom()"><span class="fa fa-fw fa-copy"></span></a>
</span>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': !isModelCatalogueIdValid() }">
<label for="modelCatalogueId" class="">Catalogue ID (URL)</label>
<input type="text" class="form-control" id="modelCatalogueId" placeholder="e.g. external ID, namespace (leave blank for generated)" ng-model="model.modelCatalogueId">
</div>
<div class="form-group">
<label for="description" class="">Description</label>
<textarea rows="10" ng-model="model.description" placeholder="Description (Optional)" class="form-control" id="description" ng-keydown="navigateOnKey($event, 9, 'metadata')"></textarea>
</div>
</form>
</div>
<div ng-switch-when="metadata" id="metadata">
<form ng-submit="select('parents')">
<div>
<h4>Metadata</h4>
<ordered-map-editor title="Key" value-title="Value" object="metadata"></ordered-map-editor>
</div>
</form>
</div>
<div ng-switch-when="parents" id="parents">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Parent Model</label>
<elements-as-tags elements="parents"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="<NAME>" ng-model="parent.element" focus-me="step=='parents'" catalogue-element-picker="model" typeahead-on-select="push('parents', 'parent')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('parents', 'parent')" ng-disabled="isEmpty(parent.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Parent model is source for the hierarchy relationship</p>
</div>
<ordered-map-editor object="parent.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</div>
<div ng-switch-when="children" id="children">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Child Model</label>
<elements-as-tags elements="children"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="<NAME>" ng-model="child.element" focus-me="step=='children'" catalogue-element-picker="model" typeahead-on-select="push('children', 'child')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('children', 'child')" ng-disabled="isEmpty(child.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Child model is destination for the hierarchy relationship</p>
</div>
<div ng-click="importChildModelsFromCSV()">
<alert type="info">
<strong>Hint:</strong> If you have CSV file with sample data you can <a class="alert-link"><span class="fa fa-magic"></span> import child models from CSV file headers</a>.
</alert>
</div>
<ordered-map-editor object="child.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</div>
<div ng-switch-when="elements" id="elements">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Data Element</label>
<elements-as-tags elements="dataElements"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="<NAME>" ng-model="dataElement.element" focus-me="step=='elements'" catalogue-element-picker="dataElement" typeahead-on-select="push('dataElements', 'dataElement')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('dataElements', 'dataElement')" ng-disabled="isEmpty(dataElement.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Data element is destination for the containment relationship</p>
</div>
<div ng-click="importFromCSV()">
<alert type="info">
<strong>Hint:</strong> If you have CSV file with sample data you can <a class="alert-link"><span class="fa fa-magic"></span> import data elements from CSV file headers</a>.
</alert>
</div>
<ordered-map-editor object="dataElement.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</tab>
</div>
<div ng-switch-when="classifications" id="classifications">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Classifications</label>
<elements-as-tags elements="classifications"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="<NAME>" ng-model="classification.element" focus-me="step=='classifications'" catalogue-element-picker="classification" typeahead-on-select="push('classifications', 'classification')" status="draft">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('classifications', 'classification')" ng-disabled="isEmpty(classification.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
</div>
</form>
</tab>
</div>
<div ng-switch-when="summary" id="summary">
<h4 ng-show="model.name && !finished">Creating new model <strong>{{model.name}}</strong></h4>
<h4 ng-show="model.name && finished">Model <strong>{{model.name}} created</strong></h4>
<progressbar type="{{finished ? 'success' : 'primary'}}" value="pendingActionsCount == 0 ? 100 : Math.round(100 * (totalActions - pendingActionsCount) / totalActions)">{{totalActions - pendingActionsCount}} / {{totalActions}}</progressbar>
</div>
</div>
<div class="modal-footer" ng-if="step == 'summary'">
<button ng-disabled="!finished" class="btn btn-success" ng-click="reset()"><span class="glyphicon glyphicon-plus"></span> Create Another</button>
<button ng-disabled="!finished" class="btn btn-default" ng-click="$close(model)" id="exit-wizard"><span class="glyphicon glyphicon-remove"></span> Close</button>
</div>
'''
controller: ['$scope', '$state', '$window', 'messages', 'names', 'catalogueElementResource', '$modalInstance', '$timeout', 'args', 'delayedQueueExecutor', '$q', '$log', 'enhance', ($scope, $state, $window, messages, names, catalogueElementResource, $modalInstance, $timeout, args, delayedQueueExecutor, $q, $log, enhance) ->
execAfter50 = delayedQueueExecutor(500)
orderedMapEnhancer = enhance.getEnhancer('orderedMap')
$scope.reset = ->
$scope.args = args
$scope.model = {classifications: []}
$scope.metadata = orderedMapEnhancer.emptyOrderedMap()
$scope.parent = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.parents = []
$scope.child = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.children = []
$scope.dataElement = args.dataElement ? {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.dataElements = []
$scope.classification = {}
$scope.classifications = []
$scope.messages = messages.createNewMessages()
$scope.steps = ['model', 'metadata', 'parents', 'children', 'elements', 'classifications']
$scope.step = 'model'
$scope.pendingActions = []
$scope.pendingActionsCount = 0
$scope.totalActions = 0
$scope.finishInProgress = false
$scope.finished = false
$scope.parentsVisited = false
$scope.classificationsVisited = false
if args.parent
$scope.parents.push {element: args.parent, name: args.parent.name, metadata: orderedMapEnhancer.emptyOrderedMap()}
$scope.reset()
$scope.isEmpty = (object) ->
return true if not object
angular.equals object, {}
$scope.isString = (object) ->
angular.isString object
$scope.push = (arrayName, propertyName) ->
value = $scope[propertyName]
unless value
$log.warn "no scope value for #{propertyName}", $scope
return
if angular.isString value.element
value.name = value.element
value.create = true
else
value.name = value.element.name
$scope[arrayName].push value
$scope[propertyName] = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.openElementInNewWindow = (element) ->
url = $state.href('mc.resource.show', {resource: names.getPropertyNameFromType(element.elementType), id: element.id})
$window.open(url,'_blank')
$scope.finish = () ->
return if $scope.finishInProgress
$scope.finishInProgress = true
$scope.parents.push($scope.parent) if angular.isString($scope.parent?.element)
$scope.children.push($scope.child) if angular.isString($scope.child?.element)
$scope.dataElements.push($scope.dataElement) if angular.isString($scope.dataElement?.element)
$scope.classifications.push($scope.classification) if angular.isString($scope.classification?.element)
unless $scope.isEmpty($scope.metadata)
$scope.pendingActions.push (model)->
model.ext = $scope.metadata
execAfter50.submit -> catalogueElementResource('model').update(model)
angular.forEach $scope.parents, (parent) ->
if angular.isString parent.element
$scope.pendingActions.push (model) ->
catalogueElementResource("model").save({name: parent.element}).then (parentModel) ->
parent.element = parentModel
model
$scope.pendingActions.push (model) ->
parent.element.metadata = parent.ext
execAfter50.submit -> model.childOf.add parent.element
model
angular.forEach $scope.children, (child) ->
if angular.isString child.element
$scope.pendingActions.push (model) ->
catalogueElementResource("model").save({name: child.element}).then (childModel) ->
child.element = childModel
model
$scope.pendingActions.push (model) ->
child.element.metadata = child.ext
execAfter50.submit -> model.parentOf.add child.element
model
angular.forEach $scope.dataElements, (element) ->
if angular.isString element.element
$scope.pendingActions.push (model) ->
catalogueElementResource("dataElement").save({name: element.element}).then (newElement) ->
element.element = newElement
model
$scope.pendingActions.push (model) ->
element.element.metadata = element.ext
execAfter50.submit -> model.contains.add element.element
model
angular.forEach $scope.classifications, (classification) ->
if angular.isString classification.element
$scope.pendingActions.push (model) ->
catalogueElementResource('classification').save({name: classification.element}).then (newClassification) ->
model.classifications.push newClassification
execAfter50.submit -> catalogueElementResource('model').update(model)
else
$scope.pendingActions.push (model) ->
model.classifications.push classification.element
execAfter50.submit -> catalogueElementResource('model').update(model)
$scope.totalActions = $scope.pendingActionsCount = $scope.pendingActions.length + 1
$scope.step = 'summary'
decreasePendingActionsCount = (model) ->
$scope.pendingActionsCount--
# not very effective but otherwise lot of "entity updated by another transactions" occurs
model.refresh().then (fresh) ->
$timeout((-> fresh), 200)
promise = catalogueElementResource('model').save($scope.model).then decreasePendingActionsCount
for action in $scope.pendingActions
promise = promise.then(action).then decreasePendingActionsCount, (errorResponse) ->
if errorResponse.data.errors
for error in errorResponse.data.errors
messages.error(error.message)
else if errorResponse.data.error
messages.error(errorResponse.data.error)
else
messages.error('Unknown expection happened while creating new model. See application logs for details.')
$scope.finishInProgress = false
$q.reject errorResponse.data
promise.then (model) ->
messages.success "Model #{model.name} created"
$scope.finished = true
$scope.model = model
$scope.select = (step) ->
$scope.parentsVisited |= step == 'parents'
$scope.classificationsVisited |= step == 'classifications'
return if step != 'model' and not $scope.model.name
$scope.step = step
$scope.next = ->
return if not $scope.model.name
for step, i in $scope.steps
if step == $scope.step and i < $scope.steps.length - 1
nextStep = $scope.steps[i + 1]
if nextStep == 'summary'
$scope.finish()
else
$scope.step = nextStep
break
$scope.previous = ->
return if not $scope.model.name
for step, i in $scope.steps
if step == $scope.step and i != 0
$scope.step = $scope.steps[i - 1]
break
$scope.navigateOnKey = ($event, key, step) ->
$scope.select(step) if $event.keyCode == key
$scope.select('model')
$scope.importFromCSV = ->
messages.prompt("Import Data Elements", null, {type: 'data-element-suggestions-from-csv'}).then (result) ->
angular.forEach result, (element) ->
value = {element : element}
if angular.isString(value.element)
value = {name: value.element, create: true, element: value.element}
else
value.name = value.element.name
value.elementType = value.element.elementType
value.id = value.element.id
$scope.dataElements.push value
$scope.importChildModelsFromCSV = ->
messages.prompt("Import Child Models", null, {type: 'child-model-suggestions-from-csv'}).then (result) ->
angular.forEach result, (element) ->
value = {element : element}
if angular.isString(value.element)
value = {name: value.element, create: true, element: value.element}
else
value.name = value.element.name
value.elementType = value.element.elementType
value.id = value.element.id
$scope.children.push value
$scope.dismiss = (reason) ->
return $modalInstance.dismiss(reason) if $scope.finished
if $scope.model.name or $scope.model.description or not $scope.isEmpty($scope.metadata) or $scope.parents.length > 0 or $scope.children.length > 0 or $scope.dataElements.length > 0 or $scope.classifications.length > 0
messages.confirm("Close Model Wizard", "Do you want to discard all changes?").then ->
$modalInstance.dismiss(reason)
else
$modalInstance.dismiss(reason)
$scope.prefillFrom = ->
modelPromise = messages.prompt('Clone Model', 'Please, select from which Model should be the properties cloned', type: 'catalogue-element', resource: 'model')
modelPromise.then (model) ->
promises = []
$scope.model.name = model.name
$scope.model.description = model.description
$scope.metadata = angular.copy model.ext
angular.forEach model.classifications, (classification) ->
$scope.classifications.push {element: classification, name: classification.name}
push = (container, property) ->
(result) ->
angular.forEach result.list, (relation) ->
$scope[property] = element: relation.relation, ext: relation.ext
$scope.push container, property
$scope[property] = {ext: orderedMapEnhancer.emptyOrderedMap()}
promises.push model.parentOf(null, max: 100).then push('children', 'child')
promises.push model.contains(null, max: 100).then push('dataElements', 'dataElement')
$q.all promises
$scope.hasMetadata = ->
return $scope.metadata.values.length > 0 and $scope.metadata.values[0].key
$scope.isModelCatalogueIdValid = ->
return true if not $scope.model.modelCatalogueId
return new RegExp(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/).test($scope.model.modelCatalogueId)
]
}
$rootScope.createModelWizard.result.finally ->
$rootScope.createModelWizard = undefined
]
messagesProvider.setPromptFactory 'create-model', factory
] | true | angular.module('mc.core.ui.bs.modelWizard', ['mc.util.messages', 'mc.util.ui.focusMe']).config ['messagesProvider', (messagesProvider)->
factory = [ '$modal', '$q', 'messages', '$rootScope', ($modal, $q, messages,$rootScope) ->
(title, body, args) ->
# TODO: add add classifications step
$rootScope.createModelWizard ?= $modal.open {
windowClass: 'create-model-wizard'
backdrop: 'static'
keyboard: false
size: 'lg'
resolve:
args: -> args
#language=HTML
template: '''
<div class="modal-header">
<button type="button" class="close" ng-click="dismiss()"><span aria-hidden="true">×</span><span class="sr-only">Cancel</span></button>
<h4>Model Wizard</span></h4>
<ul class="tutorial-steps">
<li>
<button id="step-previous" ng-disabled="step == 'model' || step == 'summary'" ng-click="previous()" class="btn btn-default"><span class="glyphicon glyphicon-chevron-left"></span></button>
</li>
<li>
<button id="step-model" ng-disabled="step == 'summary'" ng-click="select('model')" class="btn btn-default" ng-class="{'btn-primary': step == 'model'}">1. Model</button>
</li>
<li>
<button id="step-metadata" ng-disabled="!model.name || step == 'summary'" ng-click="select('metadata')" class="btn btn-default" ng-class="{'btn-primary': step == 'metadata', 'btn-info': step != 'metadata' && hasMetadata()}">2. Metadata</button>
</li>
<li>
<button id="step-parents" ng-disabled="!model.name || step == 'summary'" ng-click="select('parents')" class="btn btn-default" ng-class="{'btn-primary': step == 'parents', 'btn-info': step != 'parents' && parents.length > 0}">3. Parents</button>
</li>
<li>
<button id="step-children" ng-disabled="!model.name || step == 'summary'" ng-click="select('children')" class="btn btn-default" ng-class="{'btn-primary': step == 'children', 'btn-info': step != 'children' && children.length > 0}">4. Children</button>
</li>
<li>
<button id="step-elements" ng-disabled="!model.name || step == 'summary'" ng-click="select('elements')" class="btn btn-default" ng-class="{'btn-primary': step == 'elements', 'btn-info': step != 'elements' && dataElements.length > 0}">5. Elements</button>
</li>
<li>
<button id="step-classifications" ng-disabled="!model.name || step == 'summary'" ng-click="select('classifications')" class="btn btn-default" ng-class="{'btn-primary': step == 'classifications', 'btn-info': step != 'classifications' && classifications.length > 0}">6. Classifications</button>
</li>
<li>
<button id="step-next" ng-disabled="!model.name || step == 'classifications' || step == 'summary'" ng-click="next()" class="btn btn-default" ><span class="glyphicon glyphicon-chevron-right"></span></button>
</li>
<li>
<button id="step-finish" ng-disabled="!model.name || !isModelCatalogueIdValid()" ng-click="finish()" class="btn btn-default btn-success"><span class="glyphicon glyphicon-ok"></span></button>
</li>
</ul>
</div>
<div class="modal-body" ng-switch="step">
<div ng-switch-when="model" id="model">
<form role="form" ng-submit="select('metadata')">
<div class="form-group">
<label for="name" class="">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="Name (Required)" ng-model="model.PI:NAME:<NAME>END_PI" focus-me="step=='model'" required>
<span class="input-group-btn">
<a class="btn btn-default" ng-click="prefillFrom()"><span class="fa fa-fw fa-copy"></span></a>
</span>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': !isModelCatalogueIdValid() }">
<label for="modelCatalogueId" class="">Catalogue ID (URL)</label>
<input type="text" class="form-control" id="modelCatalogueId" placeholder="e.g. external ID, namespace (leave blank for generated)" ng-model="model.modelCatalogueId">
</div>
<div class="form-group">
<label for="description" class="">Description</label>
<textarea rows="10" ng-model="model.description" placeholder="Description (Optional)" class="form-control" id="description" ng-keydown="navigateOnKey($event, 9, 'metadata')"></textarea>
</div>
</form>
</div>
<div ng-switch-when="metadata" id="metadata">
<form ng-submit="select('parents')">
<div>
<h4>Metadata</h4>
<ordered-map-editor title="Key" value-title="Value" object="metadata"></ordered-map-editor>
</div>
</form>
</div>
<div ng-switch-when="parents" id="parents">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Parent Model</label>
<elements-as-tags elements="parents"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="PI:NAME:<NAME>END_PI" ng-model="parent.element" focus-me="step=='parents'" catalogue-element-picker="model" typeahead-on-select="push('parents', 'parent')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('parents', 'parent')" ng-disabled="isEmpty(parent.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Parent model is source for the hierarchy relationship</p>
</div>
<ordered-map-editor object="parent.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</div>
<div ng-switch-when="children" id="children">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Child Model</label>
<elements-as-tags elements="children"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="PI:NAME:<NAME>END_PI" ng-model="child.element" focus-me="step=='children'" catalogue-element-picker="model" typeahead-on-select="push('children', 'child')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('children', 'child')" ng-disabled="isEmpty(child.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Child model is destination for the hierarchy relationship</p>
</div>
<div ng-click="importChildModelsFromCSV()">
<alert type="info">
<strong>Hint:</strong> If you have CSV file with sample data you can <a class="alert-link"><span class="fa fa-magic"></span> import child models from CSV file headers</a>.
</alert>
</div>
<ordered-map-editor object="child.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</div>
<div ng-switch-when="elements" id="elements">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Data Element</label>
<elements-as-tags elements="dataElements"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="PI:NAME:<NAME>END_PI" ng-model="dataElement.element" focus-me="step=='elements'" catalogue-element-picker="dataElement" typeahead-on-select="push('dataElements', 'dataElement')">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('dataElements', 'dataElement')" ng-disabled="isEmpty(dataElement.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<p class="help-block">Data element is destination for the containment relationship</p>
</div>
<div ng-click="importFromCSV()">
<alert type="info">
<strong>Hint:</strong> If you have CSV file with sample data you can <a class="alert-link"><span class="fa fa-magic"></span> import data elements from CSV file headers</a>.
</alert>
</div>
<ordered-map-editor object="dataElement.ext" title="Relationship Metadata" hints="['Min Occurs', 'Max Occurs']"></ordered-map-editor>
</form>
</tab>
</div>
<div ng-switch-when="classifications" id="classifications">
<br/>
<form role="form">
<div class="form-group">
<label for="name" class="">Classifications</label>
<elements-as-tags elements="classifications"></elements-as-tags>
<div class="input-group">
<input type="text" class="form-control" id="name" placeholder="PI:NAME:<NAME>END_PI" ng-model="classification.element" focus-me="step=='classifications'" catalogue-element-picker="classification" typeahead-on-select="push('classifications', 'classification')" status="draft">
<span class="input-group-btn">
<button class="btn btn-success" ng-click="push('classifications', 'classification')" ng-disabled="isEmpty(classification.element)"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
</div>
</form>
</tab>
</div>
<div ng-switch-when="summary" id="summary">
<h4 ng-show="model.name && !finished">Creating new model <strong>{{model.name}}</strong></h4>
<h4 ng-show="model.name && finished">Model <strong>{{model.name}} created</strong></h4>
<progressbar type="{{finished ? 'success' : 'primary'}}" value="pendingActionsCount == 0 ? 100 : Math.round(100 * (totalActions - pendingActionsCount) / totalActions)">{{totalActions - pendingActionsCount}} / {{totalActions}}</progressbar>
</div>
</div>
<div class="modal-footer" ng-if="step == 'summary'">
<button ng-disabled="!finished" class="btn btn-success" ng-click="reset()"><span class="glyphicon glyphicon-plus"></span> Create Another</button>
<button ng-disabled="!finished" class="btn btn-default" ng-click="$close(model)" id="exit-wizard"><span class="glyphicon glyphicon-remove"></span> Close</button>
</div>
'''
controller: ['$scope', '$state', '$window', 'messages', 'names', 'catalogueElementResource', '$modalInstance', '$timeout', 'args', 'delayedQueueExecutor', '$q', '$log', 'enhance', ($scope, $state, $window, messages, names, catalogueElementResource, $modalInstance, $timeout, args, delayedQueueExecutor, $q, $log, enhance) ->
execAfter50 = delayedQueueExecutor(500)
orderedMapEnhancer = enhance.getEnhancer('orderedMap')
$scope.reset = ->
$scope.args = args
$scope.model = {classifications: []}
$scope.metadata = orderedMapEnhancer.emptyOrderedMap()
$scope.parent = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.parents = []
$scope.child = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.children = []
$scope.dataElement = args.dataElement ? {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.dataElements = []
$scope.classification = {}
$scope.classifications = []
$scope.messages = messages.createNewMessages()
$scope.steps = ['model', 'metadata', 'parents', 'children', 'elements', 'classifications']
$scope.step = 'model'
$scope.pendingActions = []
$scope.pendingActionsCount = 0
$scope.totalActions = 0
$scope.finishInProgress = false
$scope.finished = false
$scope.parentsVisited = false
$scope.classificationsVisited = false
if args.parent
$scope.parents.push {element: args.parent, name: args.parent.name, metadata: orderedMapEnhancer.emptyOrderedMap()}
$scope.reset()
$scope.isEmpty = (object) ->
return true if not object
angular.equals object, {}
$scope.isString = (object) ->
angular.isString object
$scope.push = (arrayName, propertyName) ->
value = $scope[propertyName]
unless value
$log.warn "no scope value for #{propertyName}", $scope
return
if angular.isString value.element
value.name = value.element
value.create = true
else
value.name = value.element.name
$scope[arrayName].push value
$scope[propertyName] = {ext: orderedMapEnhancer.emptyOrderedMap()}
$scope.openElementInNewWindow = (element) ->
url = $state.href('mc.resource.show', {resource: names.getPropertyNameFromType(element.elementType), id: element.id})
$window.open(url,'_blank')
$scope.finish = () ->
return if $scope.finishInProgress
$scope.finishInProgress = true
$scope.parents.push($scope.parent) if angular.isString($scope.parent?.element)
$scope.children.push($scope.child) if angular.isString($scope.child?.element)
$scope.dataElements.push($scope.dataElement) if angular.isString($scope.dataElement?.element)
$scope.classifications.push($scope.classification) if angular.isString($scope.classification?.element)
unless $scope.isEmpty($scope.metadata)
$scope.pendingActions.push (model)->
model.ext = $scope.metadata
execAfter50.submit -> catalogueElementResource('model').update(model)
angular.forEach $scope.parents, (parent) ->
if angular.isString parent.element
$scope.pendingActions.push (model) ->
catalogueElementResource("model").save({name: parent.element}).then (parentModel) ->
parent.element = parentModel
model
$scope.pendingActions.push (model) ->
parent.element.metadata = parent.ext
execAfter50.submit -> model.childOf.add parent.element
model
angular.forEach $scope.children, (child) ->
if angular.isString child.element
$scope.pendingActions.push (model) ->
catalogueElementResource("model").save({name: child.element}).then (childModel) ->
child.element = childModel
model
$scope.pendingActions.push (model) ->
child.element.metadata = child.ext
execAfter50.submit -> model.parentOf.add child.element
model
angular.forEach $scope.dataElements, (element) ->
if angular.isString element.element
$scope.pendingActions.push (model) ->
catalogueElementResource("dataElement").save({name: element.element}).then (newElement) ->
element.element = newElement
model
$scope.pendingActions.push (model) ->
element.element.metadata = element.ext
execAfter50.submit -> model.contains.add element.element
model
angular.forEach $scope.classifications, (classification) ->
if angular.isString classification.element
$scope.pendingActions.push (model) ->
catalogueElementResource('classification').save({name: classification.element}).then (newClassification) ->
model.classifications.push newClassification
execAfter50.submit -> catalogueElementResource('model').update(model)
else
$scope.pendingActions.push (model) ->
model.classifications.push classification.element
execAfter50.submit -> catalogueElementResource('model').update(model)
$scope.totalActions = $scope.pendingActionsCount = $scope.pendingActions.length + 1
$scope.step = 'summary'
decreasePendingActionsCount = (model) ->
$scope.pendingActionsCount--
# not very effective but otherwise lot of "entity updated by another transactions" occurs
model.refresh().then (fresh) ->
$timeout((-> fresh), 200)
promise = catalogueElementResource('model').save($scope.model).then decreasePendingActionsCount
for action in $scope.pendingActions
promise = promise.then(action).then decreasePendingActionsCount, (errorResponse) ->
if errorResponse.data.errors
for error in errorResponse.data.errors
messages.error(error.message)
else if errorResponse.data.error
messages.error(errorResponse.data.error)
else
messages.error('Unknown expection happened while creating new model. See application logs for details.')
$scope.finishInProgress = false
$q.reject errorResponse.data
promise.then (model) ->
messages.success "Model #{model.name} created"
$scope.finished = true
$scope.model = model
$scope.select = (step) ->
$scope.parentsVisited |= step == 'parents'
$scope.classificationsVisited |= step == 'classifications'
return if step != 'model' and not $scope.model.name
$scope.step = step
$scope.next = ->
return if not $scope.model.name
for step, i in $scope.steps
if step == $scope.step and i < $scope.steps.length - 1
nextStep = $scope.steps[i + 1]
if nextStep == 'summary'
$scope.finish()
else
$scope.step = nextStep
break
$scope.previous = ->
return if not $scope.model.name
for step, i in $scope.steps
if step == $scope.step and i != 0
$scope.step = $scope.steps[i - 1]
break
$scope.navigateOnKey = ($event, key, step) ->
$scope.select(step) if $event.keyCode == key
$scope.select('model')
$scope.importFromCSV = ->
messages.prompt("Import Data Elements", null, {type: 'data-element-suggestions-from-csv'}).then (result) ->
angular.forEach result, (element) ->
value = {element : element}
if angular.isString(value.element)
value = {name: value.element, create: true, element: value.element}
else
value.name = value.element.name
value.elementType = value.element.elementType
value.id = value.element.id
$scope.dataElements.push value
$scope.importChildModelsFromCSV = ->
messages.prompt("Import Child Models", null, {type: 'child-model-suggestions-from-csv'}).then (result) ->
angular.forEach result, (element) ->
value = {element : element}
if angular.isString(value.element)
value = {name: value.element, create: true, element: value.element}
else
value.name = value.element.name
value.elementType = value.element.elementType
value.id = value.element.id
$scope.children.push value
$scope.dismiss = (reason) ->
return $modalInstance.dismiss(reason) if $scope.finished
if $scope.model.name or $scope.model.description or not $scope.isEmpty($scope.metadata) or $scope.parents.length > 0 or $scope.children.length > 0 or $scope.dataElements.length > 0 or $scope.classifications.length > 0
messages.confirm("Close Model Wizard", "Do you want to discard all changes?").then ->
$modalInstance.dismiss(reason)
else
$modalInstance.dismiss(reason)
$scope.prefillFrom = ->
modelPromise = messages.prompt('Clone Model', 'Please, select from which Model should be the properties cloned', type: 'catalogue-element', resource: 'model')
modelPromise.then (model) ->
promises = []
$scope.model.name = model.name
$scope.model.description = model.description
$scope.metadata = angular.copy model.ext
angular.forEach model.classifications, (classification) ->
$scope.classifications.push {element: classification, name: classification.name}
push = (container, property) ->
(result) ->
angular.forEach result.list, (relation) ->
$scope[property] = element: relation.relation, ext: relation.ext
$scope.push container, property
$scope[property] = {ext: orderedMapEnhancer.emptyOrderedMap()}
promises.push model.parentOf(null, max: 100).then push('children', 'child')
promises.push model.contains(null, max: 100).then push('dataElements', 'dataElement')
$q.all promises
$scope.hasMetadata = ->
return $scope.metadata.values.length > 0 and $scope.metadata.values[0].key
$scope.isModelCatalogueIdValid = ->
return true if not $scope.model.modelCatalogueId
return new RegExp(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/).test($scope.model.modelCatalogueId)
]
}
$rootScope.createModelWizard.result.finally ->
$rootScope.createModelWizard = undefined
]
messagesProvider.setPromptFactory 'create-model', factory
] |
[
{
"context": "r\"\n and: \"i\"\n back: \"enrere\"\n changePassword: \"Canviar contrassenya\"\n choosePassword: \"Escollir contrassenya\"\n clic",
"end": 128,
"score": 0.9985389709472656,
"start": 108,
"tag": "PASSWORD",
"value": "Canviar contrassenya"
},
{
"context": "ssword: \"... | t9n/ca.coffee | tnedich/meteor-accounts-t9n | 0 | #Language: Catalan
#Translators: ixdi
ca =
add: "afegir"
and: "i"
back: "enrere"
changePassword: "Canviar contrassenya"
choosePassword: "Escollir contrassenya"
clickAgree: "Al fer clic a Subscriure aproves la"
configure: "Disposició"
createAccount: "Crear compte"
currentPassword: "Contrassenya actual"
dontHaveAnAccount: "No tens un compte?"
email: "Correu"
emailAddress: "Adreça de correu"
emailResetLink: "Reiniciar correu"
forgotPassword: "Has oblidat la contrassenya?"
ifYouAlreadyHaveAnAccount: "Si ja tens un compte"
newPassword: "Nova contrassenya"
newPasswordAgain: "Nova contrassenya (repetir)"
optional: "Opcional"
OR: "O"
password: "Contrassenya"
passwordAgain: "Contrassenya (repetir)"
privacyPolicy: "Pòlissa de Privacitat"
remove: "eliminar"
resetYourPassword: "Resetejar la teva contrassenya"
setPassword: "Definir contrassenya"
sign: "Signar"
signIn: "Entrar"
signin: "entrar"
signOut: "Sortir"
signUp: "Subscriure"
signupCode: "Còdi de subscripció"
signUpWithYourEmailAddress: "Subscriure amb el teu correu"
terms: "Térmes d'ús"
updateYourPassword: "Actualitzar la teva contrassenya"
username: "Usuari"
usernameOrEmail: "Usuari o correu"
with: "amb"
info:
emailSent: "Correu enviat"
emailVerified: "Correu verificat"
passwordChanged: "Contrassenya canviada"
passwordReset: "Reiniciar contrassenya"
error:
emailRequired: "Es requereix el correu."
minChar: "7 caràcters mínim."
pwdsDontMatch: "Les contrassenyes no coincideixen"
pwOneDigit: "mínim un dígit."
pwOneLetter: "mínim una lletra."
signInRequired: "Has d'iniciar sessió per a fer això."
signupCodeIncorrect: "El còdi de subscripció no coincideix."
signupCodeRequired: "Es requereix el còdi de subscripció."
usernameIsEmail: "L'usuari no pot ser el correu."
usernameRequired: "Es requereix un usuari."
accounts:
#---- accounts-base
#"@" + domain + " email required":
#"A login handler should return a result or undefined":
"Email already exists.": "El correu ja existeix."
"Email doesn't match the criteria.": "El correu no coincideix amb els criteris."
#> "Invalid login token":
#> "Login forbidden":
#"Service " + options.service + " already configured":
#> "Service unknown":
#> "Unrecognized options for login request":
"User validation failed": "No s'ha pogut validar l'usuari"
"Username already exists.": "L'usuari ja existeix."
#> "You are not logged in.":
"You've been logged out by the server. Please log in again.": "Has estat desconnectat pel servidor. Si us plau, entra de nou."
"Your session has expired. Please log in again.": "La teva sessió ha expirat. Si us plau, entra de nou."
#---- accounts-oauth
#> "No matching login attempt found":
#---- accounts-password-client
#> "Password is old. Please reset your password.":
#---- accounts-password
"Incorrect password": "Contrassenya invàlida"
#> "Invalid email":
"Must be logged in": "Has d'entrar"
"Need to set a username or email": "Has d'especificar un usuari o un correu"
#> "old password format":
#> "Password may not be empty":
"Signups forbidden": "Registre prohibit"
"Token expired": "Token expirat"
"Token has invalid email address": "Token conté un correu invàlid"
"User has no password set": "Usuario no té contrassenya"
"User not found": "Usuari no trobat"
"Verify email link expired": "L'enllaç per verificar el correu ha expirat"
"Verify email link is for unknown address": "L'enllaç per verificar el correu conté una adreça desconeguda"
#---- match
#> "Match failed":
#---- Misc...
#> "Unknown error":
T9n.map "ca", ca
| 109827 | #Language: Catalan
#Translators: ixdi
ca =
add: "afegir"
and: "i"
back: "enrere"
changePassword: "<PASSWORD>"
choosePassword: "<PASSWORD>"
clickAgree: "Al fer clic a Subscriure aproves la"
configure: "Disposició"
createAccount: "Crear compte"
currentPassword: "<PASSWORD>"
dontHaveAnAccount: "No tens un compte?"
email: "Correu"
emailAddress: "Adreça de correu"
emailResetLink: "Reiniciar correu"
forgotPassword: "<PASSWORD>?"
ifYouAlreadyHaveAnAccount: "Si ja tens un compte"
newPassword: "<PASSWORD>"
newPasswordAgain: "<PASSWORD> (repetir)"
optional: "Opcional"
OR: "O"
password: "<PASSWORD>"
passwordAgain: "<PASSWORD> (repetir)"
privacyPolicy: "Pòlissa de Privacitat"
remove: "eliminar"
resetYourPassword: "<PASSWORD>"
setPassword: "<PASSWORD>"
sign: "Signar"
signIn: "Entrar"
signin: "entrar"
signOut: "Sortir"
signUp: "Subscriure"
signupCode: "Còdi de subscripció"
signUpWithYourEmailAddress: "Subscriure amb el teu correu"
terms: "Térmes d'ús"
updateYourPassword: "<PASSWORD>"
username: "Usuari"
usernameOrEmail: "Usuari o correu"
with: "amb"
info:
emailSent: "Correu enviat"
emailVerified: "Correu verificat"
passwordChanged: "<PASSWORD>"
passwordReset: "<PASSWORD>"
error:
emailRequired: "Es requereix el correu."
minChar: "7 caràcters mínim."
pwdsDontMatch: "Les contrassenyes no coincideixen"
pwOneDigit: "mínim un dígit."
pwOneLetter: "mínim una lletra."
signInRequired: "Has d'iniciar sessió per a fer això."
signupCodeIncorrect: "El còdi de subscripció no coincideix."
signupCodeRequired: "Es requereix el còdi de subscripció."
usernameIsEmail: "L'usuari no pot ser el correu."
usernameRequired: "Es requereix un usuari."
accounts:
#---- accounts-base
#"@" + domain + " email required":
#"A login handler should return a result or undefined":
"Email already exists.": "El correu ja existeix."
"Email doesn't match the criteria.": "El correu no coincideix amb els criteris."
#> "Invalid login token":
#> "Login forbidden":
#"Service " + options.service + " already configured":
#> "Service unknown":
#> "Unrecognized options for login request":
"User validation failed": "No s'ha pogut validar l'usuari"
"Username already exists.": "L'usuari ja existeix."
#> "You are not logged in.":
"You've been logged out by the server. Please log in again.": "Has estat desconnectat pel servidor. Si us plau, entra de nou."
"Your session has expired. Please log in again.": "La teva sessió ha expirat. Si us plau, entra de nou."
#---- accounts-oauth
#> "No matching login attempt found":
#---- accounts-password-client
#> "Password is old. Please reset your password.":
#---- accounts-password
"Incorrect password": "<PASSWORD>"
#> "Invalid email":
"Must be logged in": "Has d'entrar"
"Need to set a username or email": "Has d'especificar un usuari o un correu"
#> "old password format":
#> "Password may not be empty":
"Signups forbidden": "Registre prohibit"
"Token expired": "Token expirat"
"Token has invalid email address": "Token conté un correu invàlid"
"User has no password set": "Usuario no té contrassenya"
"User not found": "Usuari no trobat"
"Verify email link expired": "L'enllaç per verificar el correu ha expirat"
"Verify email link is for unknown address": "L'enllaç per verificar el correu conté una adreça desconeguda"
#---- match
#> "Match failed":
#---- Misc...
#> "Unknown error":
T9n.map "ca", ca
| true | #Language: Catalan
#Translators: ixdi
ca =
add: "afegir"
and: "i"
back: "enrere"
changePassword: "PI:PASSWORD:<PASSWORD>END_PI"
choosePassword: "PI:PASSWORD:<PASSWORD>END_PI"
clickAgree: "Al fer clic a Subscriure aproves la"
configure: "Disposició"
createAccount: "Crear compte"
currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
dontHaveAnAccount: "No tens un compte?"
email: "Correu"
emailAddress: "Adreça de correu"
emailResetLink: "Reiniciar correu"
forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI?"
ifYouAlreadyHaveAnAccount: "Si ja tens un compte"
newPassword: "PI:PASSWORD:<PASSWORD>END_PI"
newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI (repetir)"
optional: "Opcional"
OR: "O"
password: "PI:PASSWORD:<PASSWORD>END_PI"
passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI (repetir)"
privacyPolicy: "Pòlissa de Privacitat"
remove: "eliminar"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
setPassword: "PI:PASSWORD:<PASSWORD>END_PI"
sign: "Signar"
signIn: "Entrar"
signin: "entrar"
signOut: "Sortir"
signUp: "Subscriure"
signupCode: "Còdi de subscripció"
signUpWithYourEmailAddress: "Subscriure amb el teu correu"
terms: "Térmes d'ús"
updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
username: "Usuari"
usernameOrEmail: "Usuari o correu"
with: "amb"
info:
emailSent: "Correu enviat"
emailVerified: "Correu verificat"
passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI"
passwordReset: "PI:PASSWORD:<PASSWORD>END_PI"
error:
emailRequired: "Es requereix el correu."
minChar: "7 caràcters mínim."
pwdsDontMatch: "Les contrassenyes no coincideixen"
pwOneDigit: "mínim un dígit."
pwOneLetter: "mínim una lletra."
signInRequired: "Has d'iniciar sessió per a fer això."
signupCodeIncorrect: "El còdi de subscripció no coincideix."
signupCodeRequired: "Es requereix el còdi de subscripció."
usernameIsEmail: "L'usuari no pot ser el correu."
usernameRequired: "Es requereix un usuari."
accounts:
#---- accounts-base
#"@" + domain + " email required":
#"A login handler should return a result or undefined":
"Email already exists.": "El correu ja existeix."
"Email doesn't match the criteria.": "El correu no coincideix amb els criteris."
#> "Invalid login token":
#> "Login forbidden":
#"Service " + options.service + " already configured":
#> "Service unknown":
#> "Unrecognized options for login request":
"User validation failed": "No s'ha pogut validar l'usuari"
"Username already exists.": "L'usuari ja existeix."
#> "You are not logged in.":
"You've been logged out by the server. Please log in again.": "Has estat desconnectat pel servidor. Si us plau, entra de nou."
"Your session has expired. Please log in again.": "La teva sessió ha expirat. Si us plau, entra de nou."
#---- accounts-oauth
#> "No matching login attempt found":
#---- accounts-password-client
#> "Password is old. Please reset your password.":
#---- accounts-password
"Incorrect password": "PI:PASSWORD:<PASSWORD>END_PI"
#> "Invalid email":
"Must be logged in": "Has d'entrar"
"Need to set a username or email": "Has d'especificar un usuari o un correu"
#> "old password format":
#> "Password may not be empty":
"Signups forbidden": "Registre prohibit"
"Token expired": "Token expirat"
"Token has invalid email address": "Token conté un correu invàlid"
"User has no password set": "Usuario no té contrassenya"
"User not found": "Usuari no trobat"
"Verify email link expired": "L'enllaç per verificar el correu ha expirat"
"Verify email link is for unknown address": "L'enllaç per verificar el correu conté una adreça desconeguda"
#---- match
#> "Match failed":
#---- Misc...
#> "Unknown error":
T9n.map "ca", ca
|
[
{
"context": "ld.equal 'bar'\n '''\n\nmySpec = new Spec \n name: 'assignment test'\n specDSL: code\n isCoffee: true\n\n#>> Then\n\nmySp",
"end": 302,
"score": 0.7650010585784912,
"start": 287,
"tag": "NAME",
"value": "assignment test"
}
] | domain/specifications/services/specs/runSpec.spec.coffee | wearefractal/spex | 0 | #>> Setup
require 'should'
Spec = require '../../models/Spec'
runSpec = require '../runSpec'
#>> Given a Spec
code =
'''
#>> Given foo
foo = 'foo'
#>> When I change the value of foo
foo = 'bar'
#>> Then
foo.should.equal 'bar'
'''
mySpec = new Spec
name: 'assignment test'
specDSL: code
isCoffee: true
#>> Then
mySpec.status.should.equal 'notrun'
#>> When I run the spec
runSpec mySpec, (err, spec) ->
#>> Then
spec.status.should.equal 'pass'
| 202556 | #>> Setup
require 'should'
Spec = require '../../models/Spec'
runSpec = require '../runSpec'
#>> Given a Spec
code =
'''
#>> Given foo
foo = 'foo'
#>> When I change the value of foo
foo = 'bar'
#>> Then
foo.should.equal 'bar'
'''
mySpec = new Spec
name: '<NAME>'
specDSL: code
isCoffee: true
#>> Then
mySpec.status.should.equal 'notrun'
#>> When I run the spec
runSpec mySpec, (err, spec) ->
#>> Then
spec.status.should.equal 'pass'
| true | #>> Setup
require 'should'
Spec = require '../../models/Spec'
runSpec = require '../runSpec'
#>> Given a Spec
code =
'''
#>> Given foo
foo = 'foo'
#>> When I change the value of foo
foo = 'bar'
#>> Then
foo.should.equal 'bar'
'''
mySpec = new Spec
name: 'PI:NAME:<NAME>END_PI'
specDSL: code
isCoffee: true
#>> Then
mySpec.status.should.equal 'notrun'
#>> When I run the spec
runSpec mySpec, (err, spec) ->
#>> Then
spec.status.should.equal 'pass'
|
[
{
"context": " service = @repository.replace('/', '-')\n key = \"/vulcand/backends/#{service}/servers\"\n etcdManager = new EtcdManager ETCDCTL_PEERS:",
"end": 3877,
"score": 0.98345947265625,
"start": 3840,
"tag": "KEY",
"value": "\"/vulcand/backends/#{service}/servers"
}
] | src/status-model.coffee | octoblu/deployinate-service | 1 | _ = require 'lodash'
url = require 'url'
async = require 'async'
request = require 'request'
EtcdManager = require './etcd-manager'
EtcdParserModel = require './etcd-parser-model'
debug = require('debug')('deployinate-service:status-model')
class StatusModel
constructor: (options) ->
{@repository} = options
{@GOVERNATOR_MAJOR_URL, @GOVERNATOR_MINOR_URL} = options
{@ETCD_MAJOR_URI, @ETCD_MINOR_URI} = options
{@QUAY_URL, @QUAY_TOKEN} = options
throw new Error('repository is required') unless @repository?
throw new Error('ETCD_MAJOR_URI is required') unless @ETCD_MAJOR_URI?
throw new Error('ETCD_MINOR_URI is required') unless @ETCD_MINOR_URI?
throw new Error('GOVERNATOR_MAJOR_URL is required') unless @GOVERNATOR_MAJOR_URL?
throw new Error('GOVERNATOR_MINOR_URL is required') unless @GOVERNATOR_MINOR_URL?
throw new Error('QUAY_URL is required') unless @QUAY_URL?
throw new Error('QUAY_TOKEN is required') unless @QUAY_TOKEN?
get: (callback) =>
async.parallel {
majorVersion: @_getMajorVersion
minorVersion: @_getMinorVersion
status: @_getStatus
deployments: @_getGovernatorMajor
servers: @_getVulcandBackend
quay: @_getQuayStatus
}, callback
getV2: (callback) =>
async.parallel {
majorVersion: @_getMajorVersion
minorVersion: @_getMinorVersion
status: @_getStatus
deployments: @_getGovernatorMajor
servers: @_getVulcandBackendWithVersions
quay: @_getQuayStatus
}, callback
_getStatus: (callback) =>
@_getEtcd @ETCD_MAJOR_URI, "/#{@repository}/status", callback
_getQuayStatus: (callback) =>
options =
uri: "/api/v1/repository/#{@repository}/build/"
baseUrl: @QUAY_URL
json: true
auth:
bearer: @QUAY_TOKEN
request.get options, (error, response) =>
return callback error if error?
unless response.statusCode == 200
error = new Error("Expected to get a 200, got an #{response.statusCode}. host: #{@QUAY_URL}")
error.code = response.code
return callback error
return callback null, {} if _.isEmpty response.body?.builds
quayBuild = _.first response.body.builds
build =
tag: _.first quayBuild.tags
phase: quayBuild.phase
startedAt: quayBuild.started
callback null, build
_getMajorVersion: (callback) =>
@_getEtcd @ETCD_MAJOR_URI, "/#{@repository}/docker_url", (error, data) =>
return callback error if error?
callback null, _.first _.values data
_getMinorVersion: (callback) =>
@_getEtcd @ETCD_MINOR_URI, "/#{@repository}/docker_url", (error, data) =>
return callback error if error?
callback null, _.first _.values data
_getEtcd: (uri, key, callback) =>
debug 'getEtcd', uri, key
etcdManager = new EtcdManager ETCDCTL_PEERS: uri
etcd = etcdManager.getEtcd()
etcd.get key, recursive: true, (error, keys) =>
return callback null, {} if error?.errorCode == 100
return callback error if error?
return callback new Error(keys) unless _.isPlainObject(keys)
etcdParser = new EtcdParserModel key, keys
etcdParser.parse callback
_getServerVersion: (server, callback) =>
options = {
baseUrl: server.url
uri: '/version'
json: true
}
request.get options, (error, response, body) =>
return callback null, _.assign(version: error.message, server) if error?
if response.statusCode != 200
return callback null, _.assign(version: "(HTTP: #{response.statusCode})", server)
return callback null, _.assign(version: "v#{body.version}", server)
_getVulcandBackend: (callback) =>
debug 'getVulcandBackend', @repository
service = @repository.replace('/', '-')
key = "/vulcand/backends/#{service}/servers"
etcdManager = new EtcdManager ETCDCTL_PEERS: @ETCD_MAJOR_URI
etcd = etcdManager.getEtcd()
etcd.get key, recursive: true, (error, keys) =>
return callback null, {error: error.message} if error?
return callback null, {error: keys} unless _.isPlainObject(keys)
@etcdParser = new EtcdParserModel key, keys
servers = {}
@etcdParser.parse (error, data) =>
return callback error if error?
_.each _.keys(data), (key) =>
try
node = JSON.parse data[key]
servers[node.Id] = node.URL
catch error
callback null, servers
_getVulcandBackendWithVersions: (callback) =>
@_getVulcandBackend (error, serverMap) =>
return callback error if error?
servers = _.map serverMap, (url, name) => {url, name}
async.map servers, @_getServerVersion, callback
_getGovernatorMajor: (callback) =>
options =
uri: "/status"
baseUrl: @GOVERNATOR_MAJOR_URL
json: true
request.get options, (error, response) =>
return callback error if error?
unless response.statusCode == 200
host = 'unknown'
try
{host} = url.parse(@GOVERNATOR_MAJOR_URL)
error = new Error("Expected to get a 200, got an #{response.statusCode}. host: #{host}")
error.code = response.code
return callback error
deploys = _.pick response.body, (value, key) =>
_.startsWith key, "governator:/#{@repository}:"
callback null, deploys
module.exports = StatusModel
| 161143 | _ = require 'lodash'
url = require 'url'
async = require 'async'
request = require 'request'
EtcdManager = require './etcd-manager'
EtcdParserModel = require './etcd-parser-model'
debug = require('debug')('deployinate-service:status-model')
class StatusModel
constructor: (options) ->
{@repository} = options
{@GOVERNATOR_MAJOR_URL, @GOVERNATOR_MINOR_URL} = options
{@ETCD_MAJOR_URI, @ETCD_MINOR_URI} = options
{@QUAY_URL, @QUAY_TOKEN} = options
throw new Error('repository is required') unless @repository?
throw new Error('ETCD_MAJOR_URI is required') unless @ETCD_MAJOR_URI?
throw new Error('ETCD_MINOR_URI is required') unless @ETCD_MINOR_URI?
throw new Error('GOVERNATOR_MAJOR_URL is required') unless @GOVERNATOR_MAJOR_URL?
throw new Error('GOVERNATOR_MINOR_URL is required') unless @GOVERNATOR_MINOR_URL?
throw new Error('QUAY_URL is required') unless @QUAY_URL?
throw new Error('QUAY_TOKEN is required') unless @QUAY_TOKEN?
get: (callback) =>
async.parallel {
majorVersion: @_getMajorVersion
minorVersion: @_getMinorVersion
status: @_getStatus
deployments: @_getGovernatorMajor
servers: @_getVulcandBackend
quay: @_getQuayStatus
}, callback
getV2: (callback) =>
async.parallel {
majorVersion: @_getMajorVersion
minorVersion: @_getMinorVersion
status: @_getStatus
deployments: @_getGovernatorMajor
servers: @_getVulcandBackendWithVersions
quay: @_getQuayStatus
}, callback
_getStatus: (callback) =>
@_getEtcd @ETCD_MAJOR_URI, "/#{@repository}/status", callback
_getQuayStatus: (callback) =>
options =
uri: "/api/v1/repository/#{@repository}/build/"
baseUrl: @QUAY_URL
json: true
auth:
bearer: @QUAY_TOKEN
request.get options, (error, response) =>
return callback error if error?
unless response.statusCode == 200
error = new Error("Expected to get a 200, got an #{response.statusCode}. host: #{@QUAY_URL}")
error.code = response.code
return callback error
return callback null, {} if _.isEmpty response.body?.builds
quayBuild = _.first response.body.builds
build =
tag: _.first quayBuild.tags
phase: quayBuild.phase
startedAt: quayBuild.started
callback null, build
_getMajorVersion: (callback) =>
@_getEtcd @ETCD_MAJOR_URI, "/#{@repository}/docker_url", (error, data) =>
return callback error if error?
callback null, _.first _.values data
_getMinorVersion: (callback) =>
@_getEtcd @ETCD_MINOR_URI, "/#{@repository}/docker_url", (error, data) =>
return callback error if error?
callback null, _.first _.values data
_getEtcd: (uri, key, callback) =>
debug 'getEtcd', uri, key
etcdManager = new EtcdManager ETCDCTL_PEERS: uri
etcd = etcdManager.getEtcd()
etcd.get key, recursive: true, (error, keys) =>
return callback null, {} if error?.errorCode == 100
return callback error if error?
return callback new Error(keys) unless _.isPlainObject(keys)
etcdParser = new EtcdParserModel key, keys
etcdParser.parse callback
_getServerVersion: (server, callback) =>
options = {
baseUrl: server.url
uri: '/version'
json: true
}
request.get options, (error, response, body) =>
return callback null, _.assign(version: error.message, server) if error?
if response.statusCode != 200
return callback null, _.assign(version: "(HTTP: #{response.statusCode})", server)
return callback null, _.assign(version: "v#{body.version}", server)
_getVulcandBackend: (callback) =>
debug 'getVulcandBackend', @repository
service = @repository.replace('/', '-')
key = <KEY>"
etcdManager = new EtcdManager ETCDCTL_PEERS: @ETCD_MAJOR_URI
etcd = etcdManager.getEtcd()
etcd.get key, recursive: true, (error, keys) =>
return callback null, {error: error.message} if error?
return callback null, {error: keys} unless _.isPlainObject(keys)
@etcdParser = new EtcdParserModel key, keys
servers = {}
@etcdParser.parse (error, data) =>
return callback error if error?
_.each _.keys(data), (key) =>
try
node = JSON.parse data[key]
servers[node.Id] = node.URL
catch error
callback null, servers
_getVulcandBackendWithVersions: (callback) =>
@_getVulcandBackend (error, serverMap) =>
return callback error if error?
servers = _.map serverMap, (url, name) => {url, name}
async.map servers, @_getServerVersion, callback
_getGovernatorMajor: (callback) =>
options =
uri: "/status"
baseUrl: @GOVERNATOR_MAJOR_URL
json: true
request.get options, (error, response) =>
return callback error if error?
unless response.statusCode == 200
host = 'unknown'
try
{host} = url.parse(@GOVERNATOR_MAJOR_URL)
error = new Error("Expected to get a 200, got an #{response.statusCode}. host: #{host}")
error.code = response.code
return callback error
deploys = _.pick response.body, (value, key) =>
_.startsWith key, "governator:/#{@repository}:"
callback null, deploys
module.exports = StatusModel
| true | _ = require 'lodash'
url = require 'url'
async = require 'async'
request = require 'request'
EtcdManager = require './etcd-manager'
EtcdParserModel = require './etcd-parser-model'
debug = require('debug')('deployinate-service:status-model')
class StatusModel
constructor: (options) ->
{@repository} = options
{@GOVERNATOR_MAJOR_URL, @GOVERNATOR_MINOR_URL} = options
{@ETCD_MAJOR_URI, @ETCD_MINOR_URI} = options
{@QUAY_URL, @QUAY_TOKEN} = options
throw new Error('repository is required') unless @repository?
throw new Error('ETCD_MAJOR_URI is required') unless @ETCD_MAJOR_URI?
throw new Error('ETCD_MINOR_URI is required') unless @ETCD_MINOR_URI?
throw new Error('GOVERNATOR_MAJOR_URL is required') unless @GOVERNATOR_MAJOR_URL?
throw new Error('GOVERNATOR_MINOR_URL is required') unless @GOVERNATOR_MINOR_URL?
throw new Error('QUAY_URL is required') unless @QUAY_URL?
throw new Error('QUAY_TOKEN is required') unless @QUAY_TOKEN?
get: (callback) =>
async.parallel {
majorVersion: @_getMajorVersion
minorVersion: @_getMinorVersion
status: @_getStatus
deployments: @_getGovernatorMajor
servers: @_getVulcandBackend
quay: @_getQuayStatus
}, callback
getV2: (callback) =>
async.parallel {
majorVersion: @_getMajorVersion
minorVersion: @_getMinorVersion
status: @_getStatus
deployments: @_getGovernatorMajor
servers: @_getVulcandBackendWithVersions
quay: @_getQuayStatus
}, callback
_getStatus: (callback) =>
@_getEtcd @ETCD_MAJOR_URI, "/#{@repository}/status", callback
_getQuayStatus: (callback) =>
options =
uri: "/api/v1/repository/#{@repository}/build/"
baseUrl: @QUAY_URL
json: true
auth:
bearer: @QUAY_TOKEN
request.get options, (error, response) =>
return callback error if error?
unless response.statusCode == 200
error = new Error("Expected to get a 200, got an #{response.statusCode}. host: #{@QUAY_URL}")
error.code = response.code
return callback error
return callback null, {} if _.isEmpty response.body?.builds
quayBuild = _.first response.body.builds
build =
tag: _.first quayBuild.tags
phase: quayBuild.phase
startedAt: quayBuild.started
callback null, build
_getMajorVersion: (callback) =>
@_getEtcd @ETCD_MAJOR_URI, "/#{@repository}/docker_url", (error, data) =>
return callback error if error?
callback null, _.first _.values data
_getMinorVersion: (callback) =>
@_getEtcd @ETCD_MINOR_URI, "/#{@repository}/docker_url", (error, data) =>
return callback error if error?
callback null, _.first _.values data
_getEtcd: (uri, key, callback) =>
debug 'getEtcd', uri, key
etcdManager = new EtcdManager ETCDCTL_PEERS: uri
etcd = etcdManager.getEtcd()
etcd.get key, recursive: true, (error, keys) =>
return callback null, {} if error?.errorCode == 100
return callback error if error?
return callback new Error(keys) unless _.isPlainObject(keys)
etcdParser = new EtcdParserModel key, keys
etcdParser.parse callback
_getServerVersion: (server, callback) =>
options = {
baseUrl: server.url
uri: '/version'
json: true
}
request.get options, (error, response, body) =>
return callback null, _.assign(version: error.message, server) if error?
if response.statusCode != 200
return callback null, _.assign(version: "(HTTP: #{response.statusCode})", server)
return callback null, _.assign(version: "v#{body.version}", server)
_getVulcandBackend: (callback) =>
debug 'getVulcandBackend', @repository
service = @repository.replace('/', '-')
key = PI:KEY:<KEY>END_PI"
etcdManager = new EtcdManager ETCDCTL_PEERS: @ETCD_MAJOR_URI
etcd = etcdManager.getEtcd()
etcd.get key, recursive: true, (error, keys) =>
return callback null, {error: error.message} if error?
return callback null, {error: keys} unless _.isPlainObject(keys)
@etcdParser = new EtcdParserModel key, keys
servers = {}
@etcdParser.parse (error, data) =>
return callback error if error?
_.each _.keys(data), (key) =>
try
node = JSON.parse data[key]
servers[node.Id] = node.URL
catch error
callback null, servers
_getVulcandBackendWithVersions: (callback) =>
@_getVulcandBackend (error, serverMap) =>
return callback error if error?
servers = _.map serverMap, (url, name) => {url, name}
async.map servers, @_getServerVersion, callback
_getGovernatorMajor: (callback) =>
options =
uri: "/status"
baseUrl: @GOVERNATOR_MAJOR_URL
json: true
request.get options, (error, response) =>
return callback error if error?
unless response.statusCode == 200
host = 'unknown'
try
{host} = url.parse(@GOVERNATOR_MAJOR_URL)
error = new Error("Expected to get a 200, got an #{response.statusCode}. host: #{host}")
error.code = response.code
return callback error
deploys = _.pick response.body, (value, key) =>
_.startsWith key, "governator:/#{@repository}:"
callback null, deploys
module.exports = StatusModel
|
[
{
"context": "aaa'\n expect(result).to.be.empty\n\n it 'returns Carlton, VIC when search for postcode 3053', ->\n r",
"end": 462,
"score": 0.6706900000572205,
"start": 459,
"tag": "NAME",
"value": "Car"
},
{
"context": "e.lengthOf 1\n expect(result[0].name).to.equal 'Carlto... | test/api.coffee | nqngo/weather-au-api | 2 | # Run `yarn run cake build` to build api.js
# `yarn run cake test` to run this test
chai = require 'chai'
chai.use require 'chai-datetime'
expect = chai.expect
Api = require '../api.js'
api = new Api
now = Date.now()
describe 'Api', ->
it 'returns nothing when search for invalid string', ->
result = await api.search 'a'
expect(result).to.be.empty
result = await api.search 'aaaaaaaaaaaaaaaaa'
expect(result).to.be.empty
it 'returns Carlton, VIC when search for postcode 3053', ->
result = await api.search '3053'
expect(result).to.have.lengthOf 1
expect(result[0].name).to.equal 'Carlton'
expect(result[0].state).to.equal 'VIC'
it 'returns postcode 3053 when search for Carlton+VIC', ->
result = await api.search 'Carlton+VIC'
# Because Carlton returns multiple results
# filter to find if a result contain the Carlton
carlton = result.filter (r) ->
r.name is 'Carlton' and r.state is 'VIC' and r.postcode is '3053'
expect(carlton).to.have.lengthOf 1
it 'shows Carlton today 3-hourly forecasts', ->
result = await api.forecasts_3hourly()
for trihour in result
expect(trihour).to.include.all.keys 'rain', 'temp', 'wind', 'is_night'
it 'shows Carlton daily forecasts for the next 7 days', ->
result = await api.forecasts_daily()
expect(result).to.have.lengthOf.at.least 7
# Set today to midnight
today = new Date()
today.setHours 0,0,0,0
# Test membership for each result
for day in result
expect(day).to.include.all.keys 'rain', 'uv', 'astronomical', 'temp_max',
'temp_min', 'extended_text'
it 'gets weather warnings for Carlton if there is any', ->
result = await api.warnings()
expect(api.response_timestamp()).to.be.not.empty
it 'get the warning with ID VIC_RC022_IDV36310', ->
result = await api.warning 'VIC_RC022_IDV36310'
expect(result.id).to.equal 'VIC_RC022_IDV36310'
expect(result.title).to.equal 'Flood Warning for Yarra River'
expect(result.type).to.equal 'flood_warning'
it 'get the nearest observation reading from Carlton', ->
result = await api.observations()
expect(result.station.name).to.equal 'Melbourne (Olympic Park)'
expect(result.station.bom_id).to.equal '086338'
| 5568 | # Run `yarn run cake build` to build api.js
# `yarn run cake test` to run this test
chai = require 'chai'
chai.use require 'chai-datetime'
expect = chai.expect
Api = require '../api.js'
api = new Api
now = Date.now()
describe 'Api', ->
it 'returns nothing when search for invalid string', ->
result = await api.search 'a'
expect(result).to.be.empty
result = await api.search 'aaaaaaaaaaaaaaaaa'
expect(result).to.be.empty
it 'returns <NAME>lton, VIC when search for postcode 3053', ->
result = await api.search '3053'
expect(result).to.have.lengthOf 1
expect(result[0].name).to.equal '<NAME>'
expect(result[0].state).to.equal 'VIC'
it 'returns postcode 3053 when search for Carlton+VIC', ->
result = await api.search 'Car<NAME>ton+VIC'
# Because Carlton returns multiple results
# filter to find if a result contain the Carlton
carlton = result.filter (r) ->
r.name is '<NAME>' and r.state is 'VIC' and r.postcode is '3053'
expect(carlton).to.have.lengthOf 1
it 'shows Carlton today 3-hourly forecasts', ->
result = await api.forecasts_3hourly()
for trihour in result
expect(trihour).to.include.all.keys 'rain', 'temp', 'wind', 'is_night'
it 'shows Carlton daily forecasts for the next 7 days', ->
result = await api.forecasts_daily()
expect(result).to.have.lengthOf.at.least 7
# Set today to midnight
today = new Date()
today.setHours 0,0,0,0
# Test membership for each result
for day in result
expect(day).to.include.all.keys 'rain', 'uv', 'astronomical', 'temp_max',
'temp_min', 'extended_text'
it 'gets weather warnings for Carlton if there is any', ->
result = await api.warnings()
expect(api.response_timestamp()).to.be.not.empty
it 'get the warning with ID VIC_RC022_IDV36310', ->
result = await api.warning 'VIC_RC022_IDV36310'
expect(result.id).to.equal 'VIC_RC022_IDV36310'
expect(result.title).to.equal 'Flood Warning for Yarra River'
expect(result.type).to.equal 'flood_warning'
it 'get the nearest observation reading from Carlton', ->
result = await api.observations()
expect(result.station.name).to.equal 'Melbourne (Olympic Park)'
expect(result.station.bom_id).to.equal '086338'
| true | # Run `yarn run cake build` to build api.js
# `yarn run cake test` to run this test
chai = require 'chai'
chai.use require 'chai-datetime'
expect = chai.expect
Api = require '../api.js'
api = new Api
now = Date.now()
describe 'Api', ->
it 'returns nothing when search for invalid string', ->
result = await api.search 'a'
expect(result).to.be.empty
result = await api.search 'aaaaaaaaaaaaaaaaa'
expect(result).to.be.empty
it 'returns PI:NAME:<NAME>END_PIlton, VIC when search for postcode 3053', ->
result = await api.search '3053'
expect(result).to.have.lengthOf 1
expect(result[0].name).to.equal 'PI:NAME:<NAME>END_PI'
expect(result[0].state).to.equal 'VIC'
it 'returns postcode 3053 when search for Carlton+VIC', ->
result = await api.search 'CarPI:NAME:<NAME>END_PIton+VIC'
# Because Carlton returns multiple results
# filter to find if a result contain the Carlton
carlton = result.filter (r) ->
r.name is 'PI:NAME:<NAME>END_PI' and r.state is 'VIC' and r.postcode is '3053'
expect(carlton).to.have.lengthOf 1
it 'shows Carlton today 3-hourly forecasts', ->
result = await api.forecasts_3hourly()
for trihour in result
expect(trihour).to.include.all.keys 'rain', 'temp', 'wind', 'is_night'
it 'shows Carlton daily forecasts for the next 7 days', ->
result = await api.forecasts_daily()
expect(result).to.have.lengthOf.at.least 7
# Set today to midnight
today = new Date()
today.setHours 0,0,0,0
# Test membership for each result
for day in result
expect(day).to.include.all.keys 'rain', 'uv', 'astronomical', 'temp_max',
'temp_min', 'extended_text'
it 'gets weather warnings for Carlton if there is any', ->
result = await api.warnings()
expect(api.response_timestamp()).to.be.not.empty
it 'get the warning with ID VIC_RC022_IDV36310', ->
result = await api.warning 'VIC_RC022_IDV36310'
expect(result.id).to.equal 'VIC_RC022_IDV36310'
expect(result.title).to.equal 'Flood Warning for Yarra River'
expect(result.type).to.equal 'flood_warning'
it 'get the nearest observation reading from Carlton', ->
result = await api.observations()
expect(result.station.name).to.equal 'Melbourne (Olympic Park)'
expect(result.station.bom_id).to.equal '086338'
|
[
{
"context": "fix classes with js-\n\n defaults:\n csrfToken: \"csrf_token\",\n target: \"#post_url\"\n\n constructor: (el, op",
"end": 143,
"score": 0.8815522789955139,
"start": 133,
"tag": "PASSWORD",
"value": "csrf_token"
}
] | spirit/static/spirit/scripts/move_comments.coffee | rterehov/Spirit | 1 | ###
Move comments to other topic
###
$ = jQuery
class MoveComment
#TODO: prefix classes with js-
defaults:
csrfToken: "csrf_token",
target: "#post_url"
constructor: (el, options) ->
@el = $(el)
@options = $.extend {}, @defaults, options
do @setUp
setUp: ->
@el.on 'click', @showMoveComments
@el.on 'click', @stopClick
# TODO: this should probably be moved from
# here to its own class, since it gets
# called for every el. Since we have only
# one "move comments" link, it's ok for now.
$move_comments = $(".js-move-comments")
$move_comments.on 'click', @moveComments
$move_comments.on 'click', @stopClick
showMoveComments: =>
if $(".move-comments").is ":hidden"
do $(".move-comments").show
do @addCommentSelection
return
addCommentSelection: =>
$li = $("<li/>").appendTo ".comment-date"
$checkbox = $("<input/>", {
class: "move-comment-checkbox",
name: "comments",
type: "checkbox",
value: ""
}).appendTo $li
# add comment_id to every checkbox value
$checkbox.each ->
$commentId = $(@).closest(".comment").data "pk"
$(@).val $commentId
moveComments: =>
$form = $("<form/>", {
action: @options.target,
method: "post"
}).hide().appendTo $('body')
# inputCsrfToken
$("<input/>", {
name: "csrfmiddlewaretoken",
type: "hidden",
value: @options.csrfToken
}).appendTo $form
# inputTopicId
topicId = $("#id_move_comments_topic").val()
$("<input/>", {
name: "topic",
type: "text",
value: topicId
}).appendTo $form
# append all selection inputs
$(".move-comment-checkbox").clone().appendTo $form
@formSubmit $form
return
formSubmit: ($form) ->
do $form.submit
stopClick: (e) ->
do e.preventDefault
do e.stopPropagation
return
$.fn.extend
move_comments: (options) ->
@each ->
if not $(@).data 'plugin_move_comments'
$(@).data 'plugin_move_comments', new MoveComment(@, options)
$.fn.move_comments.MoveComment = MoveComment | 22349 | ###
Move comments to other topic
###
$ = jQuery
class MoveComment
#TODO: prefix classes with js-
defaults:
csrfToken: "<PASSWORD>",
target: "#post_url"
constructor: (el, options) ->
@el = $(el)
@options = $.extend {}, @defaults, options
do @setUp
setUp: ->
@el.on 'click', @showMoveComments
@el.on 'click', @stopClick
# TODO: this should probably be moved from
# here to its own class, since it gets
# called for every el. Since we have only
# one "move comments" link, it's ok for now.
$move_comments = $(".js-move-comments")
$move_comments.on 'click', @moveComments
$move_comments.on 'click', @stopClick
showMoveComments: =>
if $(".move-comments").is ":hidden"
do $(".move-comments").show
do @addCommentSelection
return
addCommentSelection: =>
$li = $("<li/>").appendTo ".comment-date"
$checkbox = $("<input/>", {
class: "move-comment-checkbox",
name: "comments",
type: "checkbox",
value: ""
}).appendTo $li
# add comment_id to every checkbox value
$checkbox.each ->
$commentId = $(@).closest(".comment").data "pk"
$(@).val $commentId
moveComments: =>
$form = $("<form/>", {
action: @options.target,
method: "post"
}).hide().appendTo $('body')
# inputCsrfToken
$("<input/>", {
name: "csrfmiddlewaretoken",
type: "hidden",
value: @options.csrfToken
}).appendTo $form
# inputTopicId
topicId = $("#id_move_comments_topic").val()
$("<input/>", {
name: "topic",
type: "text",
value: topicId
}).appendTo $form
# append all selection inputs
$(".move-comment-checkbox").clone().appendTo $form
@formSubmit $form
return
formSubmit: ($form) ->
do $form.submit
stopClick: (e) ->
do e.preventDefault
do e.stopPropagation
return
$.fn.extend
move_comments: (options) ->
@each ->
if not $(@).data 'plugin_move_comments'
$(@).data 'plugin_move_comments', new MoveComment(@, options)
$.fn.move_comments.MoveComment = MoveComment | true | ###
Move comments to other topic
###
$ = jQuery
class MoveComment
#TODO: prefix classes with js-
defaults:
csrfToken: "PI:PASSWORD:<PASSWORD>END_PI",
target: "#post_url"
constructor: (el, options) ->
@el = $(el)
@options = $.extend {}, @defaults, options
do @setUp
setUp: ->
@el.on 'click', @showMoveComments
@el.on 'click', @stopClick
# TODO: this should probably be moved from
# here to its own class, since it gets
# called for every el. Since we have only
# one "move comments" link, it's ok for now.
$move_comments = $(".js-move-comments")
$move_comments.on 'click', @moveComments
$move_comments.on 'click', @stopClick
showMoveComments: =>
if $(".move-comments").is ":hidden"
do $(".move-comments").show
do @addCommentSelection
return
addCommentSelection: =>
$li = $("<li/>").appendTo ".comment-date"
$checkbox = $("<input/>", {
class: "move-comment-checkbox",
name: "comments",
type: "checkbox",
value: ""
}).appendTo $li
# add comment_id to every checkbox value
$checkbox.each ->
$commentId = $(@).closest(".comment").data "pk"
$(@).val $commentId
moveComments: =>
$form = $("<form/>", {
action: @options.target,
method: "post"
}).hide().appendTo $('body')
# inputCsrfToken
$("<input/>", {
name: "csrfmiddlewaretoken",
type: "hidden",
value: @options.csrfToken
}).appendTo $form
# inputTopicId
topicId = $("#id_move_comments_topic").val()
$("<input/>", {
name: "topic",
type: "text",
value: topicId
}).appendTo $form
# append all selection inputs
$(".move-comment-checkbox").clone().appendTo $form
@formSubmit $form
return
formSubmit: ($form) ->
do $form.submit
stopClick: (e) ->
do e.preventDefault
do e.stopPropagation
return
$.fn.extend
move_comments: (options) ->
@each ->
if not $(@).data 'plugin_move_comments'
$(@).data 'plugin_move_comments', new MoveComment(@, options)
$.fn.move_comments.MoveComment = MoveComment |
[
{
"context": "he: (alpha_s, idx, vdata) ->\n cache_key = [ alpha_s, idx, JSON.stringify(vdata) ].join('#')\n if @v_cache.",
"end": 9776,
"score": 0.9073193669319153,
"start": 9758,
"tag": "KEY",
"value": "alpha_s, idx, JSON"
},
{
"context": "data) ->\n cache_key ... | coffee/bloodyroots.coffee | squarooticus/bloodyroots | 1 | re_quote = require('regexp-quote')
inspect_orig = require('util').inspect
inspect = (x) -> inspect_orig(x, false, null)
require('sprintf.js')
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
class Parser
@define_production: (alpha_s, beta) ->
@prototype[alpha_s] = (vdata, idx) ->
beta.op.call this, vdata, idx
@define_grammar_operation: (name, op_f) ->
this[name] = (args...) ->
{ name: name, op: if op_f? then op_f.apply this, args else this['match_' + name].apply this, args }
@define_grammar_operation 'at_least_one', (beta, suffix) -> @match_range(beta, 1, undefined, true, suffix)
@define_grammar_operation 'alternation'
@define_grammar_operation 'range'
@define_grammar_operation 're', (re_str, match_name) -> @match_re(RegExp('^(?:' + re_str + ')'), match_name)
@define_grammar_operation 'seq'
@define_grammar_operation 'transform', (f, beta) -> @op_transform(f, beta)
@define_grammar_operation 'v'
@define_grammar_operation 'var_re'
@define_grammar_operation 'zero_or_more', (beta, suffix) -> @match_range(beta, 0, undefined, true, suffix)
@define_grammar_operation 'zero_or_one', (beta, suffix) -> @match_range(beta, 0, 1, true, suffix)
@backref: (ref) -> (vdata) ->
m = /^([^\[]*)\[([0-9]*)\]/.exec(ref)
[ (vdata[m[1]] || [ ])[m[2]], ]
debug_log: (f) ->
if @constructor.debug
[ name, idx, outcome, data ] = f.call(this)
'%-15s %3s %-25s %-8s %s\n'.printf name, idx, @string_abbrev(idx, 25), outcome || '', data || ''
@match_alternation: (args...) ->
if typeIsArray args[0]
[ beta_seq, suffix ] = args
else
beta_seq = args
(vdata, idx) ->
@debug_log -> [ 'alternation', idx, 'begin', 'alternation=%s%s'.sprintf (beta.name for beta in beta_seq), (if suffix? then ' suffix='+suffix.name else ' no-suffix') ]
i = 0
for beta in beta_seq
@debug_log -> [ 'alternation', idx, 'i='+i, beta.name ]
m = beta.op.call this, vdata, idx
if m?
if suffix?
m2 = suffix.op.call this, vdata, idx + m[0]
if m2?
@debug_log -> [ 'alternation', idx + m[0] + m2[0], 'success', 'count='+(i+1) ]
return [ m[0] + m2[0], { pos: idx, length: m[0] + m2[0], type: 'seq', seq: [ m[1], m2[1] ] } ]
else
@debug_log -> [ 'alternation', idx + m[0], 'success', 'count=%d'.sprintf (i+1) ]
return m
i++
@debug_log -> [ 'alternation', idx, 'fail' ]
return
@match_range: (beta, min=0, max, greedy=true, suffix) ->
if greedy
@_match_greedy_range(beta, min, max, suffix)
else
@_match_nongreedy_range(beta, min, max, suffix)
@_match_greedy_range: (beta, min, max, suffix) -> (vdata, idx) ->
return unless state = @_match_range_to_min(beta, min, max, true, vdata, idx)
match_indices = [ state.progress ]
@_match_range_from_min beta, max, vdata, idx, state, =>
match_indices.push(state.progress)
false
while match_indices.length
state.progress = match_indices.pop()
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count, 'greedy backtracking' ]
return result if result = @_match_range_suffix(suffix, vdata, idx, state)
state.work.pop()
state.count--
@debug_log -> [ 'range', idx + state.progress, 'fail', 'greedy backtracking' ]
return
@_match_nongreedy_range: (beta, min, max, suffix) -> (vdata, idx) ->
return unless state = @_match_range_to_min(beta, min, max, false, vdata, idx)
@_match_range_suffix(suffix, vdata, idx, state) or @_match_range_from_min(beta, max, vdata, idx, state, =>
@_match_range_suffix(suffix, vdata, idx, state)
) or (@debug_log( -> [ 'range', idx + state.progress, 'fail', '>=min non-greedy' ]); undefined)
_match_range_to_min: (beta, min, max, greedy, vdata, idx) ->
@debug_log -> [ 'range', idx, 'begin',
'%s min=%s max=%s %s %s'.sprintf(beta.name, min, (if max? then max else ''),
(if greedy then 'greedy' else 'non-greedy'),
(if suffix? then 'suffix='+suffix.name else 'no-suffix')) ]
if max? and min > max
@debug_log -> [ 're', idx, 'fail', 'min > max' ]
return
state = { count: 0, progress: 0, work: [], greedy: greedy }
while state.count < min
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count, '<min' ]
m = beta.op.call this, vdata, idx + state.progress
unless m?
@debug_log -> [ 'range', idx + state.progress, 'fail', '<min matches' ]
return
state.progress += m[0]
state.work.push m[1]
state.count++
state
_match_range_from_min: (beta, max, vdata, idx, state, func) ->
while not max? or state.count < max
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count,
'>=min %s'.sprintf(if state.greedy then 'greedy' else 'non-greedy') ]
m = beta.op.call this, vdata, idx + state.progress
break unless m?
state.progress += m[0]
state.work.push m[1]
state.count++
if output = func()
return output
return
_match_range_suffix: (suffix, vdata, idx, state) ->
if suffix?
if (m = suffix.op.call this, vdata, idx + state.progress)?
state.progress += m[0]
state.work.push m[1]
@debug_log -> [ 'range', idx + state.progress, 'success',
'count=%d %s'.sprintf(state.count, (if state.greedy then 'greedy' else 'non-greedy')) ]
return [ state.progress, { pos: idx, length: state.progress, type: 'seq', seq: state.work } ]
else
return
else
@debug_log -> [ 'range', idx + state.progress, 'success',
'count=%d %s'.sprintf(state.count, (if state.greedy then 'greedy' else 'non-greedy trivial')) ]
return [ state.progress, { pos: idx, length: state.progress, type: 'seq', seq: state.work } ]
@match_re: (rre, match_name) -> (vdata, idx) ->
m = rre.exec @str.substr idx
if m
@debug_log -> [ 're', idx, 'success', @strip_quotes inspect rre.source ]
vdata[match_name] = m[0..-1] if match_name?
[ m[0].length, { pos: idx, length: m[0].length, type: 're', match: m[0], groups: m[0..-1] } ]
else
@debug_log -> [ 're', idx, 'fail', @strip_quotes inspect rre.source ]
return
@match_seq: (beta_seq...) ->
(vdata, idx) ->
@debug_log -> [ 'seq', idx, 'begin', (beta.name for beta in beta_seq) ]
progress = 0
work = [ ]
i = 0
for beta in beta_seq
@debug_log -> [ 'seq', idx + progress, 'i='+i, beta.name ]
m = beta.op.call this, vdata, idx + progress
unless m?
@debug_log -> [ 'seq', idx + progress, 'fail' ]
return
progress += m[0]
work.push m[1]
i++
@debug_log -> [ 'seq', idx + progress, 'success' ]
[ progress, { pos: idx, length: progress, type: 'seq', seq: work } ]
@match_v: (alpha_s, argf) -> (vdata, idx) ->
@debug_log -> [ 'v', idx, 'begin', alpha_s ]
new_vdata = { }
new_vdata.arg = argf.call this, vdata if argf?
m = @vcache(alpha_s, idx, new_vdata)
@debug_log -> [ 'v', idx + (if m? then m[0] else 0), (if m? then 'success' else 'fail'), alpha_s ]
m
@match_var_re: (re_str, match_name) ->
self = this
(vdata, idx) ->
self.match_re(RegExp('^(?:' + @replace_backreferences(re_str, vdata) + ')'), match_name).call this, vdata, idx
@op_transform: (f, beta) -> (vdata, idx) ->
@debug_log -> [ 'transform', idx, 'begin', beta.name ]
m = beta.op.call this, vdata, idx
unless m?
@debug_log -> [ 'transform', idx, 'fail', beta.name ]
return
tm = f.call this, m[1], vdata, idx
unless tm?
@debug_log -> [ 'transform', idx + m[0], 'fail', 'transform' ]
return
@debug_log -> [ 'transform', idx + m[0], 'success' ]
[ m[0], tm ]
parse: (str) ->
@str = str
@v_cache = {}
@debug_log -> [ 'parse', 0, 'begin' ]
doc = @Document { }, 0
unless doc?
@debug_log -> [ 'parse', 0, 'fail' ]
return
@debug_log -> [ 'parse', doc[0], 'success' ]
doc[1]
replace_backreferences: (re_str, vdata) ->
work = re_str
while m = (/\\=([^\[]+)\[([0-9]+)\]/.exec(work))
mstr = (vdata[m[1]] || [ ])[m[2]]
mstr ?= ''
work = work.substr(0, m.index) + re_quote(mstr) + work.substr(m.index + m[0].length)
work
string_abbrev: (start, n) ->
istr = @str.substr(start)
istr = @strip_quotes inspect istr
if istr.length > n
istr.substr(0, n - 3) + '...'
else
istr
strip_quotes: (str) ->
m = /^'(.*)'$/.exec(str)
if m
m[1]
else
str
vcache: (alpha_s, idx, vdata) ->
cache_key = [ alpha_s, idx, JSON.stringify(vdata) ].join('#')
if @v_cache.hasOwnProperty(cache_key)
@debug_log -> [ 'vcache', idx, 'cached' ]
return @v_cache[cache_key]
else
@v_cache[cache_key] = this[alpha_s] vdata, idx
exports.Parser = Parser
| 65782 | re_quote = require('regexp-quote')
inspect_orig = require('util').inspect
inspect = (x) -> inspect_orig(x, false, null)
require('sprintf.js')
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
class Parser
@define_production: (alpha_s, beta) ->
@prototype[alpha_s] = (vdata, idx) ->
beta.op.call this, vdata, idx
@define_grammar_operation: (name, op_f) ->
this[name] = (args...) ->
{ name: name, op: if op_f? then op_f.apply this, args else this['match_' + name].apply this, args }
@define_grammar_operation 'at_least_one', (beta, suffix) -> @match_range(beta, 1, undefined, true, suffix)
@define_grammar_operation 'alternation'
@define_grammar_operation 'range'
@define_grammar_operation 're', (re_str, match_name) -> @match_re(RegExp('^(?:' + re_str + ')'), match_name)
@define_grammar_operation 'seq'
@define_grammar_operation 'transform', (f, beta) -> @op_transform(f, beta)
@define_grammar_operation 'v'
@define_grammar_operation 'var_re'
@define_grammar_operation 'zero_or_more', (beta, suffix) -> @match_range(beta, 0, undefined, true, suffix)
@define_grammar_operation 'zero_or_one', (beta, suffix) -> @match_range(beta, 0, 1, true, suffix)
@backref: (ref) -> (vdata) ->
m = /^([^\[]*)\[([0-9]*)\]/.exec(ref)
[ (vdata[m[1]] || [ ])[m[2]], ]
debug_log: (f) ->
if @constructor.debug
[ name, idx, outcome, data ] = f.call(this)
'%-15s %3s %-25s %-8s %s\n'.printf name, idx, @string_abbrev(idx, 25), outcome || '', data || ''
@match_alternation: (args...) ->
if typeIsArray args[0]
[ beta_seq, suffix ] = args
else
beta_seq = args
(vdata, idx) ->
@debug_log -> [ 'alternation', idx, 'begin', 'alternation=%s%s'.sprintf (beta.name for beta in beta_seq), (if suffix? then ' suffix='+suffix.name else ' no-suffix') ]
i = 0
for beta in beta_seq
@debug_log -> [ 'alternation', idx, 'i='+i, beta.name ]
m = beta.op.call this, vdata, idx
if m?
if suffix?
m2 = suffix.op.call this, vdata, idx + m[0]
if m2?
@debug_log -> [ 'alternation', idx + m[0] + m2[0], 'success', 'count='+(i+1) ]
return [ m[0] + m2[0], { pos: idx, length: m[0] + m2[0], type: 'seq', seq: [ m[1], m2[1] ] } ]
else
@debug_log -> [ 'alternation', idx + m[0], 'success', 'count=%d'.sprintf (i+1) ]
return m
i++
@debug_log -> [ 'alternation', idx, 'fail' ]
return
@match_range: (beta, min=0, max, greedy=true, suffix) ->
if greedy
@_match_greedy_range(beta, min, max, suffix)
else
@_match_nongreedy_range(beta, min, max, suffix)
@_match_greedy_range: (beta, min, max, suffix) -> (vdata, idx) ->
return unless state = @_match_range_to_min(beta, min, max, true, vdata, idx)
match_indices = [ state.progress ]
@_match_range_from_min beta, max, vdata, idx, state, =>
match_indices.push(state.progress)
false
while match_indices.length
state.progress = match_indices.pop()
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count, 'greedy backtracking' ]
return result if result = @_match_range_suffix(suffix, vdata, idx, state)
state.work.pop()
state.count--
@debug_log -> [ 'range', idx + state.progress, 'fail', 'greedy backtracking' ]
return
@_match_nongreedy_range: (beta, min, max, suffix) -> (vdata, idx) ->
return unless state = @_match_range_to_min(beta, min, max, false, vdata, idx)
@_match_range_suffix(suffix, vdata, idx, state) or @_match_range_from_min(beta, max, vdata, idx, state, =>
@_match_range_suffix(suffix, vdata, idx, state)
) or (@debug_log( -> [ 'range', idx + state.progress, 'fail', '>=min non-greedy' ]); undefined)
_match_range_to_min: (beta, min, max, greedy, vdata, idx) ->
@debug_log -> [ 'range', idx, 'begin',
'%s min=%s max=%s %s %s'.sprintf(beta.name, min, (if max? then max else ''),
(if greedy then 'greedy' else 'non-greedy'),
(if suffix? then 'suffix='+suffix.name else 'no-suffix')) ]
if max? and min > max
@debug_log -> [ 're', idx, 'fail', 'min > max' ]
return
state = { count: 0, progress: 0, work: [], greedy: greedy }
while state.count < min
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count, '<min' ]
m = beta.op.call this, vdata, idx + state.progress
unless m?
@debug_log -> [ 'range', idx + state.progress, 'fail', '<min matches' ]
return
state.progress += m[0]
state.work.push m[1]
state.count++
state
_match_range_from_min: (beta, max, vdata, idx, state, func) ->
while not max? or state.count < max
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count,
'>=min %s'.sprintf(if state.greedy then 'greedy' else 'non-greedy') ]
m = beta.op.call this, vdata, idx + state.progress
break unless m?
state.progress += m[0]
state.work.push m[1]
state.count++
if output = func()
return output
return
_match_range_suffix: (suffix, vdata, idx, state) ->
if suffix?
if (m = suffix.op.call this, vdata, idx + state.progress)?
state.progress += m[0]
state.work.push m[1]
@debug_log -> [ 'range', idx + state.progress, 'success',
'count=%d %s'.sprintf(state.count, (if state.greedy then 'greedy' else 'non-greedy')) ]
return [ state.progress, { pos: idx, length: state.progress, type: 'seq', seq: state.work } ]
else
return
else
@debug_log -> [ 'range', idx + state.progress, 'success',
'count=%d %s'.sprintf(state.count, (if state.greedy then 'greedy' else 'non-greedy trivial')) ]
return [ state.progress, { pos: idx, length: state.progress, type: 'seq', seq: state.work } ]
@match_re: (rre, match_name) -> (vdata, idx) ->
m = rre.exec @str.substr idx
if m
@debug_log -> [ 're', idx, 'success', @strip_quotes inspect rre.source ]
vdata[match_name] = m[0..-1] if match_name?
[ m[0].length, { pos: idx, length: m[0].length, type: 're', match: m[0], groups: m[0..-1] } ]
else
@debug_log -> [ 're', idx, 'fail', @strip_quotes inspect rre.source ]
return
@match_seq: (beta_seq...) ->
(vdata, idx) ->
@debug_log -> [ 'seq', idx, 'begin', (beta.name for beta in beta_seq) ]
progress = 0
work = [ ]
i = 0
for beta in beta_seq
@debug_log -> [ 'seq', idx + progress, 'i='+i, beta.name ]
m = beta.op.call this, vdata, idx + progress
unless m?
@debug_log -> [ 'seq', idx + progress, 'fail' ]
return
progress += m[0]
work.push m[1]
i++
@debug_log -> [ 'seq', idx + progress, 'success' ]
[ progress, { pos: idx, length: progress, type: 'seq', seq: work } ]
@match_v: (alpha_s, argf) -> (vdata, idx) ->
@debug_log -> [ 'v', idx, 'begin', alpha_s ]
new_vdata = { }
new_vdata.arg = argf.call this, vdata if argf?
m = @vcache(alpha_s, idx, new_vdata)
@debug_log -> [ 'v', idx + (if m? then m[0] else 0), (if m? then 'success' else 'fail'), alpha_s ]
m
@match_var_re: (re_str, match_name) ->
self = this
(vdata, idx) ->
self.match_re(RegExp('^(?:' + @replace_backreferences(re_str, vdata) + ')'), match_name).call this, vdata, idx
@op_transform: (f, beta) -> (vdata, idx) ->
@debug_log -> [ 'transform', idx, 'begin', beta.name ]
m = beta.op.call this, vdata, idx
unless m?
@debug_log -> [ 'transform', idx, 'fail', beta.name ]
return
tm = f.call this, m[1], vdata, idx
unless tm?
@debug_log -> [ 'transform', idx + m[0], 'fail', 'transform' ]
return
@debug_log -> [ 'transform', idx + m[0], 'success' ]
[ m[0], tm ]
parse: (str) ->
@str = str
@v_cache = {}
@debug_log -> [ 'parse', 0, 'begin' ]
doc = @Document { }, 0
unless doc?
@debug_log -> [ 'parse', 0, 'fail' ]
return
@debug_log -> [ 'parse', doc[0], 'success' ]
doc[1]
replace_backreferences: (re_str, vdata) ->
work = re_str
while m = (/\\=([^\[]+)\[([0-9]+)\]/.exec(work))
mstr = (vdata[m[1]] || [ ])[m[2]]
mstr ?= ''
work = work.substr(0, m.index) + re_quote(mstr) + work.substr(m.index + m[0].length)
work
string_abbrev: (start, n) ->
istr = @str.substr(start)
istr = @strip_quotes inspect istr
if istr.length > n
istr.substr(0, n - 3) + '...'
else
istr
strip_quotes: (str) ->
m = /^'(.*)'$/.exec(str)
if m
m[1]
else
str
vcache: (alpha_s, idx, vdata) ->
cache_key = [ <KEY>.<KEY>v<KEY>
if @v_cache.hasOwnProperty(cache_key)
@debug_log -> [ 'vcache', idx, 'cached' ]
return @v_cache[cache_key]
else
@v_cache[cache_key] = this[alpha_s] vdata, idx
exports.Parser = Parser
| true | re_quote = require('regexp-quote')
inspect_orig = require('util').inspect
inspect = (x) -> inspect_orig(x, false, null)
require('sprintf.js')
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
class Parser
@define_production: (alpha_s, beta) ->
@prototype[alpha_s] = (vdata, idx) ->
beta.op.call this, vdata, idx
@define_grammar_operation: (name, op_f) ->
this[name] = (args...) ->
{ name: name, op: if op_f? then op_f.apply this, args else this['match_' + name].apply this, args }
@define_grammar_operation 'at_least_one', (beta, suffix) -> @match_range(beta, 1, undefined, true, suffix)
@define_grammar_operation 'alternation'
@define_grammar_operation 'range'
@define_grammar_operation 're', (re_str, match_name) -> @match_re(RegExp('^(?:' + re_str + ')'), match_name)
@define_grammar_operation 'seq'
@define_grammar_operation 'transform', (f, beta) -> @op_transform(f, beta)
@define_grammar_operation 'v'
@define_grammar_operation 'var_re'
@define_grammar_operation 'zero_or_more', (beta, suffix) -> @match_range(beta, 0, undefined, true, suffix)
@define_grammar_operation 'zero_or_one', (beta, suffix) -> @match_range(beta, 0, 1, true, suffix)
@backref: (ref) -> (vdata) ->
m = /^([^\[]*)\[([0-9]*)\]/.exec(ref)
[ (vdata[m[1]] || [ ])[m[2]], ]
debug_log: (f) ->
if @constructor.debug
[ name, idx, outcome, data ] = f.call(this)
'%-15s %3s %-25s %-8s %s\n'.printf name, idx, @string_abbrev(idx, 25), outcome || '', data || ''
@match_alternation: (args...) ->
if typeIsArray args[0]
[ beta_seq, suffix ] = args
else
beta_seq = args
(vdata, idx) ->
@debug_log -> [ 'alternation', idx, 'begin', 'alternation=%s%s'.sprintf (beta.name for beta in beta_seq), (if suffix? then ' suffix='+suffix.name else ' no-suffix') ]
i = 0
for beta in beta_seq
@debug_log -> [ 'alternation', idx, 'i='+i, beta.name ]
m = beta.op.call this, vdata, idx
if m?
if suffix?
m2 = suffix.op.call this, vdata, idx + m[0]
if m2?
@debug_log -> [ 'alternation', idx + m[0] + m2[0], 'success', 'count='+(i+1) ]
return [ m[0] + m2[0], { pos: idx, length: m[0] + m2[0], type: 'seq', seq: [ m[1], m2[1] ] } ]
else
@debug_log -> [ 'alternation', idx + m[0], 'success', 'count=%d'.sprintf (i+1) ]
return m
i++
@debug_log -> [ 'alternation', idx, 'fail' ]
return
@match_range: (beta, min=0, max, greedy=true, suffix) ->
if greedy
@_match_greedy_range(beta, min, max, suffix)
else
@_match_nongreedy_range(beta, min, max, suffix)
@_match_greedy_range: (beta, min, max, suffix) -> (vdata, idx) ->
return unless state = @_match_range_to_min(beta, min, max, true, vdata, idx)
match_indices = [ state.progress ]
@_match_range_from_min beta, max, vdata, idx, state, =>
match_indices.push(state.progress)
false
while match_indices.length
state.progress = match_indices.pop()
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count, 'greedy backtracking' ]
return result if result = @_match_range_suffix(suffix, vdata, idx, state)
state.work.pop()
state.count--
@debug_log -> [ 'range', idx + state.progress, 'fail', 'greedy backtracking' ]
return
@_match_nongreedy_range: (beta, min, max, suffix) -> (vdata, idx) ->
return unless state = @_match_range_to_min(beta, min, max, false, vdata, idx)
@_match_range_suffix(suffix, vdata, idx, state) or @_match_range_from_min(beta, max, vdata, idx, state, =>
@_match_range_suffix(suffix, vdata, idx, state)
) or (@debug_log( -> [ 'range', idx + state.progress, 'fail', '>=min non-greedy' ]); undefined)
_match_range_to_min: (beta, min, max, greedy, vdata, idx) ->
@debug_log -> [ 'range', idx, 'begin',
'%s min=%s max=%s %s %s'.sprintf(beta.name, min, (if max? then max else ''),
(if greedy then 'greedy' else 'non-greedy'),
(if suffix? then 'suffix='+suffix.name else 'no-suffix')) ]
if max? and min > max
@debug_log -> [ 're', idx, 'fail', 'min > max' ]
return
state = { count: 0, progress: 0, work: [], greedy: greedy }
while state.count < min
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count, '<min' ]
m = beta.op.call this, vdata, idx + state.progress
unless m?
@debug_log -> [ 'range', idx + state.progress, 'fail', '<min matches' ]
return
state.progress += m[0]
state.work.push m[1]
state.count++
state
_match_range_from_min: (beta, max, vdata, idx, state, func) ->
while not max? or state.count < max
@debug_log -> [ 'range', idx + state.progress, 'i='+state.count,
'>=min %s'.sprintf(if state.greedy then 'greedy' else 'non-greedy') ]
m = beta.op.call this, vdata, idx + state.progress
break unless m?
state.progress += m[0]
state.work.push m[1]
state.count++
if output = func()
return output
return
_match_range_suffix: (suffix, vdata, idx, state) ->
if suffix?
if (m = suffix.op.call this, vdata, idx + state.progress)?
state.progress += m[0]
state.work.push m[1]
@debug_log -> [ 'range', idx + state.progress, 'success',
'count=%d %s'.sprintf(state.count, (if state.greedy then 'greedy' else 'non-greedy')) ]
return [ state.progress, { pos: idx, length: state.progress, type: 'seq', seq: state.work } ]
else
return
else
@debug_log -> [ 'range', idx + state.progress, 'success',
'count=%d %s'.sprintf(state.count, (if state.greedy then 'greedy' else 'non-greedy trivial')) ]
return [ state.progress, { pos: idx, length: state.progress, type: 'seq', seq: state.work } ]
@match_re: (rre, match_name) -> (vdata, idx) ->
m = rre.exec @str.substr idx
if m
@debug_log -> [ 're', idx, 'success', @strip_quotes inspect rre.source ]
vdata[match_name] = m[0..-1] if match_name?
[ m[0].length, { pos: idx, length: m[0].length, type: 're', match: m[0], groups: m[0..-1] } ]
else
@debug_log -> [ 're', idx, 'fail', @strip_quotes inspect rre.source ]
return
@match_seq: (beta_seq...) ->
(vdata, idx) ->
@debug_log -> [ 'seq', idx, 'begin', (beta.name for beta in beta_seq) ]
progress = 0
work = [ ]
i = 0
for beta in beta_seq
@debug_log -> [ 'seq', idx + progress, 'i='+i, beta.name ]
m = beta.op.call this, vdata, idx + progress
unless m?
@debug_log -> [ 'seq', idx + progress, 'fail' ]
return
progress += m[0]
work.push m[1]
i++
@debug_log -> [ 'seq', idx + progress, 'success' ]
[ progress, { pos: idx, length: progress, type: 'seq', seq: work } ]
@match_v: (alpha_s, argf) -> (vdata, idx) ->
@debug_log -> [ 'v', idx, 'begin', alpha_s ]
new_vdata = { }
new_vdata.arg = argf.call this, vdata if argf?
m = @vcache(alpha_s, idx, new_vdata)
@debug_log -> [ 'v', idx + (if m? then m[0] else 0), (if m? then 'success' else 'fail'), alpha_s ]
m
@match_var_re: (re_str, match_name) ->
self = this
(vdata, idx) ->
self.match_re(RegExp('^(?:' + @replace_backreferences(re_str, vdata) + ')'), match_name).call this, vdata, idx
@op_transform: (f, beta) -> (vdata, idx) ->
@debug_log -> [ 'transform', idx, 'begin', beta.name ]
m = beta.op.call this, vdata, idx
unless m?
@debug_log -> [ 'transform', idx, 'fail', beta.name ]
return
tm = f.call this, m[1], vdata, idx
unless tm?
@debug_log -> [ 'transform', idx + m[0], 'fail', 'transform' ]
return
@debug_log -> [ 'transform', idx + m[0], 'success' ]
[ m[0], tm ]
parse: (str) ->
@str = str
@v_cache = {}
@debug_log -> [ 'parse', 0, 'begin' ]
doc = @Document { }, 0
unless doc?
@debug_log -> [ 'parse', 0, 'fail' ]
return
@debug_log -> [ 'parse', doc[0], 'success' ]
doc[1]
replace_backreferences: (re_str, vdata) ->
work = re_str
while m = (/\\=([^\[]+)\[([0-9]+)\]/.exec(work))
mstr = (vdata[m[1]] || [ ])[m[2]]
mstr ?= ''
work = work.substr(0, m.index) + re_quote(mstr) + work.substr(m.index + m[0].length)
work
string_abbrev: (start, n) ->
istr = @str.substr(start)
istr = @strip_quotes inspect istr
if istr.length > n
istr.substr(0, n - 3) + '...'
else
istr
strip_quotes: (str) ->
m = /^'(.*)'$/.exec(str)
if m
m[1]
else
str
vcache: (alpha_s, idx, vdata) ->
cache_key = [ PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PIvPI:KEY:<KEY>END_PI
if @v_cache.hasOwnProperty(cache_key)
@debug_log -> [ 'vcache', idx, 'cached' ]
return @v_cache[cache_key]
else
@v_cache[cache_key] = this[alpha_s] vdata, idx
exports.Parser = Parser
|
[
{
"context": "t.header \"\"\"/*\n\t\t\t@license md-date-time\n\t\t\t@author SimeonC\n\t\t\t@license 2015 MIT\n\t\t\t@version #{pkg.version}\n\t",
"end": 1678,
"score": 0.9119669795036316,
"start": 1671,
"tag": "USERNAME",
"value": "SimeonC"
},
{
"context": "t.header \"\"\"/*\n\t\t\t@... | gulpfile.coffee | Teleopti/md-date-time | 3 | # dependencies
fs = require 'fs'
path = require 'path'
gulp = require 'gulp'
git = require 'gulp-git'
bump = require 'gulp-bump'
filter = require 'gulp-filter'
tag_version = require 'gulp-tag-version'
del = require 'del'
concat = require 'gulp-concat-util'
order = require 'gulp-order'
rename = require 'gulp-rename'
runSequence = require 'run-sequence'
changelog = require 'conventional-changelog'
stylus = require 'gulp-stylus'
autoprefixer = require 'gulp-autoprefixer'
coffee = require 'gulp-coffee'
coffeelint = require 'gulp-coffeelint'
jade = require 'gulp-jade'
ngtemplate = require 'gulp-ngtemplate'
htmlmin = require 'gulp-htmlmin'
gulp.task 'clean:dist', (cb) -> del ['dist/*'], cb
gulp.task 'compile:jade', ['clean:dist'], ->
gulp.src ['./src/template.jade']
.pipe jade()
.pipe rename 'md-date-time.tpl.temp'
.pipe gulp.dest 'dist'
.pipe rename 'md-date-time.tpl.html'
.pipe htmlmin collapseWhitespace: true
.pipe ngtemplate module: 'mdDateTime'
.pipe rename 'md-date-time.tpl.js.temp'
.pipe gulp.dest 'dist'
gulp.task 'compile:coffee', ['compile:jade'], ->
gulp.src ['./src/main.coffee']
# Lint the coffescript
.pipe coffeelint()
.pipe coffeelint.reporter()
.pipe coffeelint.reporter 'fail'
.pipe coffee bare: true
.pipe rename 'md-date-time.js'
.pipe gulp.dest 'dist'
gulp.task 'compile:javascript', ['compile:coffee'], ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
gulp.src ['./dist/md-date-time.js','./dist/md-date-time.tpl.js.temp']
.pipe order ['dist/md-date-time.js','dist/md-date-time.tpl.js.temp']
.pipe concat 'md-date-time.js'
.pipe concat.header """/*
@license md-date-time
@author SimeonC
@license 2015 MIT
@version #{pkg.version}
See README.md for requirements and use.
*/
"""
.pipe gulp.dest 'dist'
gulp.task 'compile:stylus', ['clean:dist'], ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
gulp.src ['./src/styles.styl']
.pipe stylus()
.pipe autoprefixer()
.pipe concat()
.pipe concat.header """/*
@license md-date-time
@author SimeonC
@license 2015 MIT
@version #{pkg.version}
See README.md for requirements and use.
*/
"""
.pipe rename 'md-date-time.css'
.pipe gulp.dest 'dist'
gulp.task 'compile:main', ['compile:javascript','compile:stylus']
gulp.task 'compile', ['compile:main'], (cb) -> del ['dist/*.temp'], cb
###
Bumping version number and tagging the repository with it.
You can use the commands
gulp prerel # makes v0.1.0 -> v0.1.1-pre1
gulp patch # makes v0.1.0 → v0.1.1
gulp minor # makes v0.1.1 → v0.2.0
gulp major # makes v0.2.1 → v1.0.0
To bump the version numbers accordingly after you did a patch,
introduced a feature or made a backwards-incompatible release.
###
releaseVersion = (importance) ->
# get all the files to bump version in
gulp.src ['./package.json', './bower.json']
# bump the version number in those files
.pipe bump type: importance
# save it back to filesystem
.pipe gulp.dest './'
gulp.task 'tagversion', ->
gulp.src ['./package.json','./bower.json','./changelog.md','./dist/*']
# commit the changed version number
.pipe git.commit 'chore(release): Bump Version Number'
# Filter down to only one file
.pipe filter 'package.json'
# **tag it in the repository**
.pipe tag_version()
gulp.task 'changelog', (cb) ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
changelog
version: pkg.version
repository: pkg.repository.url
, (err, content) ->
fs.writeFile './changelog.md', content, cb
gulp.task 'release:prerel', -> releaseVersion 'prerelease'
gulp.task 'release:patch', -> releaseVersion 'patch'
gulp.task 'release:minor', -> releaseVersion 'minor'
gulp.task 'release:major', -> releaseVersion 'major'
gulp.task 'prerel', ->
runSequence(
'release:prerel'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'patch', ->
runSequence(
'release:patch'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'minor', ->
runSequence(
'release:minor'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'major', ->
runSequence(
'release:major'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'default', ['compile'] | 11805 | # dependencies
fs = require 'fs'
path = require 'path'
gulp = require 'gulp'
git = require 'gulp-git'
bump = require 'gulp-bump'
filter = require 'gulp-filter'
tag_version = require 'gulp-tag-version'
del = require 'del'
concat = require 'gulp-concat-util'
order = require 'gulp-order'
rename = require 'gulp-rename'
runSequence = require 'run-sequence'
changelog = require 'conventional-changelog'
stylus = require 'gulp-stylus'
autoprefixer = require 'gulp-autoprefixer'
coffee = require 'gulp-coffee'
coffeelint = require 'gulp-coffeelint'
jade = require 'gulp-jade'
ngtemplate = require 'gulp-ngtemplate'
htmlmin = require 'gulp-htmlmin'
gulp.task 'clean:dist', (cb) -> del ['dist/*'], cb
gulp.task 'compile:jade', ['clean:dist'], ->
gulp.src ['./src/template.jade']
.pipe jade()
.pipe rename 'md-date-time.tpl.temp'
.pipe gulp.dest 'dist'
.pipe rename 'md-date-time.tpl.html'
.pipe htmlmin collapseWhitespace: true
.pipe ngtemplate module: 'mdDateTime'
.pipe rename 'md-date-time.tpl.js.temp'
.pipe gulp.dest 'dist'
gulp.task 'compile:coffee', ['compile:jade'], ->
gulp.src ['./src/main.coffee']
# Lint the coffescript
.pipe coffeelint()
.pipe coffeelint.reporter()
.pipe coffeelint.reporter 'fail'
.pipe coffee bare: true
.pipe rename 'md-date-time.js'
.pipe gulp.dest 'dist'
gulp.task 'compile:javascript', ['compile:coffee'], ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
gulp.src ['./dist/md-date-time.js','./dist/md-date-time.tpl.js.temp']
.pipe order ['dist/md-date-time.js','dist/md-date-time.tpl.js.temp']
.pipe concat 'md-date-time.js'
.pipe concat.header """/*
@license md-date-time
@author SimeonC
@license 2015 MIT
@version #{pkg.version}
See README.md for requirements and use.
*/
"""
.pipe gulp.dest 'dist'
gulp.task 'compile:stylus', ['clean:dist'], ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
gulp.src ['./src/styles.styl']
.pipe stylus()
.pipe autoprefixer()
.pipe concat()
.pipe concat.header """/*
@license md-date-time
@author <NAME>imeonC
@license 2015 MIT
@version #{pkg.version}
See README.md for requirements and use.
*/
"""
.pipe rename 'md-date-time.css'
.pipe gulp.dest 'dist'
gulp.task 'compile:main', ['compile:javascript','compile:stylus']
gulp.task 'compile', ['compile:main'], (cb) -> del ['dist/*.temp'], cb
###
Bumping version number and tagging the repository with it.
You can use the commands
gulp prerel # makes v0.1.0 -> v0.1.1-pre1
gulp patch # makes v0.1.0 → v0.1.1
gulp minor # makes v0.1.1 → v0.2.0
gulp major # makes v0.2.1 → v1.0.0
To bump the version numbers accordingly after you did a patch,
introduced a feature or made a backwards-incompatible release.
###
releaseVersion = (importance) ->
# get all the files to bump version in
gulp.src ['./package.json', './bower.json']
# bump the version number in those files
.pipe bump type: importance
# save it back to filesystem
.pipe gulp.dest './'
gulp.task 'tagversion', ->
gulp.src ['./package.json','./bower.json','./changelog.md','./dist/*']
# commit the changed version number
.pipe git.commit 'chore(release): Bump Version Number'
# Filter down to only one file
.pipe filter 'package.json'
# **tag it in the repository**
.pipe tag_version()
gulp.task 'changelog', (cb) ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
changelog
version: pkg.version
repository: pkg.repository.url
, (err, content) ->
fs.writeFile './changelog.md', content, cb
gulp.task 'release:prerel', -> releaseVersion 'prerelease'
gulp.task 'release:patch', -> releaseVersion 'patch'
gulp.task 'release:minor', -> releaseVersion 'minor'
gulp.task 'release:major', -> releaseVersion 'major'
gulp.task 'prerel', ->
runSequence(
'release:prerel'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'patch', ->
runSequence(
'release:patch'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'minor', ->
runSequence(
'release:minor'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'major', ->
runSequence(
'release:major'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'default', ['compile'] | true | # dependencies
fs = require 'fs'
path = require 'path'
gulp = require 'gulp'
git = require 'gulp-git'
bump = require 'gulp-bump'
filter = require 'gulp-filter'
tag_version = require 'gulp-tag-version'
del = require 'del'
concat = require 'gulp-concat-util'
order = require 'gulp-order'
rename = require 'gulp-rename'
runSequence = require 'run-sequence'
changelog = require 'conventional-changelog'
stylus = require 'gulp-stylus'
autoprefixer = require 'gulp-autoprefixer'
coffee = require 'gulp-coffee'
coffeelint = require 'gulp-coffeelint'
jade = require 'gulp-jade'
ngtemplate = require 'gulp-ngtemplate'
htmlmin = require 'gulp-htmlmin'
gulp.task 'clean:dist', (cb) -> del ['dist/*'], cb
gulp.task 'compile:jade', ['clean:dist'], ->
gulp.src ['./src/template.jade']
.pipe jade()
.pipe rename 'md-date-time.tpl.temp'
.pipe gulp.dest 'dist'
.pipe rename 'md-date-time.tpl.html'
.pipe htmlmin collapseWhitespace: true
.pipe ngtemplate module: 'mdDateTime'
.pipe rename 'md-date-time.tpl.js.temp'
.pipe gulp.dest 'dist'
gulp.task 'compile:coffee', ['compile:jade'], ->
gulp.src ['./src/main.coffee']
# Lint the coffescript
.pipe coffeelint()
.pipe coffeelint.reporter()
.pipe coffeelint.reporter 'fail'
.pipe coffee bare: true
.pipe rename 'md-date-time.js'
.pipe gulp.dest 'dist'
gulp.task 'compile:javascript', ['compile:coffee'], ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
gulp.src ['./dist/md-date-time.js','./dist/md-date-time.tpl.js.temp']
.pipe order ['dist/md-date-time.js','dist/md-date-time.tpl.js.temp']
.pipe concat 'md-date-time.js'
.pipe concat.header """/*
@license md-date-time
@author SimeonC
@license 2015 MIT
@version #{pkg.version}
See README.md for requirements and use.
*/
"""
.pipe gulp.dest 'dist'
gulp.task 'compile:stylus', ['clean:dist'], ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
gulp.src ['./src/styles.styl']
.pipe stylus()
.pipe autoprefixer()
.pipe concat()
.pipe concat.header """/*
@license md-date-time
@author PI:NAME:<NAME>END_PIimeonC
@license 2015 MIT
@version #{pkg.version}
See README.md for requirements and use.
*/
"""
.pipe rename 'md-date-time.css'
.pipe gulp.dest 'dist'
gulp.task 'compile:main', ['compile:javascript','compile:stylus']
gulp.task 'compile', ['compile:main'], (cb) -> del ['dist/*.temp'], cb
###
Bumping version number and tagging the repository with it.
You can use the commands
gulp prerel # makes v0.1.0 -> v0.1.1-pre1
gulp patch # makes v0.1.0 → v0.1.1
gulp minor # makes v0.1.1 → v0.2.0
gulp major # makes v0.2.1 → v1.0.0
To bump the version numbers accordingly after you did a patch,
introduced a feature or made a backwards-incompatible release.
###
releaseVersion = (importance) ->
# get all the files to bump version in
gulp.src ['./package.json', './bower.json']
# bump the version number in those files
.pipe bump type: importance
# save it back to filesystem
.pipe gulp.dest './'
gulp.task 'tagversion', ->
gulp.src ['./package.json','./bower.json','./changelog.md','./dist/*']
# commit the changed version number
.pipe git.commit 'chore(release): Bump Version Number'
# Filter down to only one file
.pipe filter 'package.json'
# **tag it in the repository**
.pipe tag_version()
gulp.task 'changelog', (cb) ->
pkg = JSON.parse fs.readFileSync './package.json', 'utf8'
changelog
version: pkg.version
repository: pkg.repository.url
, (err, content) ->
fs.writeFile './changelog.md', content, cb
gulp.task 'release:prerel', -> releaseVersion 'prerelease'
gulp.task 'release:patch', -> releaseVersion 'patch'
gulp.task 'release:minor', -> releaseVersion 'minor'
gulp.task 'release:major', -> releaseVersion 'major'
gulp.task 'prerel', ->
runSequence(
'release:prerel'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'patch', ->
runSequence(
'release:patch'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'minor', ->
runSequence(
'release:minor'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'major', ->
runSequence(
'release:major'
, 'changelog'
, 'compile'
, 'tagversion'
)
gulp.task 'default', ['compile'] |
[
{
"context": "utf8'\nconsole.log pk\npk[0].decryptSecretMPIs 'asdfqwer'\nconsole.log pk[0]\nfor i in pk[0].privateKeyPacke",
"end": 210,
"score": 0.8465661406517029,
"start": 206,
"tag": "KEY",
"value": "qwer"
}
] | dev/oc5.iced | samkenxstream/kbpgp | 464 |
{openpgp} = require('openpgp')
openpgp.init()
fs = require 'fs'
await fs.readFile '../xa', defer err, buffer
pk = openpgp.read_privateKey buffer.toString 'utf8'
console.log pk
pk[0].decryptSecretMPIs 'asdfqwer'
console.log pk[0]
for i in pk[0].privateKeyPacket.secMPIs
console.log i.toString()
#packet = new KeyMaterial()
#packet.IV = (Buffer.from "b61522b832d04bfd", "hex").toString 'binary'
#packet.IVLength = packet.IV.length | 109599 |
{openpgp} = require('openpgp')
openpgp.init()
fs = require 'fs'
await fs.readFile '../xa', defer err, buffer
pk = openpgp.read_privateKey buffer.toString 'utf8'
console.log pk
pk[0].decryptSecretMPIs 'asdf<KEY>'
console.log pk[0]
for i in pk[0].privateKeyPacket.secMPIs
console.log i.toString()
#packet = new KeyMaterial()
#packet.IV = (Buffer.from "b61522b832d04bfd", "hex").toString 'binary'
#packet.IVLength = packet.IV.length | true |
{openpgp} = require('openpgp')
openpgp.init()
fs = require 'fs'
await fs.readFile '../xa', defer err, buffer
pk = openpgp.read_privateKey buffer.toString 'utf8'
console.log pk
pk[0].decryptSecretMPIs 'asdfPI:KEY:<KEY>END_PI'
console.log pk[0]
for i in pk[0].privateKeyPacket.secMPIs
console.log i.toString()
#packet = new KeyMaterial()
#packet.IV = (Buffer.from "b61522b832d04bfd", "hex").toString 'binary'
#packet.IVLength = packet.IV.length |
[
{
"context": "append('gallery[title]', $scope.gallery.title || 'Галерея')\n fd.append('gallery[poster]', $scope.gallery",
"end": 719,
"score": 0.9838983416557312,
"start": 712,
"tag": "NAME",
"value": "Галерея"
}
] | app/assets/javascripts/kms_gallery/application/controllers/galleries_controller.coffee | macrocoders/kms_gallery | 0 | angular.module('KMS').requires.push('ngFileUpload')
GalleriesController = ($scope, $state, $cookieStore, $timeout, Upload, Restangular, $stateParams, $http) ->
$scope.store = Restangular.all('galleries')
$scope.$state = $state
$scope.store.getList().then (galleries)->
$scope.galleries = galleries
if $stateParams.id
$scope.store.get($stateParams.id).then (gallery)->
$scope.gallery = gallery
else
$scope.gallery = {}
$scope.destroy = (gallery)->
if(confirm('Вы уверены?'))
gallery.remove().then ->
$scope.galleries = _.without($scope.galleries, gallery)
$scope.create = ->
fd = new FormData
fd.append('gallery[title]', $scope.gallery.title || 'Галерея')
fd.append('gallery[poster]', $scope.gallery.poster)
fd.append('gallery[h1]', $scope.gallery.h1 || '')
fd.append('gallery[meta_title]', $scope.gallery.meta_title || '')
fd.append('gallery[meta_keywords]', $scope.gallery.meta_keywords || '')
fd.append('gallery[meta_description]', $scope.gallery.meta_description || '')
$scope.store.withHttpConfig({ transformRequest: angular.identity }).post(fd, null, {"Content-Type": undefined}).then ->
$state.go('galleries')
,->
console.log('bug')
$scope.update = ->
fd = new FormData
fd.append('gallery[title]', $scope.gallery.title)
fd.append('gallery[h1]', $scope.gallery.h1)
fd.append('gallery[meta_title]', $scope.gallery.meta_title)
fd.append('gallery[meta_keywords]', $scope.gallery.meta_keywords)
fd.append('gallery[meta_description]', $scope.gallery.meta_description)
if $scope.gallery.poster.constructor.name == "File"
fd.append('gallery[poster]', $scope.gallery.poster)
$scope.gallery.withHttpConfig({ transformRequest: angular.identity }).post('', fd, '', {"Content-Type": undefined}).then ->
$state.go('galleries')
,->
console.log('bug')
$scope.uploadPictures = (files, gallery) ->
if files and files.length
$scope.files = files
angular.forEach files, (file) ->
file.upload = Upload.upload(
url: 'kms/galleries/'+$scope.gallery.id+'/pictures'
method: 'POST'
fields: { 'picture[gallery_id]' : $scope.gallery.id, 'picture[picture]' : file }
file: {'picture[picture]' : file})
file.upload.then ((response) ->
$timeout ->
file.result = response.data
if file == files[files.length - 1]
$state.go $state.current, {}, reload: true
), ((response) ->
if response.status > 0
$scope.errorMsg = response.status + ': ' + response.data
), (evt) ->
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total))
$scope.destroyPicture = (idx, gallery)->
picture_to_delete = $scope.gallery.pictures[idx]
if(confirm('Вы уверены?'))
$http.delete('kms/galleries/pictures/'+picture_to_delete.id).then ->
gallery.pictures.splice(idx, 1)
$scope.galleriesSortableOptions =
orderChanged: (event)->
for gallery, index in event.dest.sortableScope.modelValue
gallery_copy =
id: gallery.id
position: index
Restangular.restangularizeElement($scope.model, gallery_copy, 'galleries').put()
angular.module('KMS')
.controller('GalleriesController', ['$scope', '$state', '$cookieStore', '$timeout', 'Upload', 'Restangular', '$stateParams', '$http', GalleriesController])
| 469 | angular.module('KMS').requires.push('ngFileUpload')
GalleriesController = ($scope, $state, $cookieStore, $timeout, Upload, Restangular, $stateParams, $http) ->
$scope.store = Restangular.all('galleries')
$scope.$state = $state
$scope.store.getList().then (galleries)->
$scope.galleries = galleries
if $stateParams.id
$scope.store.get($stateParams.id).then (gallery)->
$scope.gallery = gallery
else
$scope.gallery = {}
$scope.destroy = (gallery)->
if(confirm('Вы уверены?'))
gallery.remove().then ->
$scope.galleries = _.without($scope.galleries, gallery)
$scope.create = ->
fd = new FormData
fd.append('gallery[title]', $scope.gallery.title || '<NAME>')
fd.append('gallery[poster]', $scope.gallery.poster)
fd.append('gallery[h1]', $scope.gallery.h1 || '')
fd.append('gallery[meta_title]', $scope.gallery.meta_title || '')
fd.append('gallery[meta_keywords]', $scope.gallery.meta_keywords || '')
fd.append('gallery[meta_description]', $scope.gallery.meta_description || '')
$scope.store.withHttpConfig({ transformRequest: angular.identity }).post(fd, null, {"Content-Type": undefined}).then ->
$state.go('galleries')
,->
console.log('bug')
$scope.update = ->
fd = new FormData
fd.append('gallery[title]', $scope.gallery.title)
fd.append('gallery[h1]', $scope.gallery.h1)
fd.append('gallery[meta_title]', $scope.gallery.meta_title)
fd.append('gallery[meta_keywords]', $scope.gallery.meta_keywords)
fd.append('gallery[meta_description]', $scope.gallery.meta_description)
if $scope.gallery.poster.constructor.name == "File"
fd.append('gallery[poster]', $scope.gallery.poster)
$scope.gallery.withHttpConfig({ transformRequest: angular.identity }).post('', fd, '', {"Content-Type": undefined}).then ->
$state.go('galleries')
,->
console.log('bug')
$scope.uploadPictures = (files, gallery) ->
if files and files.length
$scope.files = files
angular.forEach files, (file) ->
file.upload = Upload.upload(
url: 'kms/galleries/'+$scope.gallery.id+'/pictures'
method: 'POST'
fields: { 'picture[gallery_id]' : $scope.gallery.id, 'picture[picture]' : file }
file: {'picture[picture]' : file})
file.upload.then ((response) ->
$timeout ->
file.result = response.data
if file == files[files.length - 1]
$state.go $state.current, {}, reload: true
), ((response) ->
if response.status > 0
$scope.errorMsg = response.status + ': ' + response.data
), (evt) ->
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total))
$scope.destroyPicture = (idx, gallery)->
picture_to_delete = $scope.gallery.pictures[idx]
if(confirm('Вы уверены?'))
$http.delete('kms/galleries/pictures/'+picture_to_delete.id).then ->
gallery.pictures.splice(idx, 1)
$scope.galleriesSortableOptions =
orderChanged: (event)->
for gallery, index in event.dest.sortableScope.modelValue
gallery_copy =
id: gallery.id
position: index
Restangular.restangularizeElement($scope.model, gallery_copy, 'galleries').put()
angular.module('KMS')
.controller('GalleriesController', ['$scope', '$state', '$cookieStore', '$timeout', 'Upload', 'Restangular', '$stateParams', '$http', GalleriesController])
| true | angular.module('KMS').requires.push('ngFileUpload')
GalleriesController = ($scope, $state, $cookieStore, $timeout, Upload, Restangular, $stateParams, $http) ->
$scope.store = Restangular.all('galleries')
$scope.$state = $state
$scope.store.getList().then (galleries)->
$scope.galleries = galleries
if $stateParams.id
$scope.store.get($stateParams.id).then (gallery)->
$scope.gallery = gallery
else
$scope.gallery = {}
$scope.destroy = (gallery)->
if(confirm('Вы уверены?'))
gallery.remove().then ->
$scope.galleries = _.without($scope.galleries, gallery)
$scope.create = ->
fd = new FormData
fd.append('gallery[title]', $scope.gallery.title || 'PI:NAME:<NAME>END_PI')
fd.append('gallery[poster]', $scope.gallery.poster)
fd.append('gallery[h1]', $scope.gallery.h1 || '')
fd.append('gallery[meta_title]', $scope.gallery.meta_title || '')
fd.append('gallery[meta_keywords]', $scope.gallery.meta_keywords || '')
fd.append('gallery[meta_description]', $scope.gallery.meta_description || '')
$scope.store.withHttpConfig({ transformRequest: angular.identity }).post(fd, null, {"Content-Type": undefined}).then ->
$state.go('galleries')
,->
console.log('bug')
$scope.update = ->
fd = new FormData
fd.append('gallery[title]', $scope.gallery.title)
fd.append('gallery[h1]', $scope.gallery.h1)
fd.append('gallery[meta_title]', $scope.gallery.meta_title)
fd.append('gallery[meta_keywords]', $scope.gallery.meta_keywords)
fd.append('gallery[meta_description]', $scope.gallery.meta_description)
if $scope.gallery.poster.constructor.name == "File"
fd.append('gallery[poster]', $scope.gallery.poster)
$scope.gallery.withHttpConfig({ transformRequest: angular.identity }).post('', fd, '', {"Content-Type": undefined}).then ->
$state.go('galleries')
,->
console.log('bug')
$scope.uploadPictures = (files, gallery) ->
if files and files.length
$scope.files = files
angular.forEach files, (file) ->
file.upload = Upload.upload(
url: 'kms/galleries/'+$scope.gallery.id+'/pictures'
method: 'POST'
fields: { 'picture[gallery_id]' : $scope.gallery.id, 'picture[picture]' : file }
file: {'picture[picture]' : file})
file.upload.then ((response) ->
$timeout ->
file.result = response.data
if file == files[files.length - 1]
$state.go $state.current, {}, reload: true
), ((response) ->
if response.status > 0
$scope.errorMsg = response.status + ': ' + response.data
), (evt) ->
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total))
$scope.destroyPicture = (idx, gallery)->
picture_to_delete = $scope.gallery.pictures[idx]
if(confirm('Вы уверены?'))
$http.delete('kms/galleries/pictures/'+picture_to_delete.id).then ->
gallery.pictures.splice(idx, 1)
$scope.galleriesSortableOptions =
orderChanged: (event)->
for gallery, index in event.dest.sortableScope.modelValue
gallery_copy =
id: gallery.id
position: index
Restangular.restangularizeElement($scope.model, gallery_copy, 'galleries').put()
angular.module('KMS')
.controller('GalleriesController', ['$scope', '$state', '$cookieStore', '$timeout', 'Upload', 'Restangular', '$stateParams', '$http', GalleriesController])
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9986495971679688,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | lib/crypto.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# 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.
# Note: In 0.8 and before, crypto functions all defaulted to using
# binary-encoded strings rather than buffers.
# This is here because many functions accepted binary strings without
# any explicit encoding in older versions of node, and we don't want
# to break them unnecessarily.
toBuf = (str, encoding) ->
encoding = encoding or "binary"
if util.isString(str)
encoding = "binary" if encoding is "buffer"
str = new Buffer(str, encoding)
str
LazyTransform = (options) ->
@_options = options
return
Hash = (algorithm, options) ->
return new Hash(algorithm, options) unless this instanceof Hash
@_handle = new binding.Hash(algorithm)
LazyTransform.call this, options
return
Hmac = (hmac, key, options) ->
return new Hmac(hmac, key, options) unless this instanceof Hmac
@_handle = new binding.Hmac()
@_handle.init hmac, toBuf(key)
LazyTransform.call this, options
return
getDecoder = (decoder, encoding) ->
encoding = "utf8" if encoding is "utf-8" # Normalize encoding.
decoder = decoder or new StringDecoder(encoding)
assert decoder.encoding is encoding, "Cannot change encoding"
decoder
Cipher = (cipher, password, options) ->
return new Cipher(cipher, password, options) unless this instanceof Cipher
@_handle = new binding.CipherBase(true)
@_handle.init cipher, toBuf(password)
@_decoder = null
LazyTransform.call this, options
return
Cipheriv = (cipher, key, iv, options) ->
return new Cipheriv(cipher, key, iv, options) unless this instanceof Cipheriv
@_handle = new binding.CipherBase(true)
@_handle.initiv cipher, toBuf(key), toBuf(iv)
@_decoder = null
LazyTransform.call this, options
return
Decipher = (cipher, password, options) ->
return new Decipher(cipher, password, options) unless this instanceof Decipher
@_handle = new binding.CipherBase(false)
@_handle.init cipher, toBuf(password)
@_decoder = null
LazyTransform.call this, options
return
Decipheriv = (cipher, key, iv, options) ->
return new Decipheriv(cipher, key, iv, options) unless this instanceof Decipheriv
@_handle = new binding.CipherBase(false)
@_handle.initiv cipher, toBuf(key), toBuf(iv)
@_decoder = null
LazyTransform.call this, options
return
Sign = (algorithm, options) ->
return new Sign(algorithm, options) unless this instanceof Sign
@_handle = new binding.Sign()
@_handle.init algorithm
stream.Writable.call this, options
return
Verify = (algorithm, options) ->
return new Verify(algorithm, options) unless this instanceof Verify
@_handle = new binding.Verify
@_handle.init algorithm
stream.Writable.call this, options
return
DiffieHellman = (sizeOrKey, keyEncoding, generator, genEncoding) ->
return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) unless this instanceof DiffieHellman
throw new TypeError("First argument should be number, string or Buffer") if not util.isBuffer(sizeOrKey) and typeof sizeOrKey isnt "number" and typeof sizeOrKey isnt "string"
if keyEncoding
if typeof keyEncoding isnt "string" or (not Buffer.isEncoding(keyEncoding) and keyEncoding isnt "buffer")
genEncoding = generator
generator = keyEncoding
keyEncoding = false
keyEncoding = keyEncoding or exports.DEFAULT_ENCODING
genEncoding = genEncoding or exports.DEFAULT_ENCODING
sizeOrKey = toBuf(sizeOrKey, keyEncoding) if typeof sizeOrKey isnt "number"
unless generator
generator = DH_GENERATOR
else generator = toBuf(generator, genEncoding) if typeof generator isnt "number"
@_handle = new binding.DiffieHellman(sizeOrKey, generator)
Object.defineProperty this, "verifyError",
enumerable: true
value: @_handle.verifyError
writable: false
return
DiffieHellmanGroup = (name) ->
return new DiffieHellmanGroup(name) unless this instanceof DiffieHellmanGroup
@_handle = new binding.DiffieHellmanGroup(name)
Object.defineProperty this, "verifyError",
enumerable: true
value: @_handle.verifyError
writable: false
return
dhGenerateKeys = (encoding) ->
keys = @_handle.generateKeys()
encoding = encoding or exports.DEFAULT_ENCODING
keys = keys.toString(encoding) if encoding and encoding isnt "buffer"
keys
dhComputeSecret = (key, inEnc, outEnc) ->
inEnc = inEnc or exports.DEFAULT_ENCODING
outEnc = outEnc or exports.DEFAULT_ENCODING
ret = @_handle.computeSecret(toBuf(key, inEnc))
ret = ret.toString(outEnc) if outEnc and outEnc isnt "buffer"
ret
dhGetPrime = (encoding) ->
prime = @_handle.getPrime()
encoding = encoding or exports.DEFAULT_ENCODING
prime = prime.toString(encoding) if encoding and encoding isnt "buffer"
prime
dhGetGenerator = (encoding) ->
generator = @_handle.getGenerator()
encoding = encoding or exports.DEFAULT_ENCODING
generator = generator.toString(encoding) if encoding and encoding isnt "buffer"
generator
dhGetPublicKey = (encoding) ->
key = @_handle.getPublicKey()
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
dhGetPrivateKey = (encoding) ->
key = @_handle.getPrivateKey()
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
ECDH = (curve) ->
throw new TypeError("curve should be a string") unless util.isString(curve)
@_handle = new binding.ECDH(curve)
return
# Default
pbkdf2 = (password, salt, iterations, keylen, digest, callback) ->
password = toBuf(password)
salt = toBuf(salt)
return binding.PBKDF2(password, salt, iterations, keylen, digest, callback) if exports.DEFAULT_ENCODING is "buffer"
# at this point, we need to handle encodings.
encoding = exports.DEFAULT_ENCODING
if callback
next = (er, ret) ->
ret = ret.toString(encoding) if ret
callback er, ret
return
binding.PBKDF2 password, salt, iterations, keylen, digest, next
else
ret = binding.PBKDF2(password, salt, iterations, keylen, digest)
ret.toString encoding
return
Certificate = ->
return new Certificate() unless this instanceof Certificate
@_handle = new binding.Certificate()
return
# Use provided engine for everything by default
filterDuplicates = (names) ->
# Drop all-caps names in favor of their lowercase aliases,
# for example, 'sha1' instead of 'SHA1'.
ctx = {}
names.forEach (name) ->
key = name
key = key.toLowerCase() if /^[0-9A-Z\-]+$/.test(key)
ctx[key] = name if not ctx.hasOwnProperty(key) or ctx[key] < name
return
Object.getOwnPropertyNames(ctx).map((key) ->
ctx[key]
).sort()
"use strict"
exports.DEFAULT_ENCODING = "buffer"
try
binding = process.binding("crypto")
randomBytes = binding.randomBytes
pseudoRandomBytes = binding.pseudoRandomBytes
getCiphers = binding.getCiphers
getHashes = binding.getHashes
catch e
throw new Error("node.js not compiled with openssl crypto support.")
constants = require("constants")
stream = require("stream")
util = require("util")
DH_GENERATOR = 2
exports._toBuf = toBuf
assert = require("assert")
StringDecoder = require("string_decoder").StringDecoder
util.inherits LazyTransform, stream.Transform
[
"_readableState"
"_writableState"
"_transformState"
].forEach (prop, i, props) ->
Object.defineProperty LazyTransform::, prop,
get: ->
stream.Transform.call this, @_options
@_writableState.decodeStrings = false
@_writableState.defaultEncoding = "binary"
this[prop]
set: (val) ->
Object.defineProperty this, prop,
value: val
enumerable: true
configurable: true
writable: true
return
configurable: true
enumerable: true
return
exports.createHash = exports.Hash = Hash
util.inherits Hash, LazyTransform
Hash::_transform = (chunk, encoding, callback) ->
@_handle.update chunk, encoding
callback()
return
Hash::_flush = (callback) ->
encoding = @_readableState.encoding or "buffer"
@push @_handle.digest(encoding), encoding
callback()
return
Hash::update = (data, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
encoding = "binary" if encoding is "buffer" and util.isString(data)
@_handle.update data, encoding
this
Hash::digest = (outputEncoding) ->
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
@_handle.digest outputEncoding
exports.createHmac = exports.Hmac = Hmac
util.inherits Hmac, LazyTransform
Hmac::update = Hash::update
Hmac::digest = Hash::digest
Hmac::_flush = Hash::_flush
Hmac::_transform = Hash::_transform
exports.createCipher = exports.Cipher = Cipher
util.inherits Cipher, LazyTransform
Cipher::_transform = (chunk, encoding, callback) ->
@push @_handle.update(chunk, encoding)
callback()
return
Cipher::_flush = (callback) ->
try
@push @_handle.final()
catch e
callback e
return
callback()
return
Cipher::update = (data, inputEncoding, outputEncoding) ->
inputEncoding = inputEncoding or exports.DEFAULT_ENCODING
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
ret = @_handle.update(data, inputEncoding)
if outputEncoding and outputEncoding isnt "buffer"
@_decoder = getDecoder(@_decoder, outputEncoding)
ret = @_decoder.write(ret)
ret
Cipher::final = (outputEncoding) ->
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
ret = @_handle.final()
if outputEncoding and outputEncoding isnt "buffer"
@_decoder = getDecoder(@_decoder, outputEncoding)
ret = @_decoder.end(ret)
ret
Cipher::setAutoPadding = (ap) ->
@_handle.setAutoPadding ap
this
Cipher::getAuthTag = ->
@_handle.getAuthTag()
Cipher::setAuthTag = (tagbuf) ->
@_handle.setAuthTag tagbuf
return
Cipher::setAAD = (aadbuf) ->
@_handle.setAAD aadbuf
return
exports.createCipheriv = exports.Cipheriv = Cipheriv
util.inherits Cipheriv, LazyTransform
Cipheriv::_transform = Cipher::_transform
Cipheriv::_flush = Cipher::_flush
Cipheriv::update = Cipher::update
Cipheriv::final = Cipher::final
Cipheriv::setAutoPadding = Cipher::setAutoPadding
Cipheriv::getAuthTag = Cipher::getAuthTag
Cipheriv::setAuthTag = Cipher::setAuthTag
Cipheriv::setAAD = Cipher::setAAD
exports.createDecipher = exports.Decipher = Decipher
util.inherits Decipher, LazyTransform
Decipher::_transform = Cipher::_transform
Decipher::_flush = Cipher::_flush
Decipher::update = Cipher::update
Decipher::final = Cipher::final
Decipher::finaltol = Cipher::final
Decipher::setAutoPadding = Cipher::setAutoPadding
Decipher::getAuthTag = Cipher::getAuthTag
Decipher::setAuthTag = Cipher::setAuthTag
Decipher::setAAD = Cipher::setAAD
exports.createDecipheriv = exports.Decipheriv = Decipheriv
util.inherits Decipheriv, LazyTransform
Decipheriv::_transform = Cipher::_transform
Decipheriv::_flush = Cipher::_flush
Decipheriv::update = Cipher::update
Decipheriv::final = Cipher::final
Decipheriv::finaltol = Cipher::final
Decipheriv::setAutoPadding = Cipher::setAutoPadding
Decipheriv::getAuthTag = Cipher::getAuthTag
Decipheriv::setAuthTag = Cipher::setAuthTag
Decipheriv::setAAD = Cipher::setAAD
exports.createSign = exports.Sign = Sign
util.inherits Sign, stream.Writable
Sign::_write = (chunk, encoding, callback) ->
@_handle.update chunk, encoding
callback()
return
Sign::update = Hash::update
Sign::sign = (options, encoding) ->
throw new Error("No key provided to sign") unless options
key = options.key or options
passphrase = options.passphrase or null
ret = @_handle.sign(toBuf(key), null, passphrase)
encoding = encoding or exports.DEFAULT_ENCODING
ret = ret.toString(encoding) if encoding and encoding isnt "buffer"
ret
exports.createVerify = exports.Verify = Verify
util.inherits Verify, stream.Writable
Verify::_write = Sign::_write
Verify::update = Sign::update
Verify::verify = (object, signature, sigEncoding) ->
sigEncoding = sigEncoding or exports.DEFAULT_ENCODING
@_handle.verify toBuf(object), toBuf(signature, sigEncoding)
exports.publicEncrypt = (options, buffer) ->
key = options.key or options
padding = options.padding or constants.RSA_PKCS1_OAEP_PADDING
binding.publicEncrypt toBuf(key), buffer, padding
exports.privateDecrypt = (options, buffer) ->
key = options.key or options
passphrase = options.passphrase or null
padding = options.padding or constants.RSA_PKCS1_OAEP_PADDING
binding.privateDecrypt toBuf(key), buffer, padding, passphrase
exports.createDiffieHellman = exports.DiffieHellman = DiffieHellman
exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = DiffieHellmanGroup
DiffieHellmanGroup::generateKeys = DiffieHellman::generateKeys = dhGenerateKeys
DiffieHellmanGroup::computeSecret = DiffieHellman::computeSecret = dhComputeSecret
DiffieHellmanGroup::getPrime = DiffieHellman::getPrime = dhGetPrime
DiffieHellmanGroup::getGenerator = DiffieHellman::getGenerator = dhGetGenerator
DiffieHellmanGroup::getPublicKey = DiffieHellman::getPublicKey = dhGetPublicKey
DiffieHellmanGroup::getPrivateKey = DiffieHellman::getPrivateKey = dhGetPrivateKey
DiffieHellman::setPublicKey = (key, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
@_handle.setPublicKey toBuf(key, encoding)
this
DiffieHellman::setPrivateKey = (key, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
@_handle.setPrivateKey toBuf(key, encoding)
this
exports.createECDH = createECDH = (curve) ->
new ECDH(curve)
ECDH::computeSecret = DiffieHellman::computeSecret
ECDH::setPrivateKey = DiffieHellman::setPrivateKey
ECDH::setPublicKey = DiffieHellman::setPublicKey
ECDH::getPrivateKey = DiffieHellman::getPrivateKey
ECDH::generateKeys = generateKeys = (encoding, format) ->
@_handle.generateKeys()
@getPublicKey encoding, format
ECDH::getPublicKey = getPublicKey = (encoding, format) ->
f = undefined
if format
f = format if typeof format is "number"
if format is "compressed"
f = constants.POINT_CONVERSION_COMPRESSED
else if format is "hybrid"
f = constants.POINT_CONVERSION_HYBRID
else if format is "uncompressed"
f = constants.POINT_CONVERSION_UNCOMPRESSED
else
throw TypeError("Bad format: " + format)
else
f = constants.POINT_CONVERSION_UNCOMPRESSED
key = @_handle.getPublicKey(f)
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
exports.pbkdf2 = (password, salt, iterations, keylen, digest, callback) ->
if util.isFunction(digest)
callback = digest
digest = `undefined`
throw new Error("No callback provided to pbkdf2") unless util.isFunction(callback)
pbkdf2 password, salt, iterations, keylen, digest, callback
exports.pbkdf2Sync = (password, salt, iterations, keylen, digest) ->
pbkdf2 password, salt, iterations, keylen, digest
exports.Certificate = Certificate
Certificate::verifySpkac = (object) ->
@_handle.verifySpkac object
Certificate::exportPublicKey = (object, encoding) ->
@_handle.exportPublicKey toBuf(object, encoding)
Certificate::exportChallenge = (object, encoding) ->
@_handle.exportChallenge toBuf(object, encoding)
exports.setEngine = setEngine = (id, flags) ->
throw new TypeError("id should be a string") unless util.isString(id)
throw new TypeError("flags should be a number, if present") if flags and not util.isNumber(flags)
flags = flags >>> 0
flags = constants.ENGINE_METHOD_ALL if flags is 0
binding.setEngine id, flags
exports.randomBytes = randomBytes
exports.pseudoRandomBytes = pseudoRandomBytes
exports.rng = randomBytes
exports.prng = pseudoRandomBytes
exports.getCiphers = ->
filterDuplicates getCiphers.call(null, arguments)
exports.getHashes = ->
filterDuplicates getHashes.call(null, arguments)
# Legacy API
exports.__defineGetter__ "createCredentials", util.deprecate(->
require("tls").createSecureContext
, "createCredentials() is deprecated, use tls.createSecureContext instead")
exports.__defineGetter__ "Credentials", util.deprecate(->
require("tls").SecureContext
, "Credentials is deprecated, use tls.createSecureContext instead")
| 27557 | # Copyright <NAME>, Inc. and other Node contributors.
#
# 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.
# Note: In 0.8 and before, crypto functions all defaulted to using
# binary-encoded strings rather than buffers.
# This is here because many functions accepted binary strings without
# any explicit encoding in older versions of node, and we don't want
# to break them unnecessarily.
toBuf = (str, encoding) ->
encoding = encoding or "binary"
if util.isString(str)
encoding = "binary" if encoding is "buffer"
str = new Buffer(str, encoding)
str
LazyTransform = (options) ->
@_options = options
return
Hash = (algorithm, options) ->
return new Hash(algorithm, options) unless this instanceof Hash
@_handle = new binding.Hash(algorithm)
LazyTransform.call this, options
return
Hmac = (hmac, key, options) ->
return new Hmac(hmac, key, options) unless this instanceof Hmac
@_handle = new binding.Hmac()
@_handle.init hmac, toBuf(key)
LazyTransform.call this, options
return
getDecoder = (decoder, encoding) ->
encoding = "utf8" if encoding is "utf-8" # Normalize encoding.
decoder = decoder or new StringDecoder(encoding)
assert decoder.encoding is encoding, "Cannot change encoding"
decoder
Cipher = (cipher, password, options) ->
return new Cipher(cipher, password, options) unless this instanceof Cipher
@_handle = new binding.CipherBase(true)
@_handle.init cipher, toBuf(password)
@_decoder = null
LazyTransform.call this, options
return
Cipheriv = (cipher, key, iv, options) ->
return new Cipheriv(cipher, key, iv, options) unless this instanceof Cipheriv
@_handle = new binding.CipherBase(true)
@_handle.initiv cipher, toBuf(key), toBuf(iv)
@_decoder = null
LazyTransform.call this, options
return
Decipher = (cipher, password, options) ->
return new Decipher(cipher, password, options) unless this instanceof Decipher
@_handle = new binding.CipherBase(false)
@_handle.init cipher, toBuf(password)
@_decoder = null
LazyTransform.call this, options
return
Decipheriv = (cipher, key, iv, options) ->
return new Decipheriv(cipher, key, iv, options) unless this instanceof Decipheriv
@_handle = new binding.CipherBase(false)
@_handle.initiv cipher, toBuf(key), toBuf(iv)
@_decoder = null
LazyTransform.call this, options
return
Sign = (algorithm, options) ->
return new Sign(algorithm, options) unless this instanceof Sign
@_handle = new binding.Sign()
@_handle.init algorithm
stream.Writable.call this, options
return
Verify = (algorithm, options) ->
return new Verify(algorithm, options) unless this instanceof Verify
@_handle = new binding.Verify
@_handle.init algorithm
stream.Writable.call this, options
return
DiffieHellman = (sizeOrKey, keyEncoding, generator, genEncoding) ->
return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) unless this instanceof DiffieHellman
throw new TypeError("First argument should be number, string or Buffer") if not util.isBuffer(sizeOrKey) and typeof sizeOrKey isnt "number" and typeof sizeOrKey isnt "string"
if keyEncoding
if typeof keyEncoding isnt "string" or (not Buffer.isEncoding(keyEncoding) and keyEncoding isnt "buffer")
genEncoding = generator
generator = keyEncoding
keyEncoding = false
keyEncoding = keyEncoding or exports.DEFAULT_ENCODING
genEncoding = genEncoding or exports.DEFAULT_ENCODING
sizeOrKey = toBuf(sizeOrKey, keyEncoding) if typeof sizeOrKey isnt "number"
unless generator
generator = DH_GENERATOR
else generator = toBuf(generator, genEncoding) if typeof generator isnt "number"
@_handle = new binding.DiffieHellman(sizeOrKey, generator)
Object.defineProperty this, "verifyError",
enumerable: true
value: @_handle.verifyError
writable: false
return
DiffieHellmanGroup = (name) ->
return new DiffieHellmanGroup(name) unless this instanceof DiffieHellmanGroup
@_handle = new binding.DiffieHellmanGroup(name)
Object.defineProperty this, "verifyError",
enumerable: true
value: @_handle.verifyError
writable: false
return
dhGenerateKeys = (encoding) ->
keys = @_handle.generateKeys()
encoding = encoding or exports.DEFAULT_ENCODING
keys = keys.toString(encoding) if encoding and encoding isnt "buffer"
keys
dhComputeSecret = (key, inEnc, outEnc) ->
inEnc = inEnc or exports.DEFAULT_ENCODING
outEnc = outEnc or exports.DEFAULT_ENCODING
ret = @_handle.computeSecret(toBuf(key, inEnc))
ret = ret.toString(outEnc) if outEnc and outEnc isnt "buffer"
ret
dhGetPrime = (encoding) ->
prime = @_handle.getPrime()
encoding = encoding or exports.DEFAULT_ENCODING
prime = prime.toString(encoding) if encoding and encoding isnt "buffer"
prime
dhGetGenerator = (encoding) ->
generator = @_handle.getGenerator()
encoding = encoding or exports.DEFAULT_ENCODING
generator = generator.toString(encoding) if encoding and encoding isnt "buffer"
generator
dhGetPublicKey = (encoding) ->
key = @_handle.getPublicKey()
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
dhGetPrivateKey = (encoding) ->
key = @_handle.getPrivateKey()
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
ECDH = (curve) ->
throw new TypeError("curve should be a string") unless util.isString(curve)
@_handle = new binding.ECDH(curve)
return
# Default
pbkdf2 = (password, salt, iterations, keylen, digest, callback) ->
password = toBuf(password)
salt = toBuf(salt)
return binding.PBKDF2(password, salt, iterations, keylen, digest, callback) if exports.DEFAULT_ENCODING is "buffer"
# at this point, we need to handle encodings.
encoding = exports.DEFAULT_ENCODING
if callback
next = (er, ret) ->
ret = ret.toString(encoding) if ret
callback er, ret
return
binding.PBKDF2 password, salt, iterations, keylen, digest, next
else
ret = binding.PBKDF2(password, salt, iterations, keylen, digest)
ret.toString encoding
return
Certificate = ->
return new Certificate() unless this instanceof Certificate
@_handle = new binding.Certificate()
return
# Use provided engine for everything by default
filterDuplicates = (names) ->
# Drop all-caps names in favor of their lowercase aliases,
# for example, 'sha1' instead of 'SHA1'.
ctx = {}
names.forEach (name) ->
key = name
key = key.toLowerCase() if /^[0-9A-Z\-]+$/.test(key)
ctx[key] = name if not ctx.hasOwnProperty(key) or ctx[key] < name
return
Object.getOwnPropertyNames(ctx).map((key) ->
ctx[key]
).sort()
"use strict"
exports.DEFAULT_ENCODING = "buffer"
try
binding = process.binding("crypto")
randomBytes = binding.randomBytes
pseudoRandomBytes = binding.pseudoRandomBytes
getCiphers = binding.getCiphers
getHashes = binding.getHashes
catch e
throw new Error("node.js not compiled with openssl crypto support.")
constants = require("constants")
stream = require("stream")
util = require("util")
DH_GENERATOR = 2
exports._toBuf = toBuf
assert = require("assert")
StringDecoder = require("string_decoder").StringDecoder
util.inherits LazyTransform, stream.Transform
[
"_readableState"
"_writableState"
"_transformState"
].forEach (prop, i, props) ->
Object.defineProperty LazyTransform::, prop,
get: ->
stream.Transform.call this, @_options
@_writableState.decodeStrings = false
@_writableState.defaultEncoding = "binary"
this[prop]
set: (val) ->
Object.defineProperty this, prop,
value: val
enumerable: true
configurable: true
writable: true
return
configurable: true
enumerable: true
return
exports.createHash = exports.Hash = Hash
util.inherits Hash, LazyTransform
Hash::_transform = (chunk, encoding, callback) ->
@_handle.update chunk, encoding
callback()
return
Hash::_flush = (callback) ->
encoding = @_readableState.encoding or "buffer"
@push @_handle.digest(encoding), encoding
callback()
return
Hash::update = (data, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
encoding = "binary" if encoding is "buffer" and util.isString(data)
@_handle.update data, encoding
this
Hash::digest = (outputEncoding) ->
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
@_handle.digest outputEncoding
exports.createHmac = exports.Hmac = Hmac
util.inherits Hmac, LazyTransform
Hmac::update = Hash::update
Hmac::digest = Hash::digest
Hmac::_flush = Hash::_flush
Hmac::_transform = Hash::_transform
exports.createCipher = exports.Cipher = Cipher
util.inherits Cipher, LazyTransform
Cipher::_transform = (chunk, encoding, callback) ->
@push @_handle.update(chunk, encoding)
callback()
return
Cipher::_flush = (callback) ->
try
@push @_handle.final()
catch e
callback e
return
callback()
return
Cipher::update = (data, inputEncoding, outputEncoding) ->
inputEncoding = inputEncoding or exports.DEFAULT_ENCODING
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
ret = @_handle.update(data, inputEncoding)
if outputEncoding and outputEncoding isnt "buffer"
@_decoder = getDecoder(@_decoder, outputEncoding)
ret = @_decoder.write(ret)
ret
Cipher::final = (outputEncoding) ->
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
ret = @_handle.final()
if outputEncoding and outputEncoding isnt "buffer"
@_decoder = getDecoder(@_decoder, outputEncoding)
ret = @_decoder.end(ret)
ret
Cipher::setAutoPadding = (ap) ->
@_handle.setAutoPadding ap
this
Cipher::getAuthTag = ->
@_handle.getAuthTag()
Cipher::setAuthTag = (tagbuf) ->
@_handle.setAuthTag tagbuf
return
Cipher::setAAD = (aadbuf) ->
@_handle.setAAD aadbuf
return
exports.createCipheriv = exports.Cipheriv = Cipheriv
util.inherits Cipheriv, LazyTransform
Cipheriv::_transform = Cipher::_transform
Cipheriv::_flush = Cipher::_flush
Cipheriv::update = Cipher::update
Cipheriv::final = Cipher::final
Cipheriv::setAutoPadding = Cipher::setAutoPadding
Cipheriv::getAuthTag = Cipher::getAuthTag
Cipheriv::setAuthTag = Cipher::setAuthTag
Cipheriv::setAAD = Cipher::setAAD
exports.createDecipher = exports.Decipher = Decipher
util.inherits Decipher, LazyTransform
Decipher::_transform = Cipher::_transform
Decipher::_flush = Cipher::_flush
Decipher::update = Cipher::update
Decipher::final = Cipher::final
Decipher::finaltol = Cipher::final
Decipher::setAutoPadding = Cipher::setAutoPadding
Decipher::getAuthTag = Cipher::getAuthTag
Decipher::setAuthTag = Cipher::setAuthTag
Decipher::setAAD = Cipher::setAAD
exports.createDecipheriv = exports.Decipheriv = Decipheriv
util.inherits Decipheriv, LazyTransform
Decipheriv::_transform = Cipher::_transform
Decipheriv::_flush = Cipher::_flush
Decipheriv::update = Cipher::update
Decipheriv::final = Cipher::final
Decipheriv::finaltol = Cipher::final
Decipheriv::setAutoPadding = Cipher::setAutoPadding
Decipheriv::getAuthTag = Cipher::getAuthTag
Decipheriv::setAuthTag = Cipher::setAuthTag
Decipheriv::setAAD = Cipher::setAAD
exports.createSign = exports.Sign = Sign
util.inherits Sign, stream.Writable
Sign::_write = (chunk, encoding, callback) ->
@_handle.update chunk, encoding
callback()
return
Sign::update = Hash::update
Sign::sign = (options, encoding) ->
throw new Error("No key provided to sign") unless options
key = options.key or options
passphrase = options.passphrase or null
ret = @_handle.sign(toBuf(key), null, passphrase)
encoding = encoding or exports.DEFAULT_ENCODING
ret = ret.toString(encoding) if encoding and encoding isnt "buffer"
ret
exports.createVerify = exports.Verify = Verify
util.inherits Verify, stream.Writable
Verify::_write = Sign::_write
Verify::update = Sign::update
Verify::verify = (object, signature, sigEncoding) ->
sigEncoding = sigEncoding or exports.DEFAULT_ENCODING
@_handle.verify toBuf(object), toBuf(signature, sigEncoding)
exports.publicEncrypt = (options, buffer) ->
key = options.key or options
padding = options.padding or constants.RSA_PKCS1_OAEP_PADDING
binding.publicEncrypt toBuf(key), buffer, padding
exports.privateDecrypt = (options, buffer) ->
key = options.key or options
passphrase = options.passphrase or null
padding = options.padding or constants.RSA_PKCS1_OAEP_PADDING
binding.privateDecrypt toBuf(key), buffer, padding, passphrase
exports.createDiffieHellman = exports.DiffieHellman = DiffieHellman
exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = DiffieHellmanGroup
DiffieHellmanGroup::generateKeys = DiffieHellman::generateKeys = dhGenerateKeys
DiffieHellmanGroup::computeSecret = DiffieHellman::computeSecret = dhComputeSecret
DiffieHellmanGroup::getPrime = DiffieHellman::getPrime = dhGetPrime
DiffieHellmanGroup::getGenerator = DiffieHellman::getGenerator = dhGetGenerator
DiffieHellmanGroup::getPublicKey = DiffieHellman::getPublicKey = dhGetPublicKey
DiffieHellmanGroup::getPrivateKey = DiffieHellman::getPrivateKey = dhGetPrivateKey
DiffieHellman::setPublicKey = (key, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
@_handle.setPublicKey toBuf(key, encoding)
this
DiffieHellman::setPrivateKey = (key, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
@_handle.setPrivateKey toBuf(key, encoding)
this
exports.createECDH = createECDH = (curve) ->
new ECDH(curve)
ECDH::computeSecret = DiffieHellman::computeSecret
ECDH::setPrivateKey = DiffieHellman::setPrivateKey
ECDH::setPublicKey = DiffieHellman::setPublicKey
ECDH::getPrivateKey = DiffieHellman::getPrivateKey
ECDH::generateKeys = generateKeys = (encoding, format) ->
@_handle.generateKeys()
@getPublicKey encoding, format
ECDH::getPublicKey = getPublicKey = (encoding, format) ->
f = undefined
if format
f = format if typeof format is "number"
if format is "compressed"
f = constants.POINT_CONVERSION_COMPRESSED
else if format is "hybrid"
f = constants.POINT_CONVERSION_HYBRID
else if format is "uncompressed"
f = constants.POINT_CONVERSION_UNCOMPRESSED
else
throw TypeError("Bad format: " + format)
else
f = constants.POINT_CONVERSION_UNCOMPRESSED
key = @_handle.getPublicKey(f)
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
exports.pbkdf2 = (password, salt, iterations, keylen, digest, callback) ->
if util.isFunction(digest)
callback = digest
digest = `undefined`
throw new Error("No callback provided to pbkdf2") unless util.isFunction(callback)
pbkdf2 password, salt, iterations, keylen, digest, callback
exports.pbkdf2Sync = (password, salt, iterations, keylen, digest) ->
pbkdf2 password, salt, iterations, keylen, digest
exports.Certificate = Certificate
Certificate::verifySpkac = (object) ->
@_handle.verifySpkac object
Certificate::exportPublicKey = (object, encoding) ->
@_handle.exportPublicKey toBuf(object, encoding)
Certificate::exportChallenge = (object, encoding) ->
@_handle.exportChallenge toBuf(object, encoding)
exports.setEngine = setEngine = (id, flags) ->
throw new TypeError("id should be a string") unless util.isString(id)
throw new TypeError("flags should be a number, if present") if flags and not util.isNumber(flags)
flags = flags >>> 0
flags = constants.ENGINE_METHOD_ALL if flags is 0
binding.setEngine id, flags
exports.randomBytes = randomBytes
exports.pseudoRandomBytes = pseudoRandomBytes
exports.rng = randomBytes
exports.prng = pseudoRandomBytes
exports.getCiphers = ->
filterDuplicates getCiphers.call(null, arguments)
exports.getHashes = ->
filterDuplicates getHashes.call(null, arguments)
# Legacy API
exports.__defineGetter__ "createCredentials", util.deprecate(->
require("tls").createSecureContext
, "createCredentials() is deprecated, use tls.createSecureContext instead")
exports.__defineGetter__ "Credentials", util.deprecate(->
require("tls").SecureContext
, "Credentials is deprecated, use tls.createSecureContext instead")
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# 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.
# Note: In 0.8 and before, crypto functions all defaulted to using
# binary-encoded strings rather than buffers.
# This is here because many functions accepted binary strings without
# any explicit encoding in older versions of node, and we don't want
# to break them unnecessarily.
toBuf = (str, encoding) ->
encoding = encoding or "binary"
if util.isString(str)
encoding = "binary" if encoding is "buffer"
str = new Buffer(str, encoding)
str
LazyTransform = (options) ->
@_options = options
return
Hash = (algorithm, options) ->
return new Hash(algorithm, options) unless this instanceof Hash
@_handle = new binding.Hash(algorithm)
LazyTransform.call this, options
return
Hmac = (hmac, key, options) ->
return new Hmac(hmac, key, options) unless this instanceof Hmac
@_handle = new binding.Hmac()
@_handle.init hmac, toBuf(key)
LazyTransform.call this, options
return
getDecoder = (decoder, encoding) ->
encoding = "utf8" if encoding is "utf-8" # Normalize encoding.
decoder = decoder or new StringDecoder(encoding)
assert decoder.encoding is encoding, "Cannot change encoding"
decoder
Cipher = (cipher, password, options) ->
return new Cipher(cipher, password, options) unless this instanceof Cipher
@_handle = new binding.CipherBase(true)
@_handle.init cipher, toBuf(password)
@_decoder = null
LazyTransform.call this, options
return
Cipheriv = (cipher, key, iv, options) ->
return new Cipheriv(cipher, key, iv, options) unless this instanceof Cipheriv
@_handle = new binding.CipherBase(true)
@_handle.initiv cipher, toBuf(key), toBuf(iv)
@_decoder = null
LazyTransform.call this, options
return
Decipher = (cipher, password, options) ->
return new Decipher(cipher, password, options) unless this instanceof Decipher
@_handle = new binding.CipherBase(false)
@_handle.init cipher, toBuf(password)
@_decoder = null
LazyTransform.call this, options
return
Decipheriv = (cipher, key, iv, options) ->
return new Decipheriv(cipher, key, iv, options) unless this instanceof Decipheriv
@_handle = new binding.CipherBase(false)
@_handle.initiv cipher, toBuf(key), toBuf(iv)
@_decoder = null
LazyTransform.call this, options
return
Sign = (algorithm, options) ->
return new Sign(algorithm, options) unless this instanceof Sign
@_handle = new binding.Sign()
@_handle.init algorithm
stream.Writable.call this, options
return
Verify = (algorithm, options) ->
return new Verify(algorithm, options) unless this instanceof Verify
@_handle = new binding.Verify
@_handle.init algorithm
stream.Writable.call this, options
return
DiffieHellman = (sizeOrKey, keyEncoding, generator, genEncoding) ->
return new DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) unless this instanceof DiffieHellman
throw new TypeError("First argument should be number, string or Buffer") if not util.isBuffer(sizeOrKey) and typeof sizeOrKey isnt "number" and typeof sizeOrKey isnt "string"
if keyEncoding
if typeof keyEncoding isnt "string" or (not Buffer.isEncoding(keyEncoding) and keyEncoding isnt "buffer")
genEncoding = generator
generator = keyEncoding
keyEncoding = false
keyEncoding = keyEncoding or exports.DEFAULT_ENCODING
genEncoding = genEncoding or exports.DEFAULT_ENCODING
sizeOrKey = toBuf(sizeOrKey, keyEncoding) if typeof sizeOrKey isnt "number"
unless generator
generator = DH_GENERATOR
else generator = toBuf(generator, genEncoding) if typeof generator isnt "number"
@_handle = new binding.DiffieHellman(sizeOrKey, generator)
Object.defineProperty this, "verifyError",
enumerable: true
value: @_handle.verifyError
writable: false
return
DiffieHellmanGroup = (name) ->
return new DiffieHellmanGroup(name) unless this instanceof DiffieHellmanGroup
@_handle = new binding.DiffieHellmanGroup(name)
Object.defineProperty this, "verifyError",
enumerable: true
value: @_handle.verifyError
writable: false
return
dhGenerateKeys = (encoding) ->
keys = @_handle.generateKeys()
encoding = encoding or exports.DEFAULT_ENCODING
keys = keys.toString(encoding) if encoding and encoding isnt "buffer"
keys
dhComputeSecret = (key, inEnc, outEnc) ->
inEnc = inEnc or exports.DEFAULT_ENCODING
outEnc = outEnc or exports.DEFAULT_ENCODING
ret = @_handle.computeSecret(toBuf(key, inEnc))
ret = ret.toString(outEnc) if outEnc and outEnc isnt "buffer"
ret
dhGetPrime = (encoding) ->
prime = @_handle.getPrime()
encoding = encoding or exports.DEFAULT_ENCODING
prime = prime.toString(encoding) if encoding and encoding isnt "buffer"
prime
dhGetGenerator = (encoding) ->
generator = @_handle.getGenerator()
encoding = encoding or exports.DEFAULT_ENCODING
generator = generator.toString(encoding) if encoding and encoding isnt "buffer"
generator
dhGetPublicKey = (encoding) ->
key = @_handle.getPublicKey()
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
dhGetPrivateKey = (encoding) ->
key = @_handle.getPrivateKey()
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
ECDH = (curve) ->
throw new TypeError("curve should be a string") unless util.isString(curve)
@_handle = new binding.ECDH(curve)
return
# Default
pbkdf2 = (password, salt, iterations, keylen, digest, callback) ->
password = toBuf(password)
salt = toBuf(salt)
return binding.PBKDF2(password, salt, iterations, keylen, digest, callback) if exports.DEFAULT_ENCODING is "buffer"
# at this point, we need to handle encodings.
encoding = exports.DEFAULT_ENCODING
if callback
next = (er, ret) ->
ret = ret.toString(encoding) if ret
callback er, ret
return
binding.PBKDF2 password, salt, iterations, keylen, digest, next
else
ret = binding.PBKDF2(password, salt, iterations, keylen, digest)
ret.toString encoding
return
Certificate = ->
return new Certificate() unless this instanceof Certificate
@_handle = new binding.Certificate()
return
# Use provided engine for everything by default
filterDuplicates = (names) ->
# Drop all-caps names in favor of their lowercase aliases,
# for example, 'sha1' instead of 'SHA1'.
ctx = {}
names.forEach (name) ->
key = name
key = key.toLowerCase() if /^[0-9A-Z\-]+$/.test(key)
ctx[key] = name if not ctx.hasOwnProperty(key) or ctx[key] < name
return
Object.getOwnPropertyNames(ctx).map((key) ->
ctx[key]
).sort()
"use strict"
exports.DEFAULT_ENCODING = "buffer"
try
binding = process.binding("crypto")
randomBytes = binding.randomBytes
pseudoRandomBytes = binding.pseudoRandomBytes
getCiphers = binding.getCiphers
getHashes = binding.getHashes
catch e
throw new Error("node.js not compiled with openssl crypto support.")
constants = require("constants")
stream = require("stream")
util = require("util")
DH_GENERATOR = 2
exports._toBuf = toBuf
assert = require("assert")
StringDecoder = require("string_decoder").StringDecoder
util.inherits LazyTransform, stream.Transform
[
"_readableState"
"_writableState"
"_transformState"
].forEach (prop, i, props) ->
Object.defineProperty LazyTransform::, prop,
get: ->
stream.Transform.call this, @_options
@_writableState.decodeStrings = false
@_writableState.defaultEncoding = "binary"
this[prop]
set: (val) ->
Object.defineProperty this, prop,
value: val
enumerable: true
configurable: true
writable: true
return
configurable: true
enumerable: true
return
exports.createHash = exports.Hash = Hash
util.inherits Hash, LazyTransform
Hash::_transform = (chunk, encoding, callback) ->
@_handle.update chunk, encoding
callback()
return
Hash::_flush = (callback) ->
encoding = @_readableState.encoding or "buffer"
@push @_handle.digest(encoding), encoding
callback()
return
Hash::update = (data, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
encoding = "binary" if encoding is "buffer" and util.isString(data)
@_handle.update data, encoding
this
Hash::digest = (outputEncoding) ->
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
@_handle.digest outputEncoding
exports.createHmac = exports.Hmac = Hmac
util.inherits Hmac, LazyTransform
Hmac::update = Hash::update
Hmac::digest = Hash::digest
Hmac::_flush = Hash::_flush
Hmac::_transform = Hash::_transform
exports.createCipher = exports.Cipher = Cipher
util.inherits Cipher, LazyTransform
Cipher::_transform = (chunk, encoding, callback) ->
@push @_handle.update(chunk, encoding)
callback()
return
Cipher::_flush = (callback) ->
try
@push @_handle.final()
catch e
callback e
return
callback()
return
Cipher::update = (data, inputEncoding, outputEncoding) ->
inputEncoding = inputEncoding or exports.DEFAULT_ENCODING
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
ret = @_handle.update(data, inputEncoding)
if outputEncoding and outputEncoding isnt "buffer"
@_decoder = getDecoder(@_decoder, outputEncoding)
ret = @_decoder.write(ret)
ret
Cipher::final = (outputEncoding) ->
outputEncoding = outputEncoding or exports.DEFAULT_ENCODING
ret = @_handle.final()
if outputEncoding and outputEncoding isnt "buffer"
@_decoder = getDecoder(@_decoder, outputEncoding)
ret = @_decoder.end(ret)
ret
Cipher::setAutoPadding = (ap) ->
@_handle.setAutoPadding ap
this
Cipher::getAuthTag = ->
@_handle.getAuthTag()
Cipher::setAuthTag = (tagbuf) ->
@_handle.setAuthTag tagbuf
return
Cipher::setAAD = (aadbuf) ->
@_handle.setAAD aadbuf
return
exports.createCipheriv = exports.Cipheriv = Cipheriv
util.inherits Cipheriv, LazyTransform
Cipheriv::_transform = Cipher::_transform
Cipheriv::_flush = Cipher::_flush
Cipheriv::update = Cipher::update
Cipheriv::final = Cipher::final
Cipheriv::setAutoPadding = Cipher::setAutoPadding
Cipheriv::getAuthTag = Cipher::getAuthTag
Cipheriv::setAuthTag = Cipher::setAuthTag
Cipheriv::setAAD = Cipher::setAAD
exports.createDecipher = exports.Decipher = Decipher
util.inherits Decipher, LazyTransform
Decipher::_transform = Cipher::_transform
Decipher::_flush = Cipher::_flush
Decipher::update = Cipher::update
Decipher::final = Cipher::final
Decipher::finaltol = Cipher::final
Decipher::setAutoPadding = Cipher::setAutoPadding
Decipher::getAuthTag = Cipher::getAuthTag
Decipher::setAuthTag = Cipher::setAuthTag
Decipher::setAAD = Cipher::setAAD
exports.createDecipheriv = exports.Decipheriv = Decipheriv
util.inherits Decipheriv, LazyTransform
Decipheriv::_transform = Cipher::_transform
Decipheriv::_flush = Cipher::_flush
Decipheriv::update = Cipher::update
Decipheriv::final = Cipher::final
Decipheriv::finaltol = Cipher::final
Decipheriv::setAutoPadding = Cipher::setAutoPadding
Decipheriv::getAuthTag = Cipher::getAuthTag
Decipheriv::setAuthTag = Cipher::setAuthTag
Decipheriv::setAAD = Cipher::setAAD
exports.createSign = exports.Sign = Sign
util.inherits Sign, stream.Writable
Sign::_write = (chunk, encoding, callback) ->
@_handle.update chunk, encoding
callback()
return
Sign::update = Hash::update
Sign::sign = (options, encoding) ->
throw new Error("No key provided to sign") unless options
key = options.key or options
passphrase = options.passphrase or null
ret = @_handle.sign(toBuf(key), null, passphrase)
encoding = encoding or exports.DEFAULT_ENCODING
ret = ret.toString(encoding) if encoding and encoding isnt "buffer"
ret
exports.createVerify = exports.Verify = Verify
util.inherits Verify, stream.Writable
Verify::_write = Sign::_write
Verify::update = Sign::update
Verify::verify = (object, signature, sigEncoding) ->
sigEncoding = sigEncoding or exports.DEFAULT_ENCODING
@_handle.verify toBuf(object), toBuf(signature, sigEncoding)
exports.publicEncrypt = (options, buffer) ->
key = options.key or options
padding = options.padding or constants.RSA_PKCS1_OAEP_PADDING
binding.publicEncrypt toBuf(key), buffer, padding
exports.privateDecrypt = (options, buffer) ->
key = options.key or options
passphrase = options.passphrase or null
padding = options.padding or constants.RSA_PKCS1_OAEP_PADDING
binding.privateDecrypt toBuf(key), buffer, padding, passphrase
exports.createDiffieHellman = exports.DiffieHellman = DiffieHellman
exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = DiffieHellmanGroup
DiffieHellmanGroup::generateKeys = DiffieHellman::generateKeys = dhGenerateKeys
DiffieHellmanGroup::computeSecret = DiffieHellman::computeSecret = dhComputeSecret
DiffieHellmanGroup::getPrime = DiffieHellman::getPrime = dhGetPrime
DiffieHellmanGroup::getGenerator = DiffieHellman::getGenerator = dhGetGenerator
DiffieHellmanGroup::getPublicKey = DiffieHellman::getPublicKey = dhGetPublicKey
DiffieHellmanGroup::getPrivateKey = DiffieHellman::getPrivateKey = dhGetPrivateKey
DiffieHellman::setPublicKey = (key, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
@_handle.setPublicKey toBuf(key, encoding)
this
DiffieHellman::setPrivateKey = (key, encoding) ->
encoding = encoding or exports.DEFAULT_ENCODING
@_handle.setPrivateKey toBuf(key, encoding)
this
exports.createECDH = createECDH = (curve) ->
new ECDH(curve)
ECDH::computeSecret = DiffieHellman::computeSecret
ECDH::setPrivateKey = DiffieHellman::setPrivateKey
ECDH::setPublicKey = DiffieHellman::setPublicKey
ECDH::getPrivateKey = DiffieHellman::getPrivateKey
ECDH::generateKeys = generateKeys = (encoding, format) ->
@_handle.generateKeys()
@getPublicKey encoding, format
ECDH::getPublicKey = getPublicKey = (encoding, format) ->
f = undefined
if format
f = format if typeof format is "number"
if format is "compressed"
f = constants.POINT_CONVERSION_COMPRESSED
else if format is "hybrid"
f = constants.POINT_CONVERSION_HYBRID
else if format is "uncompressed"
f = constants.POINT_CONVERSION_UNCOMPRESSED
else
throw TypeError("Bad format: " + format)
else
f = constants.POINT_CONVERSION_UNCOMPRESSED
key = @_handle.getPublicKey(f)
encoding = encoding or exports.DEFAULT_ENCODING
key = key.toString(encoding) if encoding and encoding isnt "buffer"
key
exports.pbkdf2 = (password, salt, iterations, keylen, digest, callback) ->
if util.isFunction(digest)
callback = digest
digest = `undefined`
throw new Error("No callback provided to pbkdf2") unless util.isFunction(callback)
pbkdf2 password, salt, iterations, keylen, digest, callback
exports.pbkdf2Sync = (password, salt, iterations, keylen, digest) ->
pbkdf2 password, salt, iterations, keylen, digest
exports.Certificate = Certificate
Certificate::verifySpkac = (object) ->
@_handle.verifySpkac object
Certificate::exportPublicKey = (object, encoding) ->
@_handle.exportPublicKey toBuf(object, encoding)
Certificate::exportChallenge = (object, encoding) ->
@_handle.exportChallenge toBuf(object, encoding)
exports.setEngine = setEngine = (id, flags) ->
throw new TypeError("id should be a string") unless util.isString(id)
throw new TypeError("flags should be a number, if present") if flags and not util.isNumber(flags)
flags = flags >>> 0
flags = constants.ENGINE_METHOD_ALL if flags is 0
binding.setEngine id, flags
exports.randomBytes = randomBytes
exports.pseudoRandomBytes = pseudoRandomBytes
exports.rng = randomBytes
exports.prng = pseudoRandomBytes
exports.getCiphers = ->
filterDuplicates getCiphers.call(null, arguments)
exports.getHashes = ->
filterDuplicates getHashes.call(null, arguments)
# Legacy API
exports.__defineGetter__ "createCredentials", util.deprecate(->
require("tls").createSecureContext
, "createCredentials() is deprecated, use tls.createSecureContext instead")
exports.__defineGetter__ "Credentials", util.deprecate(->
require("tls").SecureContext
, "Credentials is deprecated, use tls.createSecureContext instead")
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9990475177764893,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-sigint-infinite-loop.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# 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.
# This test is to assert that we can SIGINT a script which loops forever.
# Ref(http):
# groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
console.log "start"
c = spawn(process.execPath, [
"-e"
"while(true) { console.log(\"hi\"); }"
])
sentKill = false
gotChildExit = true
c.stdout.on "data", (s) ->
# Prevent race condition:
# Wait for the first bit of output from the child process
# so that we're sure that it's in the V8 event loop and not
# just in the startup phase of execution.
unless sentKill
c.kill "SIGINT"
console.log "SIGINT infinite-loop.js"
sentKill = true
return
c.on "exit", (code) ->
assert.ok code isnt 0
console.log "killed infinite-loop.js"
gotChildExit = true
return
process.on "exit", ->
assert.ok sentKill
assert.ok gotChildExit
return
| 177500 | # Copyright <NAME>, Inc. and other Node contributors.
#
# 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.
# This test is to assert that we can SIGINT a script which loops forever.
# Ref(http):
# groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
console.log "start"
c = spawn(process.execPath, [
"-e"
"while(true) { console.log(\"hi\"); }"
])
sentKill = false
gotChildExit = true
c.stdout.on "data", (s) ->
# Prevent race condition:
# Wait for the first bit of output from the child process
# so that we're sure that it's in the V8 event loop and not
# just in the startup phase of execution.
unless sentKill
c.kill "SIGINT"
console.log "SIGINT infinite-loop.js"
sentKill = true
return
c.on "exit", (code) ->
assert.ok code isnt 0
console.log "killed infinite-loop.js"
gotChildExit = true
return
process.on "exit", ->
assert.ok sentKill
assert.ok gotChildExit
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# 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.
# This test is to assert that we can SIGINT a script which loops forever.
# Ref(http):
# groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
console.log "start"
c = spawn(process.execPath, [
"-e"
"while(true) { console.log(\"hi\"); }"
])
sentKill = false
gotChildExit = true
c.stdout.on "data", (s) ->
# Prevent race condition:
# Wait for the first bit of output from the child process
# so that we're sure that it's in the V8 event loop and not
# just in the startup phase of execution.
unless sentKill
c.kill "SIGINT"
console.log "SIGINT infinite-loop.js"
sentKill = true
return
c.on "exit", (code) ->
assert.ok code isnt 0
console.log "killed infinite-loop.js"
gotChildExit = true
return
process.on "exit", ->
assert.ok sentKill
assert.ok gotChildExit
return
|
[
{
"context": "on data bare', ->\n houses =\n lannister: ['Tywin', 'Cersei', 'Tyrion', 'Jaimie']\n baratheon: ",
"end": 204,
"score": 0.9997936487197876,
"start": 199,
"tag": "NAME",
"value": "Tywin"
},
{
"context": "are', ->\n houses =\n lannister: ['Tywin', 'Cer... | test/hypermedia-formats/bare.coffee | OpenCubes/Nap | 1 | bare = require '../../lib/hypermedia-formats/bare'
should = require('chai').should()
describe 'bare hypermedia formatter', ->
it 'should return json data bare', ->
houses =
lannister: ['Tywin', 'Cersei', 'Tyrion', 'Jaimie']
baratheon: ['Robert', 'Renly', 'Stannis']
stark: ['Ned', 'Catelyn', 'Sansa', 'Robb', 'Bran', 'Rickon']
bare(houses).should.deep.equal houses
| 142282 | bare = require '../../lib/hypermedia-formats/bare'
should = require('chai').should()
describe 'bare hypermedia formatter', ->
it 'should return json data bare', ->
houses =
lannister: ['<NAME>', '<NAME>', '<NAME>', '<NAME>']
baratheon: ['<NAME>', '<NAME>', '<NAME>']
stark: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']
bare(houses).should.deep.equal houses
| true | bare = require '../../lib/hypermedia-formats/bare'
should = require('chai').should()
describe 'bare hypermedia formatter', ->
it 'should return json data bare', ->
houses =
lannister: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
baratheon: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
stark: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
bare(houses).should.deep.equal houses
|
[
{
"context": "'\n 'filename'\n ]\n\n @AUTH_COMPONENTS = [\n 'username'\n 'password'\n ]\n\n @ALIAS_COMPONENTS =\n ha",
"end": 650,
"score": 0.9502048492431641,
"start": 642,
"tag": "USERNAME",
"value": "username"
},
{
"context": "onents = {}) ->\n components = {\n ... | src/lib/object/url.coffee | krokis/layla | 9 | ParseURL = require 'url'
Net = require 'net'
Path = require 'path'
URI = require './uri'
Null = require './null'
Boolean = require './boolean'
String = require './string'
QuotedString = require './string/quoted'
Number = require './number'
Error = require '../error'
ValueError = require '../error/value'
###
###
class URL extends URI
name: 'url'
@URL_COMPONENTS = [
'scheme'
'auth'
'host'
'port'
'path'
'query'
'fragment'
]
@PATH_COMPONENTS = [
'dirname'
'basename'
'extname'
'filename'
]
@AUTH_COMPONENTS = [
'username'
'password'
]
@ALIAS_COMPONENTS =
hash: 'fragment'
protocol: 'scheme'
@parseComponents: (url) ->
url = url.trim()
# TODO catch parsing errors
parsed_url = ParseURL.parse url, no, yes
return {
scheme: parsed_url.protocol and parsed_url.protocol[...-1]
auth: parsed_url.auth
host: parsed_url.hostname
port: parsed_url.port
path: parsed_url.pathname
query: parsed_url.query
fragment: parsed_url.hash and parsed_url.hash[1..]
slashes: parsed_url.slashes
}
@URL_COMPONENTS.forEach (component) ->
URL.property component, -> @components[component]
@property 'username', ->
if @auth? then @auth.split(':')[0] else null
@property 'password', ->
if @auth? then @auth.split(':')[1] else null
@property 'domain', ->
if @isIP() then null else @host
@property 'dirname', ->
if @path then Path.dirname(@path) else null
@property 'basename', ->
if @path then Path.basename(@path) else null
@property 'extname', ->
if @path then Path.extname(@path) else null
@property 'filename', ->
if @path then Path.basename(@path, @extname) else null
constructor: (components) ->
components = {components...}
if components.port?
port = parseFloat components.port
if isNaN port
throw new ValueError """
Cannot create URL with a non-numeric port: #{components.port}
"""
if port % 1 # If not integer
throw new ValueError """
Cannot create URL with a non-integer port number: #{port}
"""
unless 1 <= port <= 65535
throw new ValueError """
Cannot create URL with port `#{port}`: \
port number is out of 1..65535 range
"""
components.port = port.toString()
if components.fragment?
components.fragment = ParseURL.format components.fragment
if components.query?
components.query = ParseURL.format components.query
if components.host?
components.host = components.host.toLowerCase()
super components
isIP: ->
Net.isIP @host
makePath: (components = {}) ->
components = {
dirname: @dirname,
filename: @filename,
extname: @extname,
components...
}
components.dirname or= ''
components.filename or= ''
components.extname or= ''
components.basename ?= components.filename + components.extname
components.basename or= ''
return Path.join '/', components.dirname, components.basename
makeAuth: (components = {}) ->
components = {
username: @username,
password: @password
components...
}
if components.username?
if components.password?
"#{components.username}:#{components.password}"
else
components.username
else if components.password?
":#{components.password}"
else
null
###
Resolves another URL or string with this as the base
###
'.+': (context, other) ->
if other instanceof URL or other instanceof String
@class.parse ParseURL.resolve(@value, other.value)
else
super context, other
###
Batch define all accessors (`scheme`, `path`, `query`, etc)
###
@URL_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @components[component]
if value?
return new QuotedString value
else
return Null.null
value = if value.isNull() then null else value.toString()
return @copy [component]: value
@PATH_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @[component]
if value?
return new QuotedString value
else
return Null.null
if value.isNull()
value = null
else
try
value = value.toString()
catch e
throw e # TODO!
path = @makePath [component]: value
return @copy path: path
@AUTH_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @[component]
if value?
return new QuotedString value
else
return Null.null
if value.isNull()
value = null
else
try
value = value.toString()
catch e
throw e # TODO!
auth = @makeAuth [component]: value
return @copy auth: auth
for alias of @ALIAS_COMPONENTS
URL::[".#{alias}"] = URL::[".#{@ALIAS_COMPONENTS[alias]}"]
###
Returns `true` if the URL is a fully qualified URL, ie: it has a scheme
###
'.absolute?': ->
Boolean.new @scheme isnt null
###
Returns `true` if the URL is a relative URL, ie: it has no scheme
###
'.relative?': ->
Boolean.new @scheme is null
###
Returns `true` if the host is a v4 IP
###
'.ipv4?': ->
Boolean.new Net.isIPv4 @host
###
Returns `true` if the host is a v6 IP
###
'.ipv6?': ->
Boolean.new Net.isIPv6 @host
###
Returns `true` if the host is an IP (v4 or v6)
###
'.ip?': ->
Boolean.new @isIP()
###
Returns `true` if the URL has a host and it's not an IP address.
###
'.domain': ->
if domain = @domain
new QuotedString domain
else
Null.NULL
###
Returns a copy of the URL with the scheme set to `http`
###
'.http': ->
@copy scheme: 'http'
###
Returns a copy of the URL with the scheme set to `https`
###
'.https': ->
@copy scheme: 'https'
toString: ->
ParseURL.format {
protocol: (@scheme and "#{@scheme }:") or null
auth: @auth
host: null
hostname: @host
port: @port
pathname: @path
path: @path
search: (@query? and "?#{@query}") or null
hash: (@fragment? and "##{@fragment}") or null
slashes: !!(@host or @scheme?)
}
do ->
supah = String::['.+']
String::['.+'] = (context, other, etc...) ->
if other instanceof URL
other.class.parse ParseURL.resolve @value, other.value
else
supah.call @, context, other, etc...
module.exports = URL
| 174104 | ParseURL = require 'url'
Net = require 'net'
Path = require 'path'
URI = require './uri'
Null = require './null'
Boolean = require './boolean'
String = require './string'
QuotedString = require './string/quoted'
Number = require './number'
Error = require '../error'
ValueError = require '../error/value'
###
###
class URL extends URI
name: 'url'
@URL_COMPONENTS = [
'scheme'
'auth'
'host'
'port'
'path'
'query'
'fragment'
]
@PATH_COMPONENTS = [
'dirname'
'basename'
'extname'
'filename'
]
@AUTH_COMPONENTS = [
'username'
'password'
]
@ALIAS_COMPONENTS =
hash: 'fragment'
protocol: 'scheme'
@parseComponents: (url) ->
url = url.trim()
# TODO catch parsing errors
parsed_url = ParseURL.parse url, no, yes
return {
scheme: parsed_url.protocol and parsed_url.protocol[...-1]
auth: parsed_url.auth
host: parsed_url.hostname
port: parsed_url.port
path: parsed_url.pathname
query: parsed_url.query
fragment: parsed_url.hash and parsed_url.hash[1..]
slashes: parsed_url.slashes
}
@URL_COMPONENTS.forEach (component) ->
URL.property component, -> @components[component]
@property 'username', ->
if @auth? then @auth.split(':')[0] else null
@property 'password', ->
if @auth? then @auth.split(':')[1] else null
@property 'domain', ->
if @isIP() then null else @host
@property 'dirname', ->
if @path then Path.dirname(@path) else null
@property 'basename', ->
if @path then Path.basename(@path) else null
@property 'extname', ->
if @path then Path.extname(@path) else null
@property 'filename', ->
if @path then Path.basename(@path, @extname) else null
constructor: (components) ->
components = {components...}
if components.port?
port = parseFloat components.port
if isNaN port
throw new ValueError """
Cannot create URL with a non-numeric port: #{components.port}
"""
if port % 1 # If not integer
throw new ValueError """
Cannot create URL with a non-integer port number: #{port}
"""
unless 1 <= port <= 65535
throw new ValueError """
Cannot create URL with port `#{port}`: \
port number is out of 1..65535 range
"""
components.port = port.toString()
if components.fragment?
components.fragment = ParseURL.format components.fragment
if components.query?
components.query = ParseURL.format components.query
if components.host?
components.host = components.host.toLowerCase()
super components
isIP: ->
Net.isIP @host
makePath: (components = {}) ->
components = {
dirname: @dirname,
filename: @filename,
extname: @extname,
components...
}
components.dirname or= ''
components.filename or= ''
components.extname or= ''
components.basename ?= components.filename + components.extname
components.basename or= ''
return Path.join '/', components.dirname, components.basename
makeAuth: (components = {}) ->
components = {
username: @username,
password: <PASSWORD>
components...
}
if components.username?
if components.password?
"#{components.username}:#{components.password}"
else
components.username
else if components.password?
":#{components.password}"
else
null
###
Resolves another URL or string with this as the base
###
'.+': (context, other) ->
if other instanceof URL or other instanceof String
@class.parse ParseURL.resolve(@value, other.value)
else
super context, other
###
Batch define all accessors (`scheme`, `path`, `query`, etc)
###
@URL_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @components[component]
if value?
return new QuotedString value
else
return Null.null
value = if value.isNull() then null else value.toString()
return @copy [component]: value
@PATH_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @[component]
if value?
return new QuotedString value
else
return Null.null
if value.isNull()
value = null
else
try
value = value.toString()
catch e
throw e # TODO!
path = @makePath [component]: value
return @copy path: path
@AUTH_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @[component]
if value?
return new QuotedString value
else
return Null.null
if value.isNull()
value = null
else
try
value = value.toString()
catch e
throw e # TODO!
auth = @makeAuth [component]: value
return @copy auth: auth
for alias of @ALIAS_COMPONENTS
URL::[".#{alias}"] = URL::[".#{@ALIAS_COMPONENTS[alias]}"]
###
Returns `true` if the URL is a fully qualified URL, ie: it has a scheme
###
'.absolute?': ->
Boolean.new @scheme isnt null
###
Returns `true` if the URL is a relative URL, ie: it has no scheme
###
'.relative?': ->
Boolean.new @scheme is null
###
Returns `true` if the host is a v4 IP
###
'.ipv4?': ->
Boolean.new Net.isIPv4 @host
###
Returns `true` if the host is a v6 IP
###
'.ipv6?': ->
Boolean.new Net.isIPv6 @host
###
Returns `true` if the host is an IP (v4 or v6)
###
'.ip?': ->
Boolean.new @isIP()
###
Returns `true` if the URL has a host and it's not an IP address.
###
'.domain': ->
if domain = @domain
new QuotedString domain
else
Null.NULL
###
Returns a copy of the URL with the scheme set to `http`
###
'.http': ->
@copy scheme: 'http'
###
Returns a copy of the URL with the scheme set to `https`
###
'.https': ->
@copy scheme: 'https'
toString: ->
ParseURL.format {
protocol: (@scheme and "#{@scheme }:") or null
auth: @auth
host: null
hostname: @host
port: @port
pathname: @path
path: @path
search: (@query? and "?#{@query}") or null
hash: (@fragment? and "##{@fragment}") or null
slashes: !!(@host or @scheme?)
}
do ->
supah = String::['.+']
String::['.+'] = (context, other, etc...) ->
if other instanceof URL
other.class.parse ParseURL.resolve @value, other.value
else
supah.call @, context, other, etc...
module.exports = URL
| true | ParseURL = require 'url'
Net = require 'net'
Path = require 'path'
URI = require './uri'
Null = require './null'
Boolean = require './boolean'
String = require './string'
QuotedString = require './string/quoted'
Number = require './number'
Error = require '../error'
ValueError = require '../error/value'
###
###
class URL extends URI
name: 'url'
@URL_COMPONENTS = [
'scheme'
'auth'
'host'
'port'
'path'
'query'
'fragment'
]
@PATH_COMPONENTS = [
'dirname'
'basename'
'extname'
'filename'
]
@AUTH_COMPONENTS = [
'username'
'password'
]
@ALIAS_COMPONENTS =
hash: 'fragment'
protocol: 'scheme'
@parseComponents: (url) ->
url = url.trim()
# TODO catch parsing errors
parsed_url = ParseURL.parse url, no, yes
return {
scheme: parsed_url.protocol and parsed_url.protocol[...-1]
auth: parsed_url.auth
host: parsed_url.hostname
port: parsed_url.port
path: parsed_url.pathname
query: parsed_url.query
fragment: parsed_url.hash and parsed_url.hash[1..]
slashes: parsed_url.slashes
}
@URL_COMPONENTS.forEach (component) ->
URL.property component, -> @components[component]
@property 'username', ->
if @auth? then @auth.split(':')[0] else null
@property 'password', ->
if @auth? then @auth.split(':')[1] else null
@property 'domain', ->
if @isIP() then null else @host
@property 'dirname', ->
if @path then Path.dirname(@path) else null
@property 'basename', ->
if @path then Path.basename(@path) else null
@property 'extname', ->
if @path then Path.extname(@path) else null
@property 'filename', ->
if @path then Path.basename(@path, @extname) else null
constructor: (components) ->
components = {components...}
if components.port?
port = parseFloat components.port
if isNaN port
throw new ValueError """
Cannot create URL with a non-numeric port: #{components.port}
"""
if port % 1 # If not integer
throw new ValueError """
Cannot create URL with a non-integer port number: #{port}
"""
unless 1 <= port <= 65535
throw new ValueError """
Cannot create URL with port `#{port}`: \
port number is out of 1..65535 range
"""
components.port = port.toString()
if components.fragment?
components.fragment = ParseURL.format components.fragment
if components.query?
components.query = ParseURL.format components.query
if components.host?
components.host = components.host.toLowerCase()
super components
isIP: ->
Net.isIP @host
makePath: (components = {}) ->
components = {
dirname: @dirname,
filename: @filename,
extname: @extname,
components...
}
components.dirname or= ''
components.filename or= ''
components.extname or= ''
components.basename ?= components.filename + components.extname
components.basename or= ''
return Path.join '/', components.dirname, components.basename
makeAuth: (components = {}) ->
components = {
username: @username,
password: PI:PASSWORD:<PASSWORD>END_PI
components...
}
if components.username?
if components.password?
"#{components.username}:#{components.password}"
else
components.username
else if components.password?
":#{components.password}"
else
null
###
Resolves another URL or string with this as the base
###
'.+': (context, other) ->
if other instanceof URL or other instanceof String
@class.parse ParseURL.resolve(@value, other.value)
else
super context, other
###
Batch define all accessors (`scheme`, `path`, `query`, etc)
###
@URL_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @components[component]
if value?
return new QuotedString value
else
return Null.null
value = if value.isNull() then null else value.toString()
return @copy [component]: value
@PATH_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @[component]
if value?
return new QuotedString value
else
return Null.null
if value.isNull()
value = null
else
try
value = value.toString()
catch e
throw e # TODO!
path = @makePath [component]: value
return @copy path: path
@AUTH_COMPONENTS.forEach (component) ->
URL::[".#{component}"] = (context, value) ->
if value is undefined
value = @[component]
if value?
return new QuotedString value
else
return Null.null
if value.isNull()
value = null
else
try
value = value.toString()
catch e
throw e # TODO!
auth = @makeAuth [component]: value
return @copy auth: auth
for alias of @ALIAS_COMPONENTS
URL::[".#{alias}"] = URL::[".#{@ALIAS_COMPONENTS[alias]}"]
###
Returns `true` if the URL is a fully qualified URL, ie: it has a scheme
###
'.absolute?': ->
Boolean.new @scheme isnt null
###
Returns `true` if the URL is a relative URL, ie: it has no scheme
###
'.relative?': ->
Boolean.new @scheme is null
###
Returns `true` if the host is a v4 IP
###
'.ipv4?': ->
Boolean.new Net.isIPv4 @host
###
Returns `true` if the host is a v6 IP
###
'.ipv6?': ->
Boolean.new Net.isIPv6 @host
###
Returns `true` if the host is an IP (v4 or v6)
###
'.ip?': ->
Boolean.new @isIP()
###
Returns `true` if the URL has a host and it's not an IP address.
###
'.domain': ->
if domain = @domain
new QuotedString domain
else
Null.NULL
###
Returns a copy of the URL with the scheme set to `http`
###
'.http': ->
@copy scheme: 'http'
###
Returns a copy of the URL with the scheme set to `https`
###
'.https': ->
@copy scheme: 'https'
toString: ->
ParseURL.format {
protocol: (@scheme and "#{@scheme }:") or null
auth: @auth
host: null
hostname: @host
port: @port
pathname: @path
path: @path
search: (@query? and "?#{@query}") or null
hash: (@fragment? and "##{@fragment}") or null
slashes: !!(@host or @scheme?)
}
do ->
supah = String::['.+']
String::['.+'] = (context, other, etc...) ->
if other instanceof URL
other.class.parse ParseURL.resolve @value, other.value
else
supah.call @, context, other, etc...
module.exports = URL
|
[
{
"context": "an HTTP POST request to create a product.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass CreateAircraftP",
"end": 156,
"score": 0.9998397827148438,
"start": 144,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/specification/request/ajax/CreateAircraftProductAjaxRequest.coffee | qrefdev/qref | 0 | AjaxRequest = require('../../../serialization/AjaxRequest')
###
Object sent as the body of an HTTP POST request to create a product.
@author Nathan Klick
@copyright QRef 2012
###
class CreateAircraftProductAjaxRequest extends AjaxRequest
###
@property [String] (Required) A unique internal name for the product. Might possibly be a SKU or PN.
###
name:
type: String
required: true
###
@property [String] (Optional) A product description which will be visible on the product details screen.
###
description:
type: String
required: false
default: ''
###
@property [Boolean] (Required) A true/false value indicating whether the product is published for consumer user.
###
isPublished:
type: Boolean
required: true
default: false
###
@property [String] (Optional) An apple product code for the corresponding item in the iTunes store.
###
appleProductIdentifier:
type: String
required: false
###
@property [String] (Optional) A google product code for the corresponding item in the google play store.
###
androidProductIdentifier:
type: String
required: false
###
@property [Boolean] (Required) A true/false value indicating whether this product is available for apple devices.
###
isAppleEnabled:
type: Boolean
required: true
default: false
###
@property [Boolean] (Required) A true/false value indicating whether this product is available for android devices.
###
isAndroidEnabled:
type: Boolean
required: true
default: false
###
@property [Number] (Required) The suggested retail price for this product. Price may vary in iTunes and Google Play stores.
###
suggestedRetailPrice:
type: Number
required: true
default: 0
min: 0
max: 100.00
###
@property [String] (Required) An enumeration indicating general product category. Valid values are ['aviation', 'marine', 'navigation'].
###
productCategory:
type: String
required: true
enum: ['aviation', 'marine', 'navigation']
###
@property [String] (Required) An enumeration indicating the type of product. Valid values are ['checklist', 'manual', 'guide'].
###
productType:
type: String
required: true
enum: ['checklist', 'manual', 'guide']
###
@property [ObjectId] (Optional) An associated base checklist for aircraft products. This category represents the stock checklist that the user receives when purchasing the product.
###
aircraftChecklist:
type: ObjectId
ref: 'aircraft.checklists'
required: false
default: null
###
@property [Boolean] (Required) A true/false value indicating whether this product is a sample product which is included with the application at no charge.
###
isSampleProduct:
type: Boolean
required: true
default: false
###
@property [String] (Optional) An string indicating which aircraft, marine, or navigation serial numbers are supported by this product.
###
serialNumber:
type: String
required: false
default: null
###
@property [ObjectId] (Required) The manufacturer associated with this product.
@see AircraftManufacturerSchemaInternal
###
manufacturer:
type: ObjectId
ref: 'aircraft.manufacturers'
required: true
###
@property [ObjectId] (Required) The model associated with this product.
@see AircraftModelSchemaInternal
###
model:
type: ObjectId
ref: 'aircraft.models'
required: true
###
@property [String] (Optional) A server-based relative path to the cover artwork for this product. This path should be relative to the server root.
###
coverImage:
type: String
required: false
###
@property [String] (Optional) A server-based relative path to the icon for this product. This path should be relative to the server root.
###
productIcon:
type: String
required: false
module.exports = CreateAircraftProductAjaxRequest | 192062 | AjaxRequest = require('../../../serialization/AjaxRequest')
###
Object sent as the body of an HTTP POST request to create a product.
@author <NAME>
@copyright QRef 2012
###
class CreateAircraftProductAjaxRequest extends AjaxRequest
###
@property [String] (Required) A unique internal name for the product. Might possibly be a SKU or PN.
###
name:
type: String
required: true
###
@property [String] (Optional) A product description which will be visible on the product details screen.
###
description:
type: String
required: false
default: ''
###
@property [Boolean] (Required) A true/false value indicating whether the product is published for consumer user.
###
isPublished:
type: Boolean
required: true
default: false
###
@property [String] (Optional) An apple product code for the corresponding item in the iTunes store.
###
appleProductIdentifier:
type: String
required: false
###
@property [String] (Optional) A google product code for the corresponding item in the google play store.
###
androidProductIdentifier:
type: String
required: false
###
@property [Boolean] (Required) A true/false value indicating whether this product is available for apple devices.
###
isAppleEnabled:
type: Boolean
required: true
default: false
###
@property [Boolean] (Required) A true/false value indicating whether this product is available for android devices.
###
isAndroidEnabled:
type: Boolean
required: true
default: false
###
@property [Number] (Required) The suggested retail price for this product. Price may vary in iTunes and Google Play stores.
###
suggestedRetailPrice:
type: Number
required: true
default: 0
min: 0
max: 100.00
###
@property [String] (Required) An enumeration indicating general product category. Valid values are ['aviation', 'marine', 'navigation'].
###
productCategory:
type: String
required: true
enum: ['aviation', 'marine', 'navigation']
###
@property [String] (Required) An enumeration indicating the type of product. Valid values are ['checklist', 'manual', 'guide'].
###
productType:
type: String
required: true
enum: ['checklist', 'manual', 'guide']
###
@property [ObjectId] (Optional) An associated base checklist for aircraft products. This category represents the stock checklist that the user receives when purchasing the product.
###
aircraftChecklist:
type: ObjectId
ref: 'aircraft.checklists'
required: false
default: null
###
@property [Boolean] (Required) A true/false value indicating whether this product is a sample product which is included with the application at no charge.
###
isSampleProduct:
type: Boolean
required: true
default: false
###
@property [String] (Optional) An string indicating which aircraft, marine, or navigation serial numbers are supported by this product.
###
serialNumber:
type: String
required: false
default: null
###
@property [ObjectId] (Required) The manufacturer associated with this product.
@see AircraftManufacturerSchemaInternal
###
manufacturer:
type: ObjectId
ref: 'aircraft.manufacturers'
required: true
###
@property [ObjectId] (Required) The model associated with this product.
@see AircraftModelSchemaInternal
###
model:
type: ObjectId
ref: 'aircraft.models'
required: true
###
@property [String] (Optional) A server-based relative path to the cover artwork for this product. This path should be relative to the server root.
###
coverImage:
type: String
required: false
###
@property [String] (Optional) A server-based relative path to the icon for this product. This path should be relative to the server root.
###
productIcon:
type: String
required: false
module.exports = CreateAircraftProductAjaxRequest | true | AjaxRequest = require('../../../serialization/AjaxRequest')
###
Object sent as the body of an HTTP POST request to create a product.
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
###
class CreateAircraftProductAjaxRequest extends AjaxRequest
###
@property [String] (Required) A unique internal name for the product. Might possibly be a SKU or PN.
###
name:
type: String
required: true
###
@property [String] (Optional) A product description which will be visible on the product details screen.
###
description:
type: String
required: false
default: ''
###
@property [Boolean] (Required) A true/false value indicating whether the product is published for consumer user.
###
isPublished:
type: Boolean
required: true
default: false
###
@property [String] (Optional) An apple product code for the corresponding item in the iTunes store.
###
appleProductIdentifier:
type: String
required: false
###
@property [String] (Optional) A google product code for the corresponding item in the google play store.
###
androidProductIdentifier:
type: String
required: false
###
@property [Boolean] (Required) A true/false value indicating whether this product is available for apple devices.
###
isAppleEnabled:
type: Boolean
required: true
default: false
###
@property [Boolean] (Required) A true/false value indicating whether this product is available for android devices.
###
isAndroidEnabled:
type: Boolean
required: true
default: false
###
@property [Number] (Required) The suggested retail price for this product. Price may vary in iTunes and Google Play stores.
###
suggestedRetailPrice:
type: Number
required: true
default: 0
min: 0
max: 100.00
###
@property [String] (Required) An enumeration indicating general product category. Valid values are ['aviation', 'marine', 'navigation'].
###
productCategory:
type: String
required: true
enum: ['aviation', 'marine', 'navigation']
###
@property [String] (Required) An enumeration indicating the type of product. Valid values are ['checklist', 'manual', 'guide'].
###
productType:
type: String
required: true
enum: ['checklist', 'manual', 'guide']
###
@property [ObjectId] (Optional) An associated base checklist for aircraft products. This category represents the stock checklist that the user receives when purchasing the product.
###
aircraftChecklist:
type: ObjectId
ref: 'aircraft.checklists'
required: false
default: null
###
@property [Boolean] (Required) A true/false value indicating whether this product is a sample product which is included with the application at no charge.
###
isSampleProduct:
type: Boolean
required: true
default: false
###
@property [String] (Optional) An string indicating which aircraft, marine, or navigation serial numbers are supported by this product.
###
serialNumber:
type: String
required: false
default: null
###
@property [ObjectId] (Required) The manufacturer associated with this product.
@see AircraftManufacturerSchemaInternal
###
manufacturer:
type: ObjectId
ref: 'aircraft.manufacturers'
required: true
###
@property [ObjectId] (Required) The model associated with this product.
@see AircraftModelSchemaInternal
###
model:
type: ObjectId
ref: 'aircraft.models'
required: true
###
@property [String] (Optional) A server-based relative path to the cover artwork for this product. This path should be relative to the server root.
###
coverImage:
type: String
required: false
###
@property [String] (Optional) A server-based relative path to the icon for this product. This path should be relative to the server root.
###
productIcon:
type: String
required: false
module.exports = CreateAircraftProductAjaxRequest |
[
{
"context": "p for bot commands'\n version: '0.2'\n authors: ['Álvaro Cuesta']\n",
"end": 1766,
"score": 0.9998679161071777,
"start": 1753,
"tag": "NAME",
"value": "Álvaro Cuesta"
}
] | plugins/help.coffee | alvaro-cuesta/nerdobot | 2 | module.exports = ({hidden, banner}) ->
@addCommand 'help',
args: '<command, optional>'
description: 'List commands or print help for <command>'
({nick}, command, to) =>
to ?= nick
if command?
command = command[1..] if command[0] == @config.prefix
for _, meta of @plugins
for cmd, info of meta.commands
if hidden?.length? and cmd not in hidden and (command == cmd or
(@config.aliases[cmd]? and command in @config.aliases[cmd]))
helpMsg = "#{@BOLD}#{@color 'red'}#{@config.prefix}#{cmd}#{@RESET}"
helpMsg += ' ' + info.args if info.args?
helpMsg += ' - ' + info.description if info.description?
@say to, helpMsg
if info.help?
@say to, " #{info.help}"
if @config.aliases[cmd]?
aliases = @config.aliases[cmd]
@say to, " #{@BOLD}Aliases:#{@RESET} #{@config.prefix + aliases.join ", #{@config.prefix}"}"
return
@notice nick, "Unknown command #{@BOLD}#{@config.prefix}#{command}#{@RESET}"
else
commands = []
for _, meta of @plugins
for cmd, _ of meta.commands
commands.push cmd if hidden?.length? and cmd not in hidden
commands.sort (a, b) ->
return 1 if a > b
return -1 if a < b
0
@say to, "#{@BOLD}#{@color 'red'}Available commands:#{@RESET} #{@config.prefix + commands.join ", #{@config.prefix}"}"
@say to, " Type #{@BOLD}#{@config.prefix}help <command>#{@BOLD} for detailed instructions."
@say to, banner if banner?
name: 'Help'
description: 'Print help for bot commands'
version: '0.2'
authors: ['Álvaro Cuesta']
| 69647 | module.exports = ({hidden, banner}) ->
@addCommand 'help',
args: '<command, optional>'
description: 'List commands or print help for <command>'
({nick}, command, to) =>
to ?= nick
if command?
command = command[1..] if command[0] == @config.prefix
for _, meta of @plugins
for cmd, info of meta.commands
if hidden?.length? and cmd not in hidden and (command == cmd or
(@config.aliases[cmd]? and command in @config.aliases[cmd]))
helpMsg = "#{@BOLD}#{@color 'red'}#{@config.prefix}#{cmd}#{@RESET}"
helpMsg += ' ' + info.args if info.args?
helpMsg += ' - ' + info.description if info.description?
@say to, helpMsg
if info.help?
@say to, " #{info.help}"
if @config.aliases[cmd]?
aliases = @config.aliases[cmd]
@say to, " #{@BOLD}Aliases:#{@RESET} #{@config.prefix + aliases.join ", #{@config.prefix}"}"
return
@notice nick, "Unknown command #{@BOLD}#{@config.prefix}#{command}#{@RESET}"
else
commands = []
for _, meta of @plugins
for cmd, _ of meta.commands
commands.push cmd if hidden?.length? and cmd not in hidden
commands.sort (a, b) ->
return 1 if a > b
return -1 if a < b
0
@say to, "#{@BOLD}#{@color 'red'}Available commands:#{@RESET} #{@config.prefix + commands.join ", #{@config.prefix}"}"
@say to, " Type #{@BOLD}#{@config.prefix}help <command>#{@BOLD} for detailed instructions."
@say to, banner if banner?
name: 'Help'
description: 'Print help for bot commands'
version: '0.2'
authors: ['<NAME>']
| true | module.exports = ({hidden, banner}) ->
@addCommand 'help',
args: '<command, optional>'
description: 'List commands or print help for <command>'
({nick}, command, to) =>
to ?= nick
if command?
command = command[1..] if command[0] == @config.prefix
for _, meta of @plugins
for cmd, info of meta.commands
if hidden?.length? and cmd not in hidden and (command == cmd or
(@config.aliases[cmd]? and command in @config.aliases[cmd]))
helpMsg = "#{@BOLD}#{@color 'red'}#{@config.prefix}#{cmd}#{@RESET}"
helpMsg += ' ' + info.args if info.args?
helpMsg += ' - ' + info.description if info.description?
@say to, helpMsg
if info.help?
@say to, " #{info.help}"
if @config.aliases[cmd]?
aliases = @config.aliases[cmd]
@say to, " #{@BOLD}Aliases:#{@RESET} #{@config.prefix + aliases.join ", #{@config.prefix}"}"
return
@notice nick, "Unknown command #{@BOLD}#{@config.prefix}#{command}#{@RESET}"
else
commands = []
for _, meta of @plugins
for cmd, _ of meta.commands
commands.push cmd if hidden?.length? and cmd not in hidden
commands.sort (a, b) ->
return 1 if a > b
return -1 if a < b
0
@say to, "#{@BOLD}#{@color 'red'}Available commands:#{@RESET} #{@config.prefix + commands.join ", #{@config.prefix}"}"
@say to, " Type #{@BOLD}#{@config.prefix}help <command>#{@BOLD} for detailed instructions."
@say to, banner if banner?
name: 'Help'
description: 'Print help for bot commands'
version: '0.2'
authors: ['PI:NAME:<NAME>END_PI']
|
[
{
"context": "1UserId = 42\n\t\t@user =\n\t\t\t_id: @userId\n\t\t\temail: 'user@example.com'\n\t\t\toverleaf:\n\t\t\t\tid: @v1UserId\n\n\tdescribe 'getPl",
"end": 888,
"score": 0.9998677372932434,
"start": 872,
"tag": "EMAIL",
"value": "user@example.com"
}
] | test/unit/coffee/Subscription/V1SusbcriptionManagerTests.coffee | shyoshyo/web-sharelatex | 1 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../app/js/Features/Subscription/V1SubscriptionManager'
sinon = require("sinon")
expect = require("chai").expect
describe 'V1SubscriptionManager', ->
beforeEach ->
@V1SubscriptionManager = SandboxedModule.require modulePath, requires:
"../User/UserGetter": @UserGetter = {}
"logger-sharelatex":
log: sinon.stub()
err: sinon.stub()
warn: sinon.stub()
"settings-sharelatex": @Settings =
apis:
v1:
host: @host = "http://overleaf.example.com"
v1GrandfatheredFeaturesUidCutoff: 10
v1GrandfatheredFeatures:
github: true
mendeley: true
"request": @request = sinon.stub()
@userId = 'abcd'
@v1UserId = 42
@user =
_id: @userId
email: 'user@example.com'
overleaf:
id: @v1UserId
describe 'getPlanCodeFromV1', ->
beforeEach ->
@responseBody =
id: 32,
plan_name: 'pro'
@V1SubscriptionManager._v1Request = sinon.stub()
.yields(null, @responseBody)
@call = (cb) =>
@V1SubscriptionManager.getPlanCodeFromV1 @userId, cb
describe 'when all goes well', ->
it 'should call _v1Request', (done) ->
@call (err, planCode) =>
expect(
@V1SubscriptionManager._v1Request.callCount
).to.equal 1
expect(
@V1SubscriptionManager._v1Request.calledWith(
@userId
)
).to.equal true
done()
it 'should return the v1 user id', (done) ->
@call (err, planCode, v1Id) ->
expect(v1Id).to.equal @v1UserId
done()
it 'should produce a plan-code without error', (done) ->
@call (err, planCode) =>
expect(err).to.not.exist
expect(planCode).to.equal 'v1_pro'
done()
describe 'when the plan_name from v1 is null', ->
beforeEach ->
@responseBody.plan_name = null
it 'should produce a null plan-code without error', (done) ->
@call (err, planCode) =>
expect(err).to.not.exist
expect(planCode).to.equal null
done()
describe 'getGrandfatheredFeaturesForV1User', ->
describe 'when the user ID is greater than the cutoff', ->
it 'should return an empty feature set', (done) ->
expect(@V1SubscriptionManager.getGrandfatheredFeaturesForV1User 100).to.eql {}
done()
describe 'when the user ID is less than the cutoff', ->
it 'should return a feature set with grandfathered properties for github and mendeley', (done) ->
expect(@V1SubscriptionManager.getGrandfatheredFeaturesForV1User 1).to.eql
github: true
mendeley: true
done()
describe '_v1Request', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, @user)
describe 'when v1IdForUser produces an error', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not call request', (done) ->
@call (err, planCode) =>
expect(
@request.callCount
).to.equal 0
done()
it 'should produce an error', (done) ->
@call (err, planCode) =>
expect(err).to.exist
done()
describe 'when v1IdForUser does not find a user', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, null)
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not call request', (done) ->
@call (err, planCode) =>
expect(
@request.callCount
).to.equal 0
done()
it 'should not error', (done) ->
@call (err) =>
expect(err).to.not.exist
done()
describe 'when the request to v1 fails', ->
beforeEach ->
@request.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.exist
done()
describe 'when the call succeeds', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, @v1UserId)
@request.yields(null, { statusCode: 200 }, "{}")
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not produce an error', (done) ->
@call (err, body, v1Id) =>
expect(err).not.to.exist
done()
it 'should return the v1 user id', (done) ->
@call (err, body, v1Id) =>
expect(v1Id).to.equal @v1UserId
done()
it 'should return the http response body', (done) ->
@call (err, body, v1Id) =>
expect(body).to.equal "{}"
done()
describe 'when the call returns an http error status code', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, @v1UserId)
@request.yields(null, { statusCode: 500 }, "{}")
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should produce an error', (done) ->
@call (err, body, v1Id) =>
expect(err).to.exist
done()
describe 'v1IdForUser', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, @user)
describe 'when getUser produces an error', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.exist
done()
describe 'when getUser does not find a user', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, null)
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should not error', (done) ->
@call (err, user_id) =>
expect(err).to.not.exist
done()
describe 'when it works', ->
beforeEach ->
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should not error', (done) ->
@call (err, user_id) =>
expect(err).to.not.exist
done()
it 'should return the v1 user id', (done) ->
@call (err, user_id) =>
expect(user_id).to.eql 42
done() | 183284 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../app/js/Features/Subscription/V1SubscriptionManager'
sinon = require("sinon")
expect = require("chai").expect
describe 'V1SubscriptionManager', ->
beforeEach ->
@V1SubscriptionManager = SandboxedModule.require modulePath, requires:
"../User/UserGetter": @UserGetter = {}
"logger-sharelatex":
log: sinon.stub()
err: sinon.stub()
warn: sinon.stub()
"settings-sharelatex": @Settings =
apis:
v1:
host: @host = "http://overleaf.example.com"
v1GrandfatheredFeaturesUidCutoff: 10
v1GrandfatheredFeatures:
github: true
mendeley: true
"request": @request = sinon.stub()
@userId = 'abcd'
@v1UserId = 42
@user =
_id: @userId
email: '<EMAIL>'
overleaf:
id: @v1UserId
describe 'getPlanCodeFromV1', ->
beforeEach ->
@responseBody =
id: 32,
plan_name: 'pro'
@V1SubscriptionManager._v1Request = sinon.stub()
.yields(null, @responseBody)
@call = (cb) =>
@V1SubscriptionManager.getPlanCodeFromV1 @userId, cb
describe 'when all goes well', ->
it 'should call _v1Request', (done) ->
@call (err, planCode) =>
expect(
@V1SubscriptionManager._v1Request.callCount
).to.equal 1
expect(
@V1SubscriptionManager._v1Request.calledWith(
@userId
)
).to.equal true
done()
it 'should return the v1 user id', (done) ->
@call (err, planCode, v1Id) ->
expect(v1Id).to.equal @v1UserId
done()
it 'should produce a plan-code without error', (done) ->
@call (err, planCode) =>
expect(err).to.not.exist
expect(planCode).to.equal 'v1_pro'
done()
describe 'when the plan_name from v1 is null', ->
beforeEach ->
@responseBody.plan_name = null
it 'should produce a null plan-code without error', (done) ->
@call (err, planCode) =>
expect(err).to.not.exist
expect(planCode).to.equal null
done()
describe 'getGrandfatheredFeaturesForV1User', ->
describe 'when the user ID is greater than the cutoff', ->
it 'should return an empty feature set', (done) ->
expect(@V1SubscriptionManager.getGrandfatheredFeaturesForV1User 100).to.eql {}
done()
describe 'when the user ID is less than the cutoff', ->
it 'should return a feature set with grandfathered properties for github and mendeley', (done) ->
expect(@V1SubscriptionManager.getGrandfatheredFeaturesForV1User 1).to.eql
github: true
mendeley: true
done()
describe '_v1Request', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, @user)
describe 'when v1IdForUser produces an error', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not call request', (done) ->
@call (err, planCode) =>
expect(
@request.callCount
).to.equal 0
done()
it 'should produce an error', (done) ->
@call (err, planCode) =>
expect(err).to.exist
done()
describe 'when v1IdForUser does not find a user', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, null)
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not call request', (done) ->
@call (err, planCode) =>
expect(
@request.callCount
).to.equal 0
done()
it 'should not error', (done) ->
@call (err) =>
expect(err).to.not.exist
done()
describe 'when the request to v1 fails', ->
beforeEach ->
@request.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.exist
done()
describe 'when the call succeeds', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, @v1UserId)
@request.yields(null, { statusCode: 200 }, "{}")
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not produce an error', (done) ->
@call (err, body, v1Id) =>
expect(err).not.to.exist
done()
it 'should return the v1 user id', (done) ->
@call (err, body, v1Id) =>
expect(v1Id).to.equal @v1UserId
done()
it 'should return the http response body', (done) ->
@call (err, body, v1Id) =>
expect(body).to.equal "{}"
done()
describe 'when the call returns an http error status code', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, @v1UserId)
@request.yields(null, { statusCode: 500 }, "{}")
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should produce an error', (done) ->
@call (err, body, v1Id) =>
expect(err).to.exist
done()
describe 'v1IdForUser', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, @user)
describe 'when getUser produces an error', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.exist
done()
describe 'when getUser does not find a user', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, null)
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should not error', (done) ->
@call (err, user_id) =>
expect(err).to.not.exist
done()
describe 'when it works', ->
beforeEach ->
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should not error', (done) ->
@call (err, user_id) =>
expect(err).to.not.exist
done()
it 'should return the v1 user id', (done) ->
@call (err, user_id) =>
expect(user_id).to.eql 42
done() | true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../app/js/Features/Subscription/V1SubscriptionManager'
sinon = require("sinon")
expect = require("chai").expect
describe 'V1SubscriptionManager', ->
beforeEach ->
@V1SubscriptionManager = SandboxedModule.require modulePath, requires:
"../User/UserGetter": @UserGetter = {}
"logger-sharelatex":
log: sinon.stub()
err: sinon.stub()
warn: sinon.stub()
"settings-sharelatex": @Settings =
apis:
v1:
host: @host = "http://overleaf.example.com"
v1GrandfatheredFeaturesUidCutoff: 10
v1GrandfatheredFeatures:
github: true
mendeley: true
"request": @request = sinon.stub()
@userId = 'abcd'
@v1UserId = 42
@user =
_id: @userId
email: 'PI:EMAIL:<EMAIL>END_PI'
overleaf:
id: @v1UserId
describe 'getPlanCodeFromV1', ->
beforeEach ->
@responseBody =
id: 32,
plan_name: 'pro'
@V1SubscriptionManager._v1Request = sinon.stub()
.yields(null, @responseBody)
@call = (cb) =>
@V1SubscriptionManager.getPlanCodeFromV1 @userId, cb
describe 'when all goes well', ->
it 'should call _v1Request', (done) ->
@call (err, planCode) =>
expect(
@V1SubscriptionManager._v1Request.callCount
).to.equal 1
expect(
@V1SubscriptionManager._v1Request.calledWith(
@userId
)
).to.equal true
done()
it 'should return the v1 user id', (done) ->
@call (err, planCode, v1Id) ->
expect(v1Id).to.equal @v1UserId
done()
it 'should produce a plan-code without error', (done) ->
@call (err, planCode) =>
expect(err).to.not.exist
expect(planCode).to.equal 'v1_pro'
done()
describe 'when the plan_name from v1 is null', ->
beforeEach ->
@responseBody.plan_name = null
it 'should produce a null plan-code without error', (done) ->
@call (err, planCode) =>
expect(err).to.not.exist
expect(planCode).to.equal null
done()
describe 'getGrandfatheredFeaturesForV1User', ->
describe 'when the user ID is greater than the cutoff', ->
it 'should return an empty feature set', (done) ->
expect(@V1SubscriptionManager.getGrandfatheredFeaturesForV1User 100).to.eql {}
done()
describe 'when the user ID is less than the cutoff', ->
it 'should return a feature set with grandfathered properties for github and mendeley', (done) ->
expect(@V1SubscriptionManager.getGrandfatheredFeaturesForV1User 1).to.eql
github: true
mendeley: true
done()
describe '_v1Request', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, @user)
describe 'when v1IdForUser produces an error', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not call request', (done) ->
@call (err, planCode) =>
expect(
@request.callCount
).to.equal 0
done()
it 'should produce an error', (done) ->
@call (err, planCode) =>
expect(err).to.exist
done()
describe 'when v1IdForUser does not find a user', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, null)
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not call request', (done) ->
@call (err, planCode) =>
expect(
@request.callCount
).to.equal 0
done()
it 'should not error', (done) ->
@call (err) =>
expect(err).to.not.exist
done()
describe 'when the request to v1 fails', ->
beforeEach ->
@request.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.exist
done()
describe 'when the call succeeds', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, @v1UserId)
@request.yields(null, { statusCode: 200 }, "{}")
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should not produce an error', (done) ->
@call (err, body, v1Id) =>
expect(err).not.to.exist
done()
it 'should return the v1 user id', (done) ->
@call (err, body, v1Id) =>
expect(v1Id).to.equal @v1UserId
done()
it 'should return the http response body', (done) ->
@call (err, body, v1Id) =>
expect(body).to.equal "{}"
done()
describe 'when the call returns an http error status code', ->
beforeEach ->
@V1SubscriptionManager.v1IdForUser = sinon.stub()
.yields(null, @v1UserId)
@request.yields(null, { statusCode: 500 }, "{}")
@call = (cb) =>
@V1SubscriptionManager._v1Request @user_id, { url: () -> '/foo' }, cb
it 'should produce an error', (done) ->
@call (err, body, v1Id) =>
expect(err).to.exist
done()
describe 'v1IdForUser', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, @user)
describe 'when getUser produces an error', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(new Error('woops'))
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.exist
done()
describe 'when getUser does not find a user', ->
beforeEach ->
@UserGetter.getUser = sinon.stub()
.yields(null, null)
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should not error', (done) ->
@call (err, user_id) =>
expect(err).to.not.exist
done()
describe 'when it works', ->
beforeEach ->
@call = (cb) =>
@V1SubscriptionManager.v1IdForUser @user_id, cb
it 'should not error', (done) ->
@call (err, user_id) =>
expect(err).to.not.exist
done()
it 'should return the v1 user id', (done) ->
@call (err, user_id) =>
expect(user_id).to.eql 42
done() |
[
{
"context": "aseObject\", ->\n beforeEach ->\n @name = \"nick\"\n @state = \"fl\"\n @defaultSubject = ",
"end": 781,
"score": 0.997123122215271,
"start": 777,
"tag": "NAME",
"value": "nick"
}
] | www/lib/js/angular-google-maps/spec/coffee/oo/base-object.spec.coffee | neilff/liqbo-cordova | 1 | describe "oo.BaseObject", ->
it "exists ~ you loaded the script!", ->
expect(oo.BaseObject?).toEqual(true)
@ngGmapModule "oo.test", ->
@PersonModule =
changePersonName: (person, name)->
person.name = name
person
killPersonsName: (person)->
delete person.name
person
@PersonAttributes =
p_name: "no_name"
state: "no_state"
class @Person extends oo.BaseObject
@include oo.test.PersonModule
@extend oo.test.PersonAttributes
constructor: (name, state)->
@name = if name? then name else oo.test.Person.p_name
@state = if state? then state else oo.test.Person.state
describe "oo.BaseObject", ->
beforeEach ->
@name = "nick"
@state = "fl"
@defaultSubject = new oo.test.Person()
@subject = new oo.test.Person(@name, @state)
describe "include specs", ->
it "defaults attributes exist", ->
expect(@defaultSubject.name?).toEqual(true)
expect(@defaultSubject.name?).toEqual(true)
it "defaults attributes are correct", ->
expect(@defaultSubject.name).toEqual(oo.test.PersonAttributes.p_name)
expect(@defaultSubject.state).toEqual(oo.test.PersonAttributes.state)
it "subject attributes are correct ", ->
expect(@subject.name).toEqual(@name)
expect(@subject.state).toEqual(@state)
describe "extend specs", ->
it "defaults functions exist", ->
expect(@defaultSubject.changePersonName?).toEqual(true)
expect(@defaultSubject.killPersonsName?).toEqual(true)
it "subject functions act correctly", ->
p = @defaultSubject.changePersonName(angular.copy(@defaultSubject), "john")
p2 = @defaultSubject.killPersonsName(@defaultSubject)
expect(p.name).toEqual("john")
expect(p2.name).toEqual(undefined) | 2794 | describe "oo.BaseObject", ->
it "exists ~ you loaded the script!", ->
expect(oo.BaseObject?).toEqual(true)
@ngGmapModule "oo.test", ->
@PersonModule =
changePersonName: (person, name)->
person.name = name
person
killPersonsName: (person)->
delete person.name
person
@PersonAttributes =
p_name: "no_name"
state: "no_state"
class @Person extends oo.BaseObject
@include oo.test.PersonModule
@extend oo.test.PersonAttributes
constructor: (name, state)->
@name = if name? then name else oo.test.Person.p_name
@state = if state? then state else oo.test.Person.state
describe "oo.BaseObject", ->
beforeEach ->
@name = "<NAME>"
@state = "fl"
@defaultSubject = new oo.test.Person()
@subject = new oo.test.Person(@name, @state)
describe "include specs", ->
it "defaults attributes exist", ->
expect(@defaultSubject.name?).toEqual(true)
expect(@defaultSubject.name?).toEqual(true)
it "defaults attributes are correct", ->
expect(@defaultSubject.name).toEqual(oo.test.PersonAttributes.p_name)
expect(@defaultSubject.state).toEqual(oo.test.PersonAttributes.state)
it "subject attributes are correct ", ->
expect(@subject.name).toEqual(@name)
expect(@subject.state).toEqual(@state)
describe "extend specs", ->
it "defaults functions exist", ->
expect(@defaultSubject.changePersonName?).toEqual(true)
expect(@defaultSubject.killPersonsName?).toEqual(true)
it "subject functions act correctly", ->
p = @defaultSubject.changePersonName(angular.copy(@defaultSubject), "john")
p2 = @defaultSubject.killPersonsName(@defaultSubject)
expect(p.name).toEqual("john")
expect(p2.name).toEqual(undefined) | true | describe "oo.BaseObject", ->
it "exists ~ you loaded the script!", ->
expect(oo.BaseObject?).toEqual(true)
@ngGmapModule "oo.test", ->
@PersonModule =
changePersonName: (person, name)->
person.name = name
person
killPersonsName: (person)->
delete person.name
person
@PersonAttributes =
p_name: "no_name"
state: "no_state"
class @Person extends oo.BaseObject
@include oo.test.PersonModule
@extend oo.test.PersonAttributes
constructor: (name, state)->
@name = if name? then name else oo.test.Person.p_name
@state = if state? then state else oo.test.Person.state
describe "oo.BaseObject", ->
beforeEach ->
@name = "PI:NAME:<NAME>END_PI"
@state = "fl"
@defaultSubject = new oo.test.Person()
@subject = new oo.test.Person(@name, @state)
describe "include specs", ->
it "defaults attributes exist", ->
expect(@defaultSubject.name?).toEqual(true)
expect(@defaultSubject.name?).toEqual(true)
it "defaults attributes are correct", ->
expect(@defaultSubject.name).toEqual(oo.test.PersonAttributes.p_name)
expect(@defaultSubject.state).toEqual(oo.test.PersonAttributes.state)
it "subject attributes are correct ", ->
expect(@subject.name).toEqual(@name)
expect(@subject.state).toEqual(@state)
describe "extend specs", ->
it "defaults functions exist", ->
expect(@defaultSubject.changePersonName?).toEqual(true)
expect(@defaultSubject.killPersonsName?).toEqual(true)
it "subject functions act correctly", ->
p = @defaultSubject.changePersonName(angular.copy(@defaultSubject), "john")
p2 = @defaultSubject.killPersonsName(@defaultSubject)
expect(p.name).toEqual("john")
expect(p2.name).toEqual(undefined) |
[
{
"context": "# inputData:\n # [ {\n # label: \"Customer 1\",\n # value: 1550.12\n # ] }\n @pieChar",
"end": 9899,
"score": 0.8317974209785461,
"start": 9898,
"tag": "NAME",
"value": "1"
}
] | src/services/chart-formatter/chart-formatter.svc.coffee | agranado2k/impac-angular | 7 | angular
.module('impac.services.chart-formatter', [])
.service('ChartFormatterSvc', (ImpacTheming, $filter, $window, $document, ImpacDashboardsSvc) ->
_self = @
COLORS = ImpacTheming.get().chartColors
# on browser window blur event, remove any lingering chartjs-tooltips from the DOM.
$window.onblur = ->
angular.element($document[0].getElementById('chartjs-tooltip')).remove()
# Returns the color defined for positive values
@getPositiveColor = ->
return COLORS.positive
# Returns the color defined for negative values
@getNegativeColor = ->
return COLORS.negative
# Returns the color defined for "others" value
@getOthersColor = ->
return COLORS.others
# Returns a color from the array retrieved from Maestrano Rails app (set in config files)
@getColor = (index) ->
return COLORS.array[index%COLORS.array.length]
# Returns a color from the array retrieved from Maestrano Rails app (set in config files) with applying passed opacity
@getLightenColor = (index, alpha) ->
htmlColor = COLORS.array[index%COLORS.array.length]
return lightenColor(htmlColor, alpha || 0.4) if htmlColor
# Removes the # from an HTML color value
cutHex = (htmlColor) ->
return htmlColor.replace(/#/,'')
hexToR = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(0,2),16)
hexToG = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(2,4),16)
hexToB = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(4,6),16)
hexToRGB = (htmlColor) ->
return [hexToR(htmlColor),hexToG(htmlColor),hexToB(htmlColor)].join(",")
lightenColor = (htmlColor, alpha) ->
return "rgba(#{hexToRGB(htmlColor)},#{alpha})"
# Configure ChartJs global options
# ----------
@customTooltip = (tooltip) ->
# Find the tooltip
tooltipEl = angular.element('#chartjs-tooltip')
if (!tooltipEl[0])
angular.element('body').append('<div id="chartjs-tooltip"></div>')
tooltipEl = angular.element('#chartjs-tooltip')
# Hide if no tooltip
if (!tooltip.opacity)
tooltipEl.css({
opacity: 0.5
})
return
# Set caret Position
tooltipEl.removeClass('above below no-transform')
if (tooltip.yAlign)
tooltipEl.addClass(tooltip.yAlign)
else
tooltipEl.addClass('no-transform')
# Set Text
if (tooltip.body)
innerHtml = _.compact([
(tooltip.beforeTitle || []).join('<br/>'), (tooltip.title || []).join('<br/>'), (tooltip.afterTitle || []).join('<br/>'), (tooltip.beforeBody || []).join('<br/>'), (tooltip.body || []).join('<br/>'), (tooltip.afterBody || []).join('<br/>'), (tooltip.beforeFooter || [])
.join('<br/>'), (tooltip.footer || []).join('<br/>'), (tooltip.afterFooter || []).join('<br/>')
])
tooltipEl.html(innerHtml.join('<br/>'))
# Alignment
canvasEl = angular.element(this._chart.canvas)
offset = canvasEl.offset()
# Avoid mouse glitches
canvasEl.bind 'mouseleave', (event) ->
tooltipEl.remove() unless event.relatedTarget.id == 'chartjs-tooltip'
tooltipEl.bind 'mouseleave', (event) ->
tooltipEl.remove() unless event.relatedTarget.tagName == 'CANVAS'
# Display, position, and set styles for font
tooltipEl.css({
'background-color': '#17262d'
color: 'white'
opacity: 1
transition: 'opacity 0.5s, top 0.5s, left 0.5s'
position: 'absolute'
width: tooltip.width ? "#{tooltip.width}px" : 'auto'
left: "#{offset.left + tooltip.x + 10}px"
top: "#{offset.top + tooltip.y + 10}px"
fontFamily: tooltip._fontFamily
fontSize: tooltip.fontSize
fontStyle: tooltip._fontStyle
padding: "#{tooltip.yPadding}px #{tooltip.xPadding}px"
'border-radius': '2px'
})
angular.merge Chart.defaults.global, {
defaultColor: _self.getColor(0)
tooltips:
titleFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
bodyFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
footerFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
enabled: false
custom: _self.customTooltip
elements:
point:
hitRadius: 8
hoverRadius: 8
line:
tension: 0
borderWidth: 2
legend:
display: false
}
angular.merge Chart.defaults.scale, {
ticks:
beginAtZero: true
minRotation: 0
# maxRotation: 0
fontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
scaleLabel:
fontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
}
@setTooltipsTextLayout = (opts, showSerieInTitle=false) ->
angular.merge opts, {
tooltips:
callbacks:
title: (context, data) ->
unless showSerieInTitle
return data.labels[context[0].index]
else
title = [data.labels[context[0].index]]
title.push data.datasets[context[0].datasetIndex].label if data.datasets[context[0].datasetIndex].label
return title.join(' | ')
label: (context, data) ->
currency = opts.currency || ImpacDashboardsSvc.getCurrentDashboard().currency
unless currency=='hide'
return $filter('mnoCurrency')(data.datasets[context.datasetIndex].data[context.index], currency)
else
return data.datasets[context.datasetIndex].data[context.index]
}
# Line Chart of several datasets | versusMode can be used to force positive/negative colors
# ----------
# inputDataArray:
# [{
# title: "Serie",
# labels: ["date1","date2"],
# values: [15.25,7.4]
# }]
# versusMode: put the negative dataset first
@lineChart = (inputDataArray, opts={}, versusMode=false) ->
_self.setTooltipsTextLayout(opts, true)
index = 0
isFilled = inputDataArray.length == 1
singleValue = false
if inputDataArray[0].labels.length < 2
# if the values array have only one entry, we double it to avoid the display of a single point on the chart
singleValue = true
inputDataArray[0].labels.push inputDataArray[0].labels[0]
# Defaut when several datasets or single dataset but with only one value: straight lines without point dot
if inputDataArray.length > 1 || (opts.pointDot? && !opts.pointDot) || singleValue
angular.merge(opts, {
elements:
point:
radius: 0.0001
line:
tension: 0.3
})
return {
type: 'line',
options: opts,
data: {
labels: inputDataArray[0].labels,
datasets: _.map inputDataArray, (inputData) ->
if singleValue
inputData.values.push inputData.values[0]
if versusMode
if index == 0
color = _self.getNegativeColor()
else
color = _self.getPositiveColor()
else
color = _self.getColor(index)
index++
return {
label: inputData.title
data: inputData.values
fill: isFilled
backgroundColor: lightenColor(color,0.3)
borderColor: color
pointBorderColor: color
pointBackgroundColor: color
pointHoverBackgroundColor: 'rgb(255,255,255)'
}
}
}
# TODO refactor barChart and combinedChart (now we have chartjs v2.0...)
# Bar Chart of one dataset with several values (eg: different coloured bars for several accounts)
# ----------
# inputData:
# {
# labels: ["Account1","Account2"],
# values: [15.25,7.4]
# }
# positivesOnly: if true (default), negative bars will be turned into their opposite
@barChart = (inputData, opts={}, positivesOnly=true) ->
_self.setTooltipsTextLayout(opts)
index = 0
colors = []
for value in inputData.values
inputData.values[index] = Math.abs(value) if positivesOnly
colors.push(_self.getColor(index))
index++
return {
type: 'bar'
options: opts
data: {
labels: inputData.labels
datasets: [{ backgroundColor: colors, data: inputData.values }]
}
}
# Bar Chart of several datasets with several values each
# ----------
# inputData:
# labels: ['Company A', 'Company B']
# datasets:
# [
# {title: 'ASSET', values: [1566,56156]}
# {title: 'LIABILITY', values: [67868,686]}
# ]
# positivesOnly: if true (default), negative bars will be turned into their opposite
@combinedBarChart = (inputData, opts={}, positivesOnly=true, versusMode=false) ->
_self.setTooltipsTextLayout(opts, true)
index = 0
result = {
type: 'bar',
options: opts,
data: {
labels: inputData.labels
datasets: _.map inputData.datasets, (dataset) ->
color = _self.getColor(index)
if versusMode
if index == 0
color = _self.getNegativeColor()
else
color = _self.getPositiveColor()
index++
if positivesOnly
for value in dataset.values
value = Math.abs(value)
return {
label: dataset.title,
data: dataset.values,
backgroundColor: color,
}
}
}
return result
# inputData:
# [ {
# label: "Customer 1",
# value: 1550.12
# ] }
@pieChart = (inputData, opts={}, versusMode=false) ->
_self.setTooltipsTextLayout(opts)
index=0
colors=[]
if versusMode
colors.push(_self.getNegativeColor())
for data in inputData
colors.push(_self.getPositiveColor()) unless index==0
index++
else
for data in inputData
colors.push(_self.getColor(index))
index++
{
type: 'doughnut',
options: opts,
data: {
datasets: [
{
data: _.map inputData, ( (data) -> Math.abs(data.value) )
backgroundColor: colors
}
]
labels: _.map inputData, ( (data) -> data.label )
}
}
return
)
| 5054 | angular
.module('impac.services.chart-formatter', [])
.service('ChartFormatterSvc', (ImpacTheming, $filter, $window, $document, ImpacDashboardsSvc) ->
_self = @
COLORS = ImpacTheming.get().chartColors
# on browser window blur event, remove any lingering chartjs-tooltips from the DOM.
$window.onblur = ->
angular.element($document[0].getElementById('chartjs-tooltip')).remove()
# Returns the color defined for positive values
@getPositiveColor = ->
return COLORS.positive
# Returns the color defined for negative values
@getNegativeColor = ->
return COLORS.negative
# Returns the color defined for "others" value
@getOthersColor = ->
return COLORS.others
# Returns a color from the array retrieved from Maestrano Rails app (set in config files)
@getColor = (index) ->
return COLORS.array[index%COLORS.array.length]
# Returns a color from the array retrieved from Maestrano Rails app (set in config files) with applying passed opacity
@getLightenColor = (index, alpha) ->
htmlColor = COLORS.array[index%COLORS.array.length]
return lightenColor(htmlColor, alpha || 0.4) if htmlColor
# Removes the # from an HTML color value
cutHex = (htmlColor) ->
return htmlColor.replace(/#/,'')
hexToR = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(0,2),16)
hexToG = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(2,4),16)
hexToB = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(4,6),16)
hexToRGB = (htmlColor) ->
return [hexToR(htmlColor),hexToG(htmlColor),hexToB(htmlColor)].join(",")
lightenColor = (htmlColor, alpha) ->
return "rgba(#{hexToRGB(htmlColor)},#{alpha})"
# Configure ChartJs global options
# ----------
@customTooltip = (tooltip) ->
# Find the tooltip
tooltipEl = angular.element('#chartjs-tooltip')
if (!tooltipEl[0])
angular.element('body').append('<div id="chartjs-tooltip"></div>')
tooltipEl = angular.element('#chartjs-tooltip')
# Hide if no tooltip
if (!tooltip.opacity)
tooltipEl.css({
opacity: 0.5
})
return
# Set caret Position
tooltipEl.removeClass('above below no-transform')
if (tooltip.yAlign)
tooltipEl.addClass(tooltip.yAlign)
else
tooltipEl.addClass('no-transform')
# Set Text
if (tooltip.body)
innerHtml = _.compact([
(tooltip.beforeTitle || []).join('<br/>'), (tooltip.title || []).join('<br/>'), (tooltip.afterTitle || []).join('<br/>'), (tooltip.beforeBody || []).join('<br/>'), (tooltip.body || []).join('<br/>'), (tooltip.afterBody || []).join('<br/>'), (tooltip.beforeFooter || [])
.join('<br/>'), (tooltip.footer || []).join('<br/>'), (tooltip.afterFooter || []).join('<br/>')
])
tooltipEl.html(innerHtml.join('<br/>'))
# Alignment
canvasEl = angular.element(this._chart.canvas)
offset = canvasEl.offset()
# Avoid mouse glitches
canvasEl.bind 'mouseleave', (event) ->
tooltipEl.remove() unless event.relatedTarget.id == 'chartjs-tooltip'
tooltipEl.bind 'mouseleave', (event) ->
tooltipEl.remove() unless event.relatedTarget.tagName == 'CANVAS'
# Display, position, and set styles for font
tooltipEl.css({
'background-color': '#17262d'
color: 'white'
opacity: 1
transition: 'opacity 0.5s, top 0.5s, left 0.5s'
position: 'absolute'
width: tooltip.width ? "#{tooltip.width}px" : 'auto'
left: "#{offset.left + tooltip.x + 10}px"
top: "#{offset.top + tooltip.y + 10}px"
fontFamily: tooltip._fontFamily
fontSize: tooltip.fontSize
fontStyle: tooltip._fontStyle
padding: "#{tooltip.yPadding}px #{tooltip.xPadding}px"
'border-radius': '2px'
})
angular.merge Chart.defaults.global, {
defaultColor: _self.getColor(0)
tooltips:
titleFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
bodyFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
footerFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
enabled: false
custom: _self.customTooltip
elements:
point:
hitRadius: 8
hoverRadius: 8
line:
tension: 0
borderWidth: 2
legend:
display: false
}
angular.merge Chart.defaults.scale, {
ticks:
beginAtZero: true
minRotation: 0
# maxRotation: 0
fontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
scaleLabel:
fontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
}
@setTooltipsTextLayout = (opts, showSerieInTitle=false) ->
angular.merge opts, {
tooltips:
callbacks:
title: (context, data) ->
unless showSerieInTitle
return data.labels[context[0].index]
else
title = [data.labels[context[0].index]]
title.push data.datasets[context[0].datasetIndex].label if data.datasets[context[0].datasetIndex].label
return title.join(' | ')
label: (context, data) ->
currency = opts.currency || ImpacDashboardsSvc.getCurrentDashboard().currency
unless currency=='hide'
return $filter('mnoCurrency')(data.datasets[context.datasetIndex].data[context.index], currency)
else
return data.datasets[context.datasetIndex].data[context.index]
}
# Line Chart of several datasets | versusMode can be used to force positive/negative colors
# ----------
# inputDataArray:
# [{
# title: "Serie",
# labels: ["date1","date2"],
# values: [15.25,7.4]
# }]
# versusMode: put the negative dataset first
@lineChart = (inputDataArray, opts={}, versusMode=false) ->
_self.setTooltipsTextLayout(opts, true)
index = 0
isFilled = inputDataArray.length == 1
singleValue = false
if inputDataArray[0].labels.length < 2
# if the values array have only one entry, we double it to avoid the display of a single point on the chart
singleValue = true
inputDataArray[0].labels.push inputDataArray[0].labels[0]
# Defaut when several datasets or single dataset but with only one value: straight lines without point dot
if inputDataArray.length > 1 || (opts.pointDot? && !opts.pointDot) || singleValue
angular.merge(opts, {
elements:
point:
radius: 0.0001
line:
tension: 0.3
})
return {
type: 'line',
options: opts,
data: {
labels: inputDataArray[0].labels,
datasets: _.map inputDataArray, (inputData) ->
if singleValue
inputData.values.push inputData.values[0]
if versusMode
if index == 0
color = _self.getNegativeColor()
else
color = _self.getPositiveColor()
else
color = _self.getColor(index)
index++
return {
label: inputData.title
data: inputData.values
fill: isFilled
backgroundColor: lightenColor(color,0.3)
borderColor: color
pointBorderColor: color
pointBackgroundColor: color
pointHoverBackgroundColor: 'rgb(255,255,255)'
}
}
}
# TODO refactor barChart and combinedChart (now we have chartjs v2.0...)
# Bar Chart of one dataset with several values (eg: different coloured bars for several accounts)
# ----------
# inputData:
# {
# labels: ["Account1","Account2"],
# values: [15.25,7.4]
# }
# positivesOnly: if true (default), negative bars will be turned into their opposite
@barChart = (inputData, opts={}, positivesOnly=true) ->
_self.setTooltipsTextLayout(opts)
index = 0
colors = []
for value in inputData.values
inputData.values[index] = Math.abs(value) if positivesOnly
colors.push(_self.getColor(index))
index++
return {
type: 'bar'
options: opts
data: {
labels: inputData.labels
datasets: [{ backgroundColor: colors, data: inputData.values }]
}
}
# Bar Chart of several datasets with several values each
# ----------
# inputData:
# labels: ['Company A', 'Company B']
# datasets:
# [
# {title: 'ASSET', values: [1566,56156]}
# {title: 'LIABILITY', values: [67868,686]}
# ]
# positivesOnly: if true (default), negative bars will be turned into their opposite
@combinedBarChart = (inputData, opts={}, positivesOnly=true, versusMode=false) ->
_self.setTooltipsTextLayout(opts, true)
index = 0
result = {
type: 'bar',
options: opts,
data: {
labels: inputData.labels
datasets: _.map inputData.datasets, (dataset) ->
color = _self.getColor(index)
if versusMode
if index == 0
color = _self.getNegativeColor()
else
color = _self.getPositiveColor()
index++
if positivesOnly
for value in dataset.values
value = Math.abs(value)
return {
label: dataset.title,
data: dataset.values,
backgroundColor: color,
}
}
}
return result
# inputData:
# [ {
# label: "Customer <NAME>",
# value: 1550.12
# ] }
@pieChart = (inputData, opts={}, versusMode=false) ->
_self.setTooltipsTextLayout(opts)
index=0
colors=[]
if versusMode
colors.push(_self.getNegativeColor())
for data in inputData
colors.push(_self.getPositiveColor()) unless index==0
index++
else
for data in inputData
colors.push(_self.getColor(index))
index++
{
type: 'doughnut',
options: opts,
data: {
datasets: [
{
data: _.map inputData, ( (data) -> Math.abs(data.value) )
backgroundColor: colors
}
]
labels: _.map inputData, ( (data) -> data.label )
}
}
return
)
| true | angular
.module('impac.services.chart-formatter', [])
.service('ChartFormatterSvc', (ImpacTheming, $filter, $window, $document, ImpacDashboardsSvc) ->
_self = @
COLORS = ImpacTheming.get().chartColors
# on browser window blur event, remove any lingering chartjs-tooltips from the DOM.
$window.onblur = ->
angular.element($document[0].getElementById('chartjs-tooltip')).remove()
# Returns the color defined for positive values
@getPositiveColor = ->
return COLORS.positive
# Returns the color defined for negative values
@getNegativeColor = ->
return COLORS.negative
# Returns the color defined for "others" value
@getOthersColor = ->
return COLORS.others
# Returns a color from the array retrieved from Maestrano Rails app (set in config files)
@getColor = (index) ->
return COLORS.array[index%COLORS.array.length]
# Returns a color from the array retrieved from Maestrano Rails app (set in config files) with applying passed opacity
@getLightenColor = (index, alpha) ->
htmlColor = COLORS.array[index%COLORS.array.length]
return lightenColor(htmlColor, alpha || 0.4) if htmlColor
# Removes the # from an HTML color value
cutHex = (htmlColor) ->
return htmlColor.replace(/#/,'')
hexToR = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(0,2),16)
hexToG = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(2,4),16)
hexToB = (htmlColor) ->
return parseInt((cutHex(htmlColor)).substring(4,6),16)
hexToRGB = (htmlColor) ->
return [hexToR(htmlColor),hexToG(htmlColor),hexToB(htmlColor)].join(",")
lightenColor = (htmlColor, alpha) ->
return "rgba(#{hexToRGB(htmlColor)},#{alpha})"
# Configure ChartJs global options
# ----------
@customTooltip = (tooltip) ->
# Find the tooltip
tooltipEl = angular.element('#chartjs-tooltip')
if (!tooltipEl[0])
angular.element('body').append('<div id="chartjs-tooltip"></div>')
tooltipEl = angular.element('#chartjs-tooltip')
# Hide if no tooltip
if (!tooltip.opacity)
tooltipEl.css({
opacity: 0.5
})
return
# Set caret Position
tooltipEl.removeClass('above below no-transform')
if (tooltip.yAlign)
tooltipEl.addClass(tooltip.yAlign)
else
tooltipEl.addClass('no-transform')
# Set Text
if (tooltip.body)
innerHtml = _.compact([
(tooltip.beforeTitle || []).join('<br/>'), (tooltip.title || []).join('<br/>'), (tooltip.afterTitle || []).join('<br/>'), (tooltip.beforeBody || []).join('<br/>'), (tooltip.body || []).join('<br/>'), (tooltip.afterBody || []).join('<br/>'), (tooltip.beforeFooter || [])
.join('<br/>'), (tooltip.footer || []).join('<br/>'), (tooltip.afterFooter || []).join('<br/>')
])
tooltipEl.html(innerHtml.join('<br/>'))
# Alignment
canvasEl = angular.element(this._chart.canvas)
offset = canvasEl.offset()
# Avoid mouse glitches
canvasEl.bind 'mouseleave', (event) ->
tooltipEl.remove() unless event.relatedTarget.id == 'chartjs-tooltip'
tooltipEl.bind 'mouseleave', (event) ->
tooltipEl.remove() unless event.relatedTarget.tagName == 'CANVAS'
# Display, position, and set styles for font
tooltipEl.css({
'background-color': '#17262d'
color: 'white'
opacity: 1
transition: 'opacity 0.5s, top 0.5s, left 0.5s'
position: 'absolute'
width: tooltip.width ? "#{tooltip.width}px" : 'auto'
left: "#{offset.left + tooltip.x + 10}px"
top: "#{offset.top + tooltip.y + 10}px"
fontFamily: tooltip._fontFamily
fontSize: tooltip.fontSize
fontStyle: tooltip._fontStyle
padding: "#{tooltip.yPadding}px #{tooltip.xPadding}px"
'border-radius': '2px'
})
angular.merge Chart.defaults.global, {
defaultColor: _self.getColor(0)
tooltips:
titleFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
bodyFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
footerFontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
enabled: false
custom: _self.customTooltip
elements:
point:
hitRadius: 8
hoverRadius: 8
line:
tension: 0
borderWidth: 2
legend:
display: false
}
angular.merge Chart.defaults.scale, {
ticks:
beginAtZero: true
minRotation: 0
# maxRotation: 0
fontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
scaleLabel:
fontFamily: "Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif"
}
@setTooltipsTextLayout = (opts, showSerieInTitle=false) ->
angular.merge opts, {
tooltips:
callbacks:
title: (context, data) ->
unless showSerieInTitle
return data.labels[context[0].index]
else
title = [data.labels[context[0].index]]
title.push data.datasets[context[0].datasetIndex].label if data.datasets[context[0].datasetIndex].label
return title.join(' | ')
label: (context, data) ->
currency = opts.currency || ImpacDashboardsSvc.getCurrentDashboard().currency
unless currency=='hide'
return $filter('mnoCurrency')(data.datasets[context.datasetIndex].data[context.index], currency)
else
return data.datasets[context.datasetIndex].data[context.index]
}
# Line Chart of several datasets | versusMode can be used to force positive/negative colors
# ----------
# inputDataArray:
# [{
# title: "Serie",
# labels: ["date1","date2"],
# values: [15.25,7.4]
# }]
# versusMode: put the negative dataset first
@lineChart = (inputDataArray, opts={}, versusMode=false) ->
_self.setTooltipsTextLayout(opts, true)
index = 0
isFilled = inputDataArray.length == 1
singleValue = false
if inputDataArray[0].labels.length < 2
# if the values array have only one entry, we double it to avoid the display of a single point on the chart
singleValue = true
inputDataArray[0].labels.push inputDataArray[0].labels[0]
# Defaut when several datasets or single dataset but with only one value: straight lines without point dot
if inputDataArray.length > 1 || (opts.pointDot? && !opts.pointDot) || singleValue
angular.merge(opts, {
elements:
point:
radius: 0.0001
line:
tension: 0.3
})
return {
type: 'line',
options: opts,
data: {
labels: inputDataArray[0].labels,
datasets: _.map inputDataArray, (inputData) ->
if singleValue
inputData.values.push inputData.values[0]
if versusMode
if index == 0
color = _self.getNegativeColor()
else
color = _self.getPositiveColor()
else
color = _self.getColor(index)
index++
return {
label: inputData.title
data: inputData.values
fill: isFilled
backgroundColor: lightenColor(color,0.3)
borderColor: color
pointBorderColor: color
pointBackgroundColor: color
pointHoverBackgroundColor: 'rgb(255,255,255)'
}
}
}
# TODO refactor barChart and combinedChart (now we have chartjs v2.0...)
# Bar Chart of one dataset with several values (eg: different coloured bars for several accounts)
# ----------
# inputData:
# {
# labels: ["Account1","Account2"],
# values: [15.25,7.4]
# }
# positivesOnly: if true (default), negative bars will be turned into their opposite
@barChart = (inputData, opts={}, positivesOnly=true) ->
_self.setTooltipsTextLayout(opts)
index = 0
colors = []
for value in inputData.values
inputData.values[index] = Math.abs(value) if positivesOnly
colors.push(_self.getColor(index))
index++
return {
type: 'bar'
options: opts
data: {
labels: inputData.labels
datasets: [{ backgroundColor: colors, data: inputData.values }]
}
}
# Bar Chart of several datasets with several values each
# ----------
# inputData:
# labels: ['Company A', 'Company B']
# datasets:
# [
# {title: 'ASSET', values: [1566,56156]}
# {title: 'LIABILITY', values: [67868,686]}
# ]
# positivesOnly: if true (default), negative bars will be turned into their opposite
@combinedBarChart = (inputData, opts={}, positivesOnly=true, versusMode=false) ->
_self.setTooltipsTextLayout(opts, true)
index = 0
result = {
type: 'bar',
options: opts,
data: {
labels: inputData.labels
datasets: _.map inputData.datasets, (dataset) ->
color = _self.getColor(index)
if versusMode
if index == 0
color = _self.getNegativeColor()
else
color = _self.getPositiveColor()
index++
if positivesOnly
for value in dataset.values
value = Math.abs(value)
return {
label: dataset.title,
data: dataset.values,
backgroundColor: color,
}
}
}
return result
# inputData:
# [ {
# label: "Customer PI:NAME:<NAME>END_PI",
# value: 1550.12
# ] }
@pieChart = (inputData, opts={}, versusMode=false) ->
_self.setTooltipsTextLayout(opts)
index=0
colors=[]
if versusMode
colors.push(_self.getNegativeColor())
for data in inputData
colors.push(_self.getPositiveColor()) unless index==0
index++
else
for data in inputData
colors.push(_self.getColor(index))
index++
{
type: 'doughnut',
options: opts,
data: {
datasets: [
{
data: _.map inputData, ( (data) -> Math.abs(data.value) )
backgroundColor: colors
}
]
labels: _.map inputData, ( (data) -> data.label )
}
}
return
)
|
[
{
"context": "main par l'utilisateur \n# - Zoom de type Control + Molette\n# - Rotation de l'appareil (passage de smartphone",
"end": 1505,
"score": 0.9546427726745605,
"start": 1498,
"tag": "NAME",
"value": "Molette"
}
] | app/assets/scripts/insearch.coffee | kylekatarnls/insearch | 0 | //- require 'jquery-1.11.0.min'
//- require 'bootstrap.min'
//- require 'typeahead'
# Menus déroulant au clic
# Exemple : lorsqu'on clique sur le bouton tout en haut à droite,
# La liste des choix possibles pour le nombre de résultats par page se déroule
$('.dropdown-toggle').click ->
$('[aria-labelledby="' + $(@).attr('id') + '"]').slideToggle()
return
# Insertion dynamique du début du titre dans un <span> dans le but de l'afficher/masquer ultérieurement
(->
string = $('h1').html()
index = string.indexOf "-"
if index isnt -1
$('h1').html("<span class='mobile-hidden'>" + string.substr(0, index + 1) + "</span>" + string.substr(index + 1))
return
)()
# Afficher/masquer les formulaires en fondu lors du clic sur un bouton
# Exemple : lorsqu'on clique sur le bouton + en haut à droite,
# Le formulaire pour ajouter une URL apparaît
(($panel) ->
$form = $panel.find 'form'
$panel.find('a.btn').click ->
$form.fadeToggle()
return
return
) $ '.option-panel'
# Si on N'est PAS sur une page de résultats (résultats de recherche / les plus populaires / historique)
# Alors,
unless $('h1').is '.results'
$choicePerPage = $ '[aria-labelledby="choice-per-page"]'
$choicePerPage.find('a[data-value]').click ->
$('input[name="resultsPerPage"]').val $(@).data 'value'
$choicePerPage.slideUp()
false
# La fonction resize est exécuté à chaque fois que les dimensions de la fenêtre changent, cela inclut :
# - Redimension à la main par l'utilisateur
# - Zoom de type Control + Molette
# - Rotation de l'appareil (passage de smartphone/tablette à l'horizontal/vertical)
# - etc.
resize = ->
screenWidth = $('body').width()
# Desktop
if(screenWidth > 640)
$('.navbar-inner .input-group').removeClass 'input-group-sm'
$('.navbar-inner .btn-group').removeClass 'btn-group-sm'
# Mobile
else
$('.navbar-inner .input-group').addClass 'input-group-sm'
$('.navbar-inner .btn-group').addClass 'btn-group-sm'
$('.navbar-inner .btn-group').css
clear: ''
float: ''
margin: ''
$('h1').css
marginTop: ''
fontSize: ''
$('#footer').css
fontSize: ''
$('.mobile-hidden').show()
# Très étroit (mobile en portrait)
if $('.navbar-inner').height() > 50
$('.navbar-inner .btn-group').css
clear: 'right'
float: 'right'
margin: '11px 0 -70px'
$('h1').css
marginTop: '0'
fontSize: '22px'
$('#footer').css
fontSize: '12px'
$('.mobile-hidden').hide()
return
resize()
$(window).resize resize
# Auto-complétion : lorsqu'on tape dans la barre de recherche, des solutions possibles
# sont proposées à l'utilisateur
$('[name="q"]').autocomplete(
(query, callback) ->
$.ajax
url: '/autocomplete'
type: 'POST'
dataType: 'json'
data:
q: query
error: ->
callback()
return
success: (res) ->
callback res
return
return
, (value) ->
switch value.toLowerCase()
when "slide", "bounce"
$("body").animate
paddingTop: 160
, 200, ->
$("body").animate
paddingTop: 60
, 200
return
when "roll", "barrel roll", "rotate"
$("body").animate(
rotate: 0
, 0).animate
rotate: 1
,
duration: 800
step: (now) ->
prop = "rotate(" + (Math.round(now * 2 * 360) % 360) + "deg)"
$(@).css
"-webkit-transform": prop
"-moz-transform": prop
transform: prop
return
when "shake", "rumble"
$("body").animate
marginLeft: -80
, 100, ->
$("body").animate
marginLeft: 80
, 200, ->
$("body").animate
marginLeft: -80
, 200, ->
$("body").animate
marginLeft: 0
, 100
return
return
return
)
$(document).on('click', '.remember-me', ->
$this = $(@);
if $this.is '.selected'
$(@).removeClass('selected')
.next('input')
.val('')
else
$(@).addClass('selected')
.next('input')
.val('on')
)
| 6251 | //- require 'jquery-1.11.0.min'
//- require 'bootstrap.min'
//- require 'typeahead'
# Menus déroulant au clic
# Exemple : lorsqu'on clique sur le bouton tout en haut à droite,
# La liste des choix possibles pour le nombre de résultats par page se déroule
$('.dropdown-toggle').click ->
$('[aria-labelledby="' + $(@).attr('id') + '"]').slideToggle()
return
# Insertion dynamique du début du titre dans un <span> dans le but de l'afficher/masquer ultérieurement
(->
string = $('h1').html()
index = string.indexOf "-"
if index isnt -1
$('h1').html("<span class='mobile-hidden'>" + string.substr(0, index + 1) + "</span>" + string.substr(index + 1))
return
)()
# Afficher/masquer les formulaires en fondu lors du clic sur un bouton
# Exemple : lorsqu'on clique sur le bouton + en haut à droite,
# Le formulaire pour ajouter une URL apparaît
(($panel) ->
$form = $panel.find 'form'
$panel.find('a.btn').click ->
$form.fadeToggle()
return
return
) $ '.option-panel'
# Si on N'est PAS sur une page de résultats (résultats de recherche / les plus populaires / historique)
# Alors,
unless $('h1').is '.results'
$choicePerPage = $ '[aria-labelledby="choice-per-page"]'
$choicePerPage.find('a[data-value]').click ->
$('input[name="resultsPerPage"]').val $(@).data 'value'
$choicePerPage.slideUp()
false
# La fonction resize est exécuté à chaque fois que les dimensions de la fenêtre changent, cela inclut :
# - Redimension à la main par l'utilisateur
# - Zoom de type Control + <NAME>
# - Rotation de l'appareil (passage de smartphone/tablette à l'horizontal/vertical)
# - etc.
resize = ->
screenWidth = $('body').width()
# Desktop
if(screenWidth > 640)
$('.navbar-inner .input-group').removeClass 'input-group-sm'
$('.navbar-inner .btn-group').removeClass 'btn-group-sm'
# Mobile
else
$('.navbar-inner .input-group').addClass 'input-group-sm'
$('.navbar-inner .btn-group').addClass 'btn-group-sm'
$('.navbar-inner .btn-group').css
clear: ''
float: ''
margin: ''
$('h1').css
marginTop: ''
fontSize: ''
$('#footer').css
fontSize: ''
$('.mobile-hidden').show()
# Très étroit (mobile en portrait)
if $('.navbar-inner').height() > 50
$('.navbar-inner .btn-group').css
clear: 'right'
float: 'right'
margin: '11px 0 -70px'
$('h1').css
marginTop: '0'
fontSize: '22px'
$('#footer').css
fontSize: '12px'
$('.mobile-hidden').hide()
return
resize()
$(window).resize resize
# Auto-complétion : lorsqu'on tape dans la barre de recherche, des solutions possibles
# sont proposées à l'utilisateur
$('[name="q"]').autocomplete(
(query, callback) ->
$.ajax
url: '/autocomplete'
type: 'POST'
dataType: 'json'
data:
q: query
error: ->
callback()
return
success: (res) ->
callback res
return
return
, (value) ->
switch value.toLowerCase()
when "slide", "bounce"
$("body").animate
paddingTop: 160
, 200, ->
$("body").animate
paddingTop: 60
, 200
return
when "roll", "barrel roll", "rotate"
$("body").animate(
rotate: 0
, 0).animate
rotate: 1
,
duration: 800
step: (now) ->
prop = "rotate(" + (Math.round(now * 2 * 360) % 360) + "deg)"
$(@).css
"-webkit-transform": prop
"-moz-transform": prop
transform: prop
return
when "shake", "rumble"
$("body").animate
marginLeft: -80
, 100, ->
$("body").animate
marginLeft: 80
, 200, ->
$("body").animate
marginLeft: -80
, 200, ->
$("body").animate
marginLeft: 0
, 100
return
return
return
)
$(document).on('click', '.remember-me', ->
$this = $(@);
if $this.is '.selected'
$(@).removeClass('selected')
.next('input')
.val('')
else
$(@).addClass('selected')
.next('input')
.val('on')
)
| true | //- require 'jquery-1.11.0.min'
//- require 'bootstrap.min'
//- require 'typeahead'
# Menus déroulant au clic
# Exemple : lorsqu'on clique sur le bouton tout en haut à droite,
# La liste des choix possibles pour le nombre de résultats par page se déroule
$('.dropdown-toggle').click ->
$('[aria-labelledby="' + $(@).attr('id') + '"]').slideToggle()
return
# Insertion dynamique du début du titre dans un <span> dans le but de l'afficher/masquer ultérieurement
(->
string = $('h1').html()
index = string.indexOf "-"
if index isnt -1
$('h1').html("<span class='mobile-hidden'>" + string.substr(0, index + 1) + "</span>" + string.substr(index + 1))
return
)()
# Afficher/masquer les formulaires en fondu lors du clic sur un bouton
# Exemple : lorsqu'on clique sur le bouton + en haut à droite,
# Le formulaire pour ajouter une URL apparaît
(($panel) ->
$form = $panel.find 'form'
$panel.find('a.btn').click ->
$form.fadeToggle()
return
return
) $ '.option-panel'
# Si on N'est PAS sur une page de résultats (résultats de recherche / les plus populaires / historique)
# Alors,
unless $('h1').is '.results'
$choicePerPage = $ '[aria-labelledby="choice-per-page"]'
$choicePerPage.find('a[data-value]').click ->
$('input[name="resultsPerPage"]').val $(@).data 'value'
$choicePerPage.slideUp()
false
# La fonction resize est exécuté à chaque fois que les dimensions de la fenêtre changent, cela inclut :
# - Redimension à la main par l'utilisateur
# - Zoom de type Control + PI:NAME:<NAME>END_PI
# - Rotation de l'appareil (passage de smartphone/tablette à l'horizontal/vertical)
# - etc.
resize = ->
screenWidth = $('body').width()
# Desktop
if(screenWidth > 640)
$('.navbar-inner .input-group').removeClass 'input-group-sm'
$('.navbar-inner .btn-group').removeClass 'btn-group-sm'
# Mobile
else
$('.navbar-inner .input-group').addClass 'input-group-sm'
$('.navbar-inner .btn-group').addClass 'btn-group-sm'
$('.navbar-inner .btn-group').css
clear: ''
float: ''
margin: ''
$('h1').css
marginTop: ''
fontSize: ''
$('#footer').css
fontSize: ''
$('.mobile-hidden').show()
# Très étroit (mobile en portrait)
if $('.navbar-inner').height() > 50
$('.navbar-inner .btn-group').css
clear: 'right'
float: 'right'
margin: '11px 0 -70px'
$('h1').css
marginTop: '0'
fontSize: '22px'
$('#footer').css
fontSize: '12px'
$('.mobile-hidden').hide()
return
resize()
$(window).resize resize
# Auto-complétion : lorsqu'on tape dans la barre de recherche, des solutions possibles
# sont proposées à l'utilisateur
$('[name="q"]').autocomplete(
(query, callback) ->
$.ajax
url: '/autocomplete'
type: 'POST'
dataType: 'json'
data:
q: query
error: ->
callback()
return
success: (res) ->
callback res
return
return
, (value) ->
switch value.toLowerCase()
when "slide", "bounce"
$("body").animate
paddingTop: 160
, 200, ->
$("body").animate
paddingTop: 60
, 200
return
when "roll", "barrel roll", "rotate"
$("body").animate(
rotate: 0
, 0).animate
rotate: 1
,
duration: 800
step: (now) ->
prop = "rotate(" + (Math.round(now * 2 * 360) % 360) + "deg)"
$(@).css
"-webkit-transform": prop
"-moz-transform": prop
transform: prop
return
when "shake", "rumble"
$("body").animate
marginLeft: -80
, 100, ->
$("body").animate
marginLeft: 80
, 200, ->
$("body").animate
marginLeft: -80
, 200, ->
$("body").animate
marginLeft: 0
, 100
return
return
return
)
$(document).on('click', '.remember-me', ->
$this = $(@);
if $this.is '.selected'
$(@).removeClass('selected')
.next('input')
.val('')
else
$(@).addClass('selected')
.next('input')
.val('on')
)
|
[
{
"context": "efault()\n Meteor.loginWithPassword {username: 'sprohaska'}, password, ->\n console.log 'logged in spro",
"end": 200,
"score": 0.9996061325073242,
"start": 191,
"tag": "USERNAME",
"value": "sprohaska"
},
{
"context": "ska'}, password, ->\n console.log 'logg... | apps/nog-app/meteor/client/templates/testConfig.coffee | nogproject/nog | 0 | password = Meteor.settings.public?.tests?.passwords?.user
Template.testConfig.events
'click .js-login-sprohaska': (ev) ->
ev.preventDefault()
Meteor.loginWithPassword {username: 'sprohaska'}, password, ->
console.log 'logged in sprohaska'
'click .js-login-alovelace': (ev) ->
ev.preventDefault()
Meteor.loginWithPassword {username: 'alovelace'}, password, ->
console.log 'logged in alovelace'
'click .js-logout': (ev) ->
ev.preventDefault()
Meteor.logout ->
console.log 'logged out'
| 68982 | password = Meteor.settings.public?.tests?.passwords?.user
Template.testConfig.events
'click .js-login-sprohaska': (ev) ->
ev.preventDefault()
Meteor.loginWithPassword {username: 'sprohaska'}, password, ->
console.log 'logged in s<PASSWORD>'
'click .js-login-alovelace': (ev) ->
ev.preventDefault()
Meteor.loginWithPassword {username: 'alovelace'}, password, ->
console.log 'logged in alovelace'
'click .js-logout': (ev) ->
ev.preventDefault()
Meteor.logout ->
console.log 'logged out'
| true | password = Meteor.settings.public?.tests?.passwords?.user
Template.testConfig.events
'click .js-login-sprohaska': (ev) ->
ev.preventDefault()
Meteor.loginWithPassword {username: 'sprohaska'}, password, ->
console.log 'logged in sPI:PASSWORD:<PASSWORD>END_PI'
'click .js-login-alovelace': (ev) ->
ev.preventDefault()
Meteor.loginWithPassword {username: 'alovelace'}, password, ->
console.log 'logged in alovelace'
'click .js-logout': (ev) ->
ev.preventDefault()
Meteor.logout ->
console.log 'logged out'
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.9998373985290527,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | src/material/basic.coffee | OniDaito/pxljs | 1 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Material} = require "./material"
{RGBA} = require "../colour/colour"
{uber_uniform_colour, uber_vertex_colour, uber_texture_mat} = require '../gl/uber_shader_paths'
# ## BasicColourMaterial
# A Basic material that is made up of a single colour
class BasicColourMaterial extends Material
# **@constructor**
# - **colour** - a Colour.RGB or Colour.RGBA
constructor : (@colour) ->
super()
if not @colour?
@colour = new RGBA.WHITE()
if not @colour.a?
@colour = new RGBA(@colour.r, @colour.g, @colour.b, 1.0)
@contract.roles.uColour = "colour"
@_uber0 = uber_uniform_colour true, @_uber0
@_uber_defines = ['BASIC_COLOUR']
# ## VertexColourMaterial
# A Basic material that takes the colours from the vertices
class VertexColourMaterial extends Material
# **@constructor**
constructor : () ->
super()
@_uber0 = uber_vertex_colour true, @_uber0
@_uber_defines = ['VERTEX_COLOUR']
# ## TextureMaterial
# A Basic material that uses a texture for it its albedo.
class TextureMaterial extends Material
# **constructor**
# - **texture** - a Texture
constructor : (@texture) ->
super()
@_uber0 = uber_texture_mat true, @_uber0
@_uber_defines = ['MATERIAL_TEXTURE', 'VERTEX_TEXTURE']
@contract.roles.uSamplerTexture = "texture"
_preDraw : () ->
@texture.bind()
module.exports =
Material : Material
BasicColourMaterial : BasicColourMaterial
VertexColourMaterial : VertexColourMaterial
TextureMaterial : TextureMaterial
| 171991 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Material} = require "./material"
{RGBA} = require "../colour/colour"
{uber_uniform_colour, uber_vertex_colour, uber_texture_mat} = require '../gl/uber_shader_paths'
# ## BasicColourMaterial
# A Basic material that is made up of a single colour
class BasicColourMaterial extends Material
# **@constructor**
# - **colour** - a Colour.RGB or Colour.RGBA
constructor : (@colour) ->
super()
if not @colour?
@colour = new RGBA.WHITE()
if not @colour.a?
@colour = new RGBA(@colour.r, @colour.g, @colour.b, 1.0)
@contract.roles.uColour = "colour"
@_uber0 = uber_uniform_colour true, @_uber0
@_uber_defines = ['BASIC_COLOUR']
# ## VertexColourMaterial
# A Basic material that takes the colours from the vertices
class VertexColourMaterial extends Material
# **@constructor**
constructor : () ->
super()
@_uber0 = uber_vertex_colour true, @_uber0
@_uber_defines = ['VERTEX_COLOUR']
# ## TextureMaterial
# A Basic material that uses a texture for it its albedo.
class TextureMaterial extends Material
# **constructor**
# - **texture** - a Texture
constructor : (@texture) ->
super()
@_uber0 = uber_texture_mat true, @_uber0
@_uber_defines = ['MATERIAL_TEXTURE', 'VERTEX_TEXTURE']
@contract.roles.uSamplerTexture = "texture"
_preDraw : () ->
@texture.bind()
module.exports =
Material : Material
BasicColourMaterial : BasicColourMaterial
VertexColourMaterial : VertexColourMaterial
TextureMaterial : TextureMaterial
| true | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
{Material} = require "./material"
{RGBA} = require "../colour/colour"
{uber_uniform_colour, uber_vertex_colour, uber_texture_mat} = require '../gl/uber_shader_paths'
# ## BasicColourMaterial
# A Basic material that is made up of a single colour
class BasicColourMaterial extends Material
# **@constructor**
# - **colour** - a Colour.RGB or Colour.RGBA
constructor : (@colour) ->
super()
if not @colour?
@colour = new RGBA.WHITE()
if not @colour.a?
@colour = new RGBA(@colour.r, @colour.g, @colour.b, 1.0)
@contract.roles.uColour = "colour"
@_uber0 = uber_uniform_colour true, @_uber0
@_uber_defines = ['BASIC_COLOUR']
# ## VertexColourMaterial
# A Basic material that takes the colours from the vertices
class VertexColourMaterial extends Material
# **@constructor**
constructor : () ->
super()
@_uber0 = uber_vertex_colour true, @_uber0
@_uber_defines = ['VERTEX_COLOUR']
# ## TextureMaterial
# A Basic material that uses a texture for it its albedo.
class TextureMaterial extends Material
# **constructor**
# - **texture** - a Texture
constructor : (@texture) ->
super()
@_uber0 = uber_texture_mat true, @_uber0
@_uber_defines = ['MATERIAL_TEXTURE', 'VERTEX_TEXTURE']
@contract.roles.uSamplerTexture = "texture"
_preDraw : () ->
@texture.bind()
module.exports =
Material : Material
BasicColourMaterial : BasicColourMaterial
VertexColourMaterial : VertexColourMaterial
TextureMaterial : TextureMaterial
|
[
{
"context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed under the Apach",
"end": 35,
"score": 0.999821662902832,
"start": 24,
"tag": "NAME",
"value": "Dan Elliott"
},
{
"context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed u... | clients/www/src/coffee/handler/isadore_current_data_handler.coffee | bluthen/isadore_server | 0 | # Copyright 2010-2019 Dan Elliott, Russell Valentine
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Other View format
#"other_views": [ #Array of view objects
# {
# "title": "Fill View", #display title of view
# "type": "fill_view|diagnostics|sensor_view", #Type of view
# #The view object for fill_view
# "view": {
# "fill_view_list": [ # Array list of fill_views, will do it in order
# {
# "view": "fill_view", #name of the view there are fill_view and fill_view_cell# as possibilities
# # fill_view goes through a list of bins and fill_view_cell# is more standalone.
# # you can have multiple fill_view with different bins it goes through.
# # You might want to do fill_view, some fill_view_cells, and fill_view again.
# "bin_ids": [ # Array of bin ID's to go through in the "fill_view" view
# 12, 13, 14, ...
# ],
# "options": { # Fill view options
# "table_class": "original_fill_view" #What class this fill_view table should have original_fill_view or pleasent_fill_view for example
# "hide_labels": true, #default false, this hides the left side labels of a fill_view
# "column_class": [ #Allows settings column css class based off result of a function See "FillViewStyler"
# {
# "func": "fillStatusStyle", #Function to use to determine column css class
# "keys": [ #data keys that go with the function.
# "fill.filled_datetime", "fill.emptied_datetime", "fill.air_begin_datetime", ...
# ]
# }
# ],
# "hover": { #Hoover options
# "row_disable": true, #Disable row hovering, default false
# "thead_enable": true, #Enable hovering head when novered over column default false
# }
# "clickfunc": "fillDialog|binLightBoxClick,.." #Which function in CurrentDataClick to use when clicking on a the table, default 'binLightboxClick'
# }
# },
# {
# "view": "fill_view_cell1", #Id for a cell view to go through
# "options": {
# "table_class": "original_fill_view" #What class this cell view table will have
# }
# }
# {
# "view": "raw1", #Just display some raw html, no key below that needs to match.
# "html": "<table class=\"fill_view_legend\"><tr><td class=\"bolded\" colspan=\"2\">Legend</td></tr><tr><td>Up Air</td><td class=\"fv_upair\">Value</td></tr><tr><td>Down Air</td><td class=\"fv_downair\">Value</td></tr><tr><td>Burners</td><td>PV (SP)</td></tr><tr><td>Full/Drying</td><td class=\"fv_full\"></td></tr><tr><td>Empty</td><td class=\"fv_empty\"></td></tr><tr><td>Shelling</td><td class=\"fv_shelling\"></td></tr><tr><td>Filling</td><td class=\"fv_filling\"></td></tr></table>" #html as a string
# }
# ... other fill_view_cells, or fill_views, or raw lists...
# ],
# "fill_view": [ #What to show in the fill_view
# {
# "label": "Fill #", #Lable to display on the left of fill_view table
# "keys": [ #Array of data keys, could be fill.fill_column or readings.binsection_sensorshortname
# "fill.fill_number"
# "readings.top_temp",
# "readings.bottom_temp"
# ],
# "format": null, #Which format function to send data to. See object "FillViewFormater"
# "class": [ #Which classes the contents of a colum in a fill_view should have
# {
# "func": "upDownAirStyle", #Function to call in "FillViewStyler"
# "keys": [ #data keys that go to function
# "readings.top_temp", "readings.bottom_temp", ...
# ]
# },
# ... More class functions or string for static class...
# ]
# },
# ... more stuff to show in fill_view
# ],
# "fill_view_cell1": [ #What to display in the cell table
# {
# "label": "Burner 1", #Cell name
# "class": "bolded" #Class content should have in cell. Can also be a array with object.func object.keys like in fill_view
# },
# {
# "label": "Burner SP",
# "bin_id": 100, #Which bins can be array of multiple binIds, data keys then being readings0, readings1, ..., instead of just readings
# "colspan": 3, # How many columns the cell should take up, default is 1
# "keys": [ #Data keys similar to fill_view keys
# "readings.burner.sp"
# ],
# "format": "fixed1T" #format function see "FillViewFormater"
# "display": "adjacent" #if "adjacent, there should be no linebreak between label and value
# "readings_func": "upBinsCount" # should get value using a entire readings function, instead of bin/fill based, see "FillViewFunc"
# },
# ... More cells to display ...
# ],
# ... More fill_view_cell# ...
# }
# # diagnostics view
# "view": {
# "interval": 1500 #refresh_in_milliseconds
# }
# # sensor_view
# "view": {
# block: [ #Can have any number of types in any order
# #Type table
# {
# "type": "table",
# "row_type": "bin|section",
# "alignment": "full|left|right",
# "columns": [
# {
# "bin_section_id": int, # If 'bin' row_type, or null if just want a label column
# "read_type_id": int, # Can be null if just want a label column
# "column_label": string, #keys: $bin_section_name$, $read_type_short_name$, $read_type_units$, $read_type_name$
# "value": string # keys: $bin_number$, $bin_name$, $bin_section_name$, $valueF1$, $valueF2$
# }, ...
# ],
# "bin_ids": [int, int, ...], # if 'bin' row_type
#
# "bin_id": int, # if 'section' row_type
# "bin_section_ids": [int, int, ...], # if 'section' row_type
#
# "header": { # or can be null
# "label": string,
# "class": string
# }
# },
# #Type diagram
# {
# "type": "diagram",
# "yindexes": [int, int, ...], # or "all"
# "header": { # or can be null
# "label": string,
# "class": string
# }
# },
# {
# "type": "config"
# }
# ...
# ]
# }
# }
FillViewStyler = {
upDownAirStyle: (topTemp, bottomTemp) ->
if topTemp > bottomTemp
return "fv_downair"
else if(topTemp < bottomTemp)
return "fv_upair"
return null
fillStatusStyle: (type, filled, emptied, air_begin, air_end, roll) ->
if type == 2
return "fv_bypass"
else
if air_end and !emptied
return "fv_shelling"
if air_begin and !air_end
return "fv_drying"
if filled and !air_begin
return "fv_filling"
if not filled
return "fv_empty"
return "fv_unknown"
}
FillViewFormater = {
lastSample: (during_mc) ->
last = null
for mcd in during_mc
mc = mcd[0]
d = newDate(mcd[1])
if not last or d > last[1]
last = [mc, d]
if last
return last[0].toFixed(1)
lastSampleDate: (during_mc) ->
last = null
for mcd in during_mc
mc = mcd[0]
d = newDate(mcd[1])
if not last or d > last[1]
last = [mc, d]
if last
return HTMLHelper.dateToReadableO3(last[1])
_mean: (array) ->
if not array
return null
if not _.isArray(array)
return array
if array.length == 0
return null
s = 0
for a in array
s += a
s=s/array.length
return s
mean: (array) ->
if array
if not _.isArray(array)
return array.toFixed(2)
t = @_mean(array)
if t
return t.toFixed(2)
return null
meanArg: (array...) ->
return @mean(array)
timeUpCalc: (begin, roll) ->
# TODO: Air deducts
# TODO: Support multiple rolls
if begin
begin = newDate(begin)
if roll and roll.length > 0
if _.isArray(roll)
t = newDate(roll[0])
else
t = newDate(roll)
return FillViewFormater.timeDiff(t, begin)
else
return FillViewFormater.timeDiffNow(begin)
return null
timeDiffNow: (time, orend) ->
# TODO: Air deducts
# TODO: Support multiple rolls
if orend and orend != ''
orend = newDate(orend)
else
orend = null
t = null
now = new Date()
if time
if _.isArray(time)
t = newDate(time[0])
else
t = newDate(time)
if orend
t = FillViewFormater.timeDiff(orend, t)
else
t = FillViewFormater.timeDiff(now, t)
return t
timeDiff: (gr, ls) ->
if not gr or not ls
return null
else
return ((gr.getTime() - ls.getTime())/(1000.0*60*60)).toFixed(2)
airDirection: (topt, bott) ->
t = @_mean(topt)
b = @_mean(bott)
if t and b
r=(b-t)
if r > 0
return 'Up'
else if r < 0
return 'Down'
return null
fixed1T: (t, u) ->
t2 = @_mean(t)
if t2
return t2.toFixed(1)
return null
fixed1P: (rh) ->
t2 = @_mean(rh)
if t2
return t2.toFixed(1)
return null
numberSplit: (str) ->
a = str.split(' ')
for v in a
i = parseInt(v, 10)
if(!isNaN(i))
return i
return NaN
twoPerns: (v1, v2) ->
return v1.toFixed(1)+' ('+v2.toFixed(1)+')'
}
FillViewFunc = {
_binCount: (up, readings, fills, nameFilter) ->
upCount = 0
downCount = 0
for binId, bin of readings
binId = parseInt(binId, 10)
if nameFilter
bn = _.findWhere(IsadoreData.bins, {id: binId})
if not bn.name.match(nameFilter)
continue
if bin.top_temp? and bin.bottom_temp?
fill = CurrentDataUtil.getBinFill(fills, binId, false)
if not fill.id?
continue
fstyle = FillViewStyler.fillStatusStyle(fill.fill_type_id, fill.filled_datetime, fill.emptied_datetime, fill.air_begin_datetime, fill.air_end_datetime, fill.roll_datetime)
if fstyle != "fv_drying"
continue
if up and bin.top_temp < bin.bottom_temp
upCount++
if !up and bin.top_temp > bin.bottom_temp
downCount++
if up
return upCount + " Up Bins"
else
return downCount + " Down Bins"
# Calculates and outputs string of number of bins in up air
upBinsCount: (readings, fills) ->
return this._binCount(true, readings, fills)
# Calculates and ouputs string number of bins in down air
downBinsCount: (readings, fills) ->
return this._binCount(false, readings, fills)
#TODO: Be able to send custom arguments to readings_func
# Calculates and outputs string of number of bins in up air
upBinsCountFilter1: (readings, fills) ->
return this._binCount(true, readings, fills, new RegExp('^Bin 1'))
# Calculates and ouputs string number of bins in down air
downBinsCountFilter1: (readings, fills) ->
return this._binCount(false, readings, fills, new RegExp('^Bin 1'))
# Calculates and outputs string of number of bins in up air
upBinsCountFilter2: (readings, fills) ->
return this._binCount(true, readings, fills, new RegExp('^Bin 2'))
# Calculates and ouputs string number of bins in down air
downBinsCountFilter2: (readings, fills) ->
return this._binCount(false, readings, fills, new RegExp('^Bin 2'))
}
window.CurrentDataUtil = {
getBinFill: (fills, bin_id, air_end) ->
now = new Date()
for fill in fills by -1
if fill and fill.bin_id == bin_id and not fill.emptied_datetime? and (not air_end || not fill.air_end_datetime?)
if fill.filled_datetime?
fill.filled_datetime = newDate(fill.filled_datetime)
if fill.air_begin_datetime?
fill.air_begin_datetime = newDate(fill.air_begin_datetime)
#If filled > now and (not emptied) or air_begin > now and not air_end
if ((fill.filled_datetime? and fill.filled_datetime < now) or (fill.air_begin_datetime? and fill.air_begin_datetime < now))
return fill
return {}
}
CurrentDataClick = {
_getFillYear: (yfill) ->
if yfill.filled_datetime?
year = newDate(yfill.filled_datetime).getFullYear()
else
year = newDate(yfill.air_begin_datetime).getFullYear()
return year
_openNewFill: (binId) ->
lightboxHandlers.editFillLightbox.open({
year: new Date().getFullYear()
bin_id: binId
})
_openEditFill: (fill) ->
self=this
lightboxHandlers.editFillLightbox.open({year: self._getFillYear(fill), fill_id: fill.id})
binLightboxClick: (binId, fill) ->
lightboxHandlers.binLightbox.open(binId)
fillDialog: (binId, fill) ->
#TODO: Check privs do binLightboxClick if not enough privs
bin = IsadoreData.getBin(binId)
hasPriv = true
if not hasPriv or bin.name.indexOf('Bin') != 0
this.binLightboxClick(binId, fill)
else
statusStyle = FillViewStyler.fillStatusStyle(fill.fill_type_id, fill.filled_datetime, fill.emptied_datetime, fill.air_begin_datetime, fill.air_end_datetime, fill.roll_datetime)
if statusStyle == 'fv_empty'
this._openNewFill(binId)
else
this._openEditFill(fill)
}
class window.CurrentDataFillViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_fills = []
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
</h1>
""")
@_$overlay = $('<div class="fill_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
_getBinReadings: (bin_id) ->
if @_readings?.hasOwnProperty(bin_id)
return @_readings[bin_id]
return {}
_getCellData: (bin_id) ->
data = {}
if _.isArray(bin_id)
for i in [0...bin_id.length]
data['fill'+i] = CurrentDataUtil.getBinFill(@_fills, bin_id[i], false)
data['readings'+i] = @_getBinReadings(bin_id)
data['bin'+i] = IsadoreData.getBin(bin_id)
else
data = {fill: CurrentDataUtil.getBinFill(@_fills, bin_id, false), readings: @_getBinReadings(bin_id), bin: IsadoreData.getBin(bin_id)}
_getCellValue: (data, onlyIfFill, keys, format) ->
if onlyIfFill and not data.fill?.id?
return null
val = null
if format
try
args = []
for key in keys
obj = data
for k in key.split('.')
obj = obj[k]
args.push(obj)
val = FillViewFormater[format].apply(FillViewFormater, args)
catch e
#console?.error?(e)
val = null
else if keys.length > 0
try
obj = data
for k in keys[0].split('.')
obj = obj[k]
val= obj
if val and k.indexOf('_datetime') == k.length - 9
val = HTMLHelper.dateToReadableO3(newDate(val))
catch e
#console?.error?(e)
val = null
return val
_makeFillViewCellRow: (row) ->
if not @_viewConfig.hasOwnProperty(row.view)
return null
columns = @_viewConfig[row.view]
tr = $('<tr></tr>')
for column in columns
td = $('<td></td>')
cell_value = null
content = null
if column.label?
content = column.label
if column.class?
td.attr('class', column.class)
if column.colspan?
td.attr('colspan', column.colspan)
if column.keys? and column.bin_id?
cell_value = @_getCellValue(@_getCellData(column.bin_id), false, column.keys, column.format)
if cell_value
if content and (!column.display? or column.display != 'adjacent')
content += "<br/>"+cell_value
else
content = cell_value
if column.readings_func?
try
cell_value2 = FillViewFunc[column.readings_func].apply(FillViewFunc, [@_readings, @_fills])
if content and (!column.display? or column.display != 'adjacent')
content += "<br/>"+cell_value2
else
content = cell_value2
catch e
if console?.error?
console.error(e)
if content
td.html(content)
if column.bin_id?
td.attr('data-info', ''+column.bin_id)
tr.append(td)
return tr
_getDynamicClass: (classInfo, bin_id) ->
if _.isString(classInfo)
return classInfo
cssClasses = []
if !_.isArray(classInfo) and _.isObject(classInfo)
cl = @_getDynamicClassFromObj(classInfo, bin_id)
if cl
cssClasses.push(cl)
else if _.isArray(classInfo)
for classObj in classInfo
cl = @_getDynamicClassFromObj(classObj, bin_id)
if cl
cssClasses.push(cl)
return cssClasses.join(' ')
_getDynamicClassFromObj: (classObj, bin_id) ->
if classObj.plain? and _.isString(classObj.plain)
return classObj.plain
if classObj.func? and _.isString(classObj.func)
data = null
if classObj.bin_id?
data = @_getCellData(classObj.bin_id)
else if bin_id
data = @_getCellData(bin_id)
try
args = []
for key in classObj.keys
obj = data
for k in key.split('.')
obj = obj[k]
args.push(obj)
val = FillViewStyler[classObj.func].apply(FillViewStyler, args)
catch e
console?.error?(e)
val = null
return val
return null
_makeRowTable: (row) ->
table = $('<table class="fill_view_table"></table>')
fv = null
arow = row
if @_viewConfig.fill_view?
fv = @_viewConfig.fill_view
table_data = []
if row.view == 'fill_view'
# First row is bin_names
table_row = [{'data-info': -1, content: "Bin"}]
for bin_id in row.bin_ids
if bin_id == "empty"
table_row.push({'data-info': -1, content: ' ', 'data-columnclass': 'fv_nodata'})
else
name = IsadoreData.getBin(bin_id).name.split(" ")
if name.length > 1
name = name[1]
else
name = name[0]
table_column = {'data-info': bin_id, content: name}
if row.options?.column_class?
cl = @_getDynamicClass(row.options.column_class, bin_id)
if cl
table_column['data-columnclass'] = cl
table_row.push(table_column)
table_data.push(table_row)
for fv_row in fv
table_row=[]
table_row.push(fv_row.label)
for bin_id in row.bin_ids
if bin_id == "empty"
table_row.push(' ')
else
cell_value = @_getCellValue(@_getCellData(bin_id), true, fv_row.keys, fv_row.format)
cell_class = null
if fv_row.class?
cell_class = @_getDynamicClass(fv_row.class, bin_id)
table_row.push({'data-info': bin_id, content: cell_value, class: cell_class})
table_data.push(table_row)
#Make HTML from table_data
firstRow = true
thead = $('<thead></thead>')
table.append(thead)
tbody = $('<tbody></tbody>')
table.append(tbody)
for row in table_data
if firstRow
tr = $('<tr></tr>')
thead.append(tr)
else
tr = $('<tr></tr>')
tbody.append(tr)
firstColumn = true
for column in row
if firstColumn or firstRow
td = $('<th></th>')
else
td = $('<td></td>')
if _.isObject(column)
if column.hasOwnProperty('data-columnclass')
td.attr('data-columnclass', column['data-columnclass'])
if column.hasOwnProperty('data-info')
td.attr('data-info', column['data-info'])
if column.content?
td.html(column.content)
if column.class?
td.addClass(column.class)
else
td.html(column)
if not firstColumn or !(arow.options?.hide_labels)
tr.append(td)
firstColumn = false
firstRow = false
return table
_makeColumnClass: ($table) ->
$tr = $('tr:first-child', $table)
$('th, td', $tr).each( (index, element) ->
rc = $(element).attr('data-columnclass')
$(element).addClass(rc)
if rc
$('tbody tr', $table).each( (index2, element2) ->
$('th,td', element2).eq(index).addClass(rc)
)
)
_makeHover: (table, hoverOptions) ->
table.delegate('tbody th,tbody td', 'mouseover mouseleave', (e) ->
$ourTd=$(this)
if e.type == 'mouseover'
if not hoverOptions?.row_disable
$('th,td', $ourTd.parent()).addClass('hover')
if $ourTd.index() != 0
$('tbody tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).addClass('hover')
)
if hoverOptions?.thead_enable
$('thead tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).addClass('hover')
)
$ourTd.removeClass('hover').addClass('super_hover')
else
$('th,td', $ourTd.parent()).removeClass('hover')
$ourTd.removeClass('super_hover')
$('tbody tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).removeClass('hover')
)
$('thead tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).removeClass('hover')
)
)
_makeClick: (table, clickfunc) ->
self = this
$('tbody td, thead th', table).click((e) ->
console.log(this)
console.log(clickfunc)
$ourTd=$(this)
idx = $ourTd.index()
bin_id = $ourTd.attr('data-info')
if not bin_id
bin_id = $('thead tr th', table).eq(idx).attr('data-info')
if not clickfunc
clickfunc = 'binLightboxClick'
if bin_id
bin_id = parseInt(bin_id, 10)
console?.log?("Click bin_id #{bin_id}")
fill = CurrentDataUtil.getBinFill(self._fills, bin_id, false)
CurrentDataClick[clickfunc](bin_id, fill)
e.preventDefault()
)
_updateReadingMap: () ->
# _readings has structure
# { binid#: {'lcsection_sshortname': value, ...}, ..}
@_readings = {}
noOldData = true
hourAgo = HTMLHelper.datetimeDelta({date: new Date(), hours: -1})
if noOldData and (not IsadoreData.lastReadingsDatetime? or IsadoreData.lastReadingsDatetime < hourAgo)
console?.log?('Last Reading too long ago for fill view.')
else
for bin in IsadoreData.bins
@_readings[bin.id] = {}
if bin.readings?
for reading in bin.readings
if reading.value? and reading.datetime > hourAgo
readTypeName = IsadoreData.readTypesIdMap[reading.read_type_id].short_name.toLowerCase()
binSectionName = IsadoreData.binSectionsIdMap[reading.bin_section_id].name.toLowerCase()
key = binSectionName+'_'+readTypeName
if not @_readings[bin.id].hasOwnProperty(key)
@_readings[bin.id][key] = reading.value
else if _.isArray(@_readings[bin.id][key])
@_readings[bin.id][key].push(reading.value)
else
@_readings[bin.id][key] = [@_readings[bin.id][key], reading.value]
_makeFillViewCellHover: () ->
$('.fill_view_cell_table', @_$overlay).delegate('td', 'mouseover mouseleave', (e) ->
$ourTd=$(this)
dataInfo = $ourTd.attr('data-info')
if e.type == 'mouseover'
$('.fill_view_cell_table td[data-info="'+dataInfo+'"]', @_$overlay).addClass('hover')
else
$('.fill_view_cell_table td[data-info="'+dataInfo+'"]', @_$overlay).removeClass('hover')
)
_makeFillViewCellClick: () ->
$('.fill_view_cell_table td', @_$overlay).click((e) ->
$ourTd=$(this)
bin_id = $ourTd.attr('data-info')
if bin_id
bin_id = parseInt(bin_id, 10)
console?.log?("Click bin_id #{bin_id}")
lightboxHandlers.binLightbox.open(bin_id)
)
_makeFixedWidthCols: ($table) ->
$colgroup = $('<colgroup></colgroup')
s = $('tbody tr:first-child > td, tbody tr:first-child > th', $table).length
p=100.0/s
for i in [0...s]
$colgroup.append($('<col style="width: '+p+'%"/>'))
$table.prepend($colgroup)
refresh: (fills) ->
@_fills = fills
console?.log?('Fill view refresh')
@_$overlay.empty()
@_updateReadingMap()
fillViewCellTable = null
if @_viewConfig?.fill_view_list?
for row in @_viewConfig.fill_view_list
if row.view == 'fill_view'
fillViewCellTable = null
table = @_makeRowTable(row)
if row.options?.table_class?
#TODO: Extended class option
$(table).addClass(row.options.table_class)
@_makeFixedWidthCols(table)
@_$overlay.append(table)
@_makeHover(table, row.options?.hover)
@_makeColumnClass(table)
@_makeClick(table, row.options?.clickfunc)
else if row.view.indexOf('fill_view_cell') == 0
if not fillViewCellTable
fillViewCellTable = $('<table class="fill_view_cell_table"></table>')
if row.options?.table_class?
#TODO: Extended class option
$(fillViewCellTable).addClass(row.options.table_class)
@_$overlay.append(fillViewCellTable)
cellRow = @_makeFillViewCellRow(row)
if cellRow?
fillViewCellTable.append(cellRow)
else if row.view.indexOf('raw') == 0
rawTable = $(row.html)
@_$overlay.append(rawTable)
@_makeFillViewCellHover()
@_makeFillViewCellClick()
else
@_$overlay.html('Contact Exoteric Analytics if you would like a Fill View.')
fixHeights()
class window.DiagnosticsViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
<button class="reset_diag priv_config">Reset</button>
</h1>
""")
if not IsadoreData.selfAccount.hasPrivilege('Config User')
$('.priv_config', @_$selfDiv).hide()
$('.reset_diag', @_$selfDiv).click(() =>
$.ajax(
{
url: "../resources/data/diagnostics_sensor_data_latest_reset"
type: 'DELETE',
dataType: 'text'
}
)
)
@_$overlay = $('<div class="diagnostics_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
@_$spinner = $('<img class="center_margins spinner" src="imgs/ajax-loader.gif" alt="Loading Spinner"/>')
@_$overlay.append(@_$spinner)
@_$table = $('<table class="diagnostics_table display hover" rules="rows"></table>')
@_$overlay.append(@_$table)
@_selfVisible = false
@_$selfDiv.on('DOMAttrModified', () =>
if @_$selfDiv.is(':visible') and not @_$selfVisible
console.log('Diag div visible')
@_$selfVisible = true
@refresh()
else if not @_$selfDiv.is(':visible')
@_$selfVisible = false
);
_update: () ->
if not @_$overlay.closest(document.documentElement)
return
if not @_$overlay.is(':visible')
@_$table.hide()
@_$spinner.show()
return
@_fetchData(
() =>
return
)
_fetchData: (cb) ->
$.ajax(
{
url: "../resources/data/diagnostics_sensor_data_latest"
type: 'GET',
dataType: 'json'
success: (d) =>
@_refreshTable(d.results, cb)
error: () ->
cb()
}
)
_refreshTable: (d, cb) ->
console.log('_refreshTable')
tableColumns = [
{sTitle: 'dT'},
{sTitle: 'MID Name'},
{sTitle: 'Port'},
{sTitle: 'Address'},
{sTitle: 'Info'},
{sTitle: 'Bin'},
{sTitle: 'Bin Section'},
{sTitle: 'Read Type'},
{sTitle: 'Err'},
{sTitle: 'Value'},
{sTitle: 'Raw'}
]
tableData = []
now = new Date()
for row in d
tableData.push([
((now - newDate(row.datetime))/1000.0).toFixed(1)
row.mid_name
row.port
row.address
row.device_info
row.bin_name
row.bin_section_name
row.read_type_short_name
row.error_code
row.value
row.raw_data
])
#@_$spinner.hide()
@_$table.show()
dt = @_$table.dataTable({
bPaginate: false
bRetrieve: true
bFilter: true
# aaData: tableData
aoColumns: tableColumns
})
dt.fnClearTable()
dt.fnAddData(tableData)
fixHeights()
cb()
refresh: () ->
@_$spinner.hide()
#@_$table.hide()
@_update()
class window.SensorViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
</h1>
""")
@_$overlay = $('<div class="diagnostics_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
@_$spinner = $('<img class="center_margins spinner" src="imgs/ajax-loader.gif" alt="Loading Spinner"/>')
@_$overlay.append(@_$spinner)
@_selfVisible = false
@_$selfDiv.on('DOMAttrModified', () =>
if @_$selfDiv.is(':visible') and not @_$selfVisible
console.log('Diag div visible')
@_$selfVisible = true
@refresh()
else if not @_$selfDiv.is(':visible')
@_$selfVisible = false
);
_replace: (str, replaceMap) ->
if str
for key, value of replaceMap
str2 = null
while str != str2
if str2
str = str2
str2 = str.replace(key, value)
return str
_header: (header, $div) ->
$header = $('h2', $div)
if not $header[0]
cssclass=''
label=''
if header.label?
label = header.label
if header.class?
cssclass = header.class
$header = $("<h2 class=\"#{cssclass}\"><span>#{label}</span></h2>")
$div.append($header)
_findWindDirection: (bin_id, readings) ->
if not readings
return 0
if IsadoreData?.general?.configs?.sensor_view?.no_fill_no_arrows? and IsadoreData.general.configs.sensor_view.no_fill_no_arrows and not CurrentDataUtil.getBinFill(@_fills, bin_id, true).id?
return 0
top_temp = 0
bottom_temp = 0
for reading in readings
if IsadoreData.readTypesIdMap[reading.read_type_id].name == 'Temperature'
if IsadoreData.binSectionsIdMap[reading.bin_section_id].name == "Bottom"
bottom_temp = reading.value
else if IsadoreData.binSectionsIdMap[reading.bin_section_id].name == "Top"
top_temp = reading.value
if top_temp != 0 and bottom_temp != 0
return (bottom_temp - top_temp)
return 0
_tableRowClass: (binId) ->
for al in IsadoreData.selfAlarms
# TODO: Fix hard code
if al.alarm_type_id == 14
if al.greater_than_p
alarmReadings = _.filter(IsadoreData.readings, (o) ->
return o.bin_id == binId && (o.bin_section_id == 13 || o.bin_section_id == 14) && o.read_type_id == 10 && o.value > al.value
);
if alarmReadings.length > 0
return 'red'
else
alarmReadings = _.filter(IsadoreData.readings, (o) ->
return o.bin_id == binId && (o.bin_section_id == 13 || o.bin_section_id == 14) && o.read_type_id == 10 && o.value <= al.value
);
if alarmReadings.length > 0
return 'red'
return null
_updateTable: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
divclass = ''
if block.alignment == 'left'
$specificDiv = $('<div class="specific"></div>')
@_$selfDiv.append($specificDiv)
$spleft = $('<div class="spleft"></div>')
$specificDiv.append($spleft)
$div = $('<div name="block'+i+'" style="margin-right: 3.5%;"></div>')
$spleft.append($div)
else if block.alignment == 'right'
$specificDiv = $('div[name="block'+(i-1)+'"]', @_$selfDiv).parent().parent()
divclass = 'spright'
$div = $('<div name="block'+i+'" class="'+divclass+'"></div>')
$specificDiv.append($div)
else
@_$selfDiv.append($('<div class="clears"></div>'))
$div = $('<div name="block'+i+'" class="'+divclass+'"></div>')
@_$selfDiv.append($div)
if block.header?
@_header(block.header, $div)
$table = $('table', $div)
if not $table[0]
$table = $('<table class="display hover" rules="rows"></table>')
$div.append($table)
#First lets make columns
aoColumns = []
for column in block.columns
stringReplacements = {
$bin_section_name$: ''
$read_type_name$: ''
$read_type_short_name$: ''
$read_type_units$: ''
}
if block.row_type == 'bin' and column.bin_section_id?
bin_section = IsadoreData.binSectionsIdMap[column.bin_section_id]
stringReplacements['$bin_section_name$'] = bin_section.name
if column.read_type_id?
read_type = IsadoreData.readTypesIdMap[column.read_type_id]
stringReplacements.$read_type_name$ = read_type.name
stringReplacements.$read_type_short_name$ = read_type.short_name
stringReplacements.$read_type_units$ = read_type.units
sTitle = @_replace(column.column_label, stringReplacements)
aoColumns.push({sTitle: sTitle})
aoColumns.push({sTitle: 'data-bin_id', bVisible: false})
#Now data
tableData = []
if block.row_type == 'bin'
for bin_id in block.bin_ids
bin = _.find(IsadoreData.bins, {id: bin_id})
if not bin
console.log('Could not find bin id: '+bin_id)
row = @_updateTable2(block, bin, null)
row.push(bin_id)
tableData.push(row)
else # 'section' row_type
bin =_.find(IsadoreData.bins, {id: block.bin_id})
for bin_section_id in block.bin_section_ids
bin_section = IsadoreData.binSectionsIdMap[bin_section_id]
row = @_updateTable2(block, bin, bin_section)
row.push(bin.id)
tableData.push(row)
dt = $table.dataTable({
bPaginate: false
bRetrieve: true
bFilter: false
aoColumns: aoColumns
fnRowCallback: (nRow, aData, ididx, ididxf) =>
nRow.setAttribute('data-bin_id', aData[aData.length-1])
rowClass = @_tableRowClass(aData[aData.length-1])
if rowClass
$(nRow).addClass(rowClass)
$('td', $(nRow)).addClass(rowClass)
return nRow
})
dt.fnClearTable()
dt.fnAddData(tableData)
elems = $('tbody tr', $table)
elems.unbind('click', lightboxHandlers.binLightbox.binClick)
elems.click(lightboxHandlers.binLightbox.binClick)
fixHeights()
_updateTable2: (block, bin, bin_section) ->
rowData = []
hourAgo = HTMLHelper.datetimeDelta({date: new Date(), hours: -1})
for column in block.columns
stringReplacements = {
$bin_number$: ''
$bin_name$: ''
$bin_section_name$: ''
$valueF1$: 'NA'
$valueF2$: 'NA'
}
stringReplacements.$bin_name$ = bin.name
binNameSegments = bin.name.split(' ')
bin_section_id = null
read_type_id = null
if binNameSegments.length > 1
stringReplacements.$bin_number$ = binNameSegments[1]
if block.row_type == 'bin' and column.bin_section_id?
bin_section = IsadoreData.binSectionsIdMap[column.bin_section_id]
bin_section_id = bin_section.id
stringReplacements['$bin_section_name$'] = bin_section.name
else if block.row_type == 'section'
bin_section_id = bin_section.id
stringReplacements['$bin_section_name$'] = bin_section.name
if column.read_type_id?
read_type = IsadoreData.readTypesIdMap[column.read_type_id]
read_type_id = read_type.id
reading = _.find(IsadoreData.lastReadings, {bin_id: bin.id, bin_section_id: bin_section_id, read_type_id: read_type_id})
if reading && reading.value && reading.datetime > hourAgo
stringReplacements.$valueF1$ = reading.value.toFixed(1)
stringReplacements.$valueF2$ = reading.value.toFixed(2)
rowData.push(@_replace(column.value, stringReplacements))
return rowData
_updateDiagram: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
$div = $('<div name="block'+i+'"></div>')
@_$selfDiv.append($div)
if block.header?
@_header(block.header, $div)
# reference: jQuery cookbook 5.1
html = []
html[html.length] = '<table class="layout_table" rules="rows" style="table-layout: fixed">'
html[html.length] = '<tbody>'
miny = 999999999
if not IsadoreData.general.configs.hasOwnProperty('bin_layout_empties') or IsadoreData.general.configs.bin_layout_empties
maxy = 0
maxx = 0
for bin in IsadoreData.bins
if bin.y < 0 or not (block.yindexes == 'all' or bin.y in block.yindexes)
continue
if bin.y < miny
miny = bin.y
if bin.y > maxy
maxy = bin.y
if bin.x > maxx
maxx = bin.x
td=[]
for x in [0..maxx]
td[td.length] = '<td class="empty"></td>'
td = td.join('')
# Lets make grid first
for y in [miny..maxy]
if y % 2 == 0
html[html.length] = '<tr class="layout_top">'+td+'</tr>'
html[html.length] = '<tr class="layout_top_labels">'+td+'</tr>'
else if y % 2 == 1
html[html.length] = '<tr class="layout_bottom_labels">'+td+'</tr>'
html[html.length] = '<tr class="layout_bottom">'+td+'</tr>'
else
sortedBins = _.sortBy(IsadoreData.bins, ['y', 'x'])
y = -1
tds = []
miny = 0
if block.yindexes != 'all'
miny = _.min(block.yindexes)
for bin in sortedBins
if (block.yindexes == 'all' or bin.y in block.yindexes) and bin.y >= 0 and y != bin.y
tds.push([])
y = bin.y
if bin.y >= 0 and bin.x >= 0
tds[tds.length-1].push('<td class="empty"></td>')
for y in [0...tds.length]
td = tds[y].join('')
if y % 2 == 0
html.push('<tr class="layout_top">'+td+'</tr>')
html.push('<tr class="layout_top_labels">'+td+'</tr>')
else if y % 2 == 1
html.push('<tr class="layout_bottom_labels">'+td+'</tr>')
html.push('<tr class="layout_bottom">'+td+'</tr>')
html[html.length] = '</tbody>'
html[html.length] = '</table>'
table = $(html.join(''))
# Then fill in the grid.
for bin in IsadoreData.bins
if (block.yindexes == 'all' or bin.y in block.yindexes) and bin.y >= 0
name = bin.name
if name == 'empty'
continue
imgStr=''
# TODO: Check for red status. If so add class="red" in td
# top/bottom
if name.indexOf('Fan') >= 0
imgStr = '<img src="imgs/icon_fan_gray.png" alt="Fan"/>'
else if name.indexOf('Burner') >= 0
imgStr = '<img src="imgs/icon_burner_gray.png" alt="Fan"/>'
else # Normal bin
# Check air flow direction
if bin.readings
windDir = @_findWindDirection(bin.id, bin.readings)
if windDir > 0
imgStr = '<img src="imgs/icon_arrowUP_gray.png" alt="Bin Up" />'
else if windDir < 0
imgStr = '<img src="imgs/icon_arrowDOWN_gray.png" alt="Bin Down" />'
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).removeClass('empty')
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('data-bin_id', bin.id)
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('data-bin_id', bin.id)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).removeClass('empty')
if bin.y % 2 == 0
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).html(imgStr)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).html(name)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan);
else
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).html(name)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).html(imgStr)
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan);
$div.empty()
$div.append($('<div name="wind_instructions">Arrows indicate air direction</div>'))
$div2 = $('<div class="layout"></div>')
$div.append($div2)
$div2.append(table)
elems = $('.layout_table td[data-bin_id]', $div)
elems.unbind('click', lightboxHandlers.binLightbox.binClick)
elems.click(lightboxHandlers.binLightbox.binClick)
tableSize = $('.layout_table', $div).width()
#$('.layout_table td').width(tableSize/(maxx+1))
_updateConfig: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
$div = $('<div name="block'+i+'"></div>')
$div.append($("""
<h1>
<span>Sensor View Config</span>
</h1>
<input data-key="no_fill_no_arrow" type="checkbox"/> <label for="sensor_view_config_no_fill_no_arrows">Only display arrows when open fill.</label>
"""))
@_$selfDiv.append($div)
no_fill_no_arrows_checkbox = $('input', $div);
if IsadoreData.general?.configs?.sensor_view?.no_fill_no_arrows? and IsadoreData.general.configs.sensor_view.no_fill_no_arrows
no_fill_no_arrows_checkbox.prop('checked', true)
else
no_fill_no_arrows_checkbox.prop('checked', false)
no_fill_no_arrows_checkbox.change(() =>
if(no_fill_no_arrows_checkbox.attr('checked'))
val = true
else
val = false
IsadoreData.general?.configs?.sensor_view?.no_fill_no_arrows = val
if not IsadoreData.selfAccount.configs?
IsadoreData.selfAccount.configs = {}
if not IsadoreData.selfAccount.configs.sensor_view?
IsadoreData.selfAccount.configs.sensor_view = {}
IsadoreData.selfAccount.configs.sensor_view.no_fill_no_arrows = val
newConfigs = _.cloneDeep(IsadoreData.selfAccount.configs)
$.ajax({
url: "../resources/accounts/#{IsadoreData.selfAccount.id}"
type: 'PUT'
dataType: 'text'
data: {configs: JSON.stringify(newConfigs)}
})
@refresh()
)
_update: () ->
for i in [0...@_viewConfig.block.length]
block = @_viewConfig.block[i]
if block.type == 'table'
@_updateTable(i, block)
else if block.type == 'diagram'
@_updateDiagram(i, block)
else if block.type == 'config'
@_updateConfig(i, block)
@_$spinner.hide()
refresh: () ->
@_$spinner.show()
#@_$table.hide()
#@_update()
DataManager.getFills({
year: new Date().getFullYear(),
callback: (d)=>
@_fills = d.fills
@_update()
})
class window.CurrentDataHandler
constructor: () ->
$('#content_current_data').tabs({activate: () -> fixHeights()})
_refresh: () ->
if @fillSub?
DataManager.dataUnSub(@fillSub)
@fillSub = null
@fillSub = DataManager.dataSub({
key: "fill",
type: ['edit', 'add', 'delete'],
year: parseInt(new Date().getFullYear(), 10)
callback: () =>
@refresh()
})
$('.last_update_datetime').html(IsadoreData.lastReadingsTime)
for otherView in @_otherViews
otherView.refresh(@_fills)
fixHeights()
_populateOtherTabs: () ->
if @_otherViews?
return
#Make other tabs and views
if IsadoreData.general.configs?.other_views?
@_otherViews = []
for view in IsadoreData.general.configs.other_views
viewTitle = view.title
viewType = view.type
viewUUID = uuid.v4()
if viewType == "fill_view"
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new CurrentDataFillViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
else if viewType == "diagnostics"
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new DiagnosticsViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
else if viewType == 'sensor_view'
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new SensorViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
$('#content_current_data').tabs('refresh')
$('#content_current_data').tabs('select', 0)
else
$('#content_current_data').tabs('refresh')
# Update the current data page if visible.
refresh: () ->
if not $('#content_current_data').is(':visible')
return
@_populateOtherTabs()
checkClientVersion()
console?.log?('Current Data refresh')
$('#menu_current_data').removeClass('unselected')
$('#menu_current_data').addClass('selected')
DataManager.getFills({
year: new Date().getFullYear(),
callback: (d)=>
@_fills = d.fills
@_refresh()
})
| 36961 | # Copyright 2010-2019 <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Other View format
#"other_views": [ #Array of view objects
# {
# "title": "Fill View", #display title of view
# "type": "fill_view|diagnostics|sensor_view", #Type of view
# #The view object for fill_view
# "view": {
# "fill_view_list": [ # Array list of fill_views, will do it in order
# {
# "view": "fill_view", #name of the view there are fill_view and fill_view_cell# as possibilities
# # fill_view goes through a list of bins and fill_view_cell# is more standalone.
# # you can have multiple fill_view with different bins it goes through.
# # You might want to do fill_view, some fill_view_cells, and fill_view again.
# "bin_ids": [ # Array of bin ID's to go through in the "fill_view" view
# 12, 13, 14, ...
# ],
# "options": { # Fill view options
# "table_class": "original_fill_view" #What class this fill_view table should have original_fill_view or pleasent_fill_view for example
# "hide_labels": true, #default false, this hides the left side labels of a fill_view
# "column_class": [ #Allows settings column css class based off result of a function See "FillViewStyler"
# {
# "func": "fillStatusStyle", #Function to use to determine column css class
# "keys": [ #data keys that go with the function.
# "fill.filled_datetime", "fill.emptied_datetime", "fill.air_begin_datetime", ...
# ]
# }
# ],
# "hover": { #Hoover options
# "row_disable": true, #Disable row hovering, default false
# "thead_enable": true, #Enable hovering head when novered over column default false
# }
# "clickfunc": "fillDialog|binLightBoxClick,.." #Which function in CurrentDataClick to use when clicking on a the table, default 'binLightboxClick'
# }
# },
# {
# "view": "fill_view_cell1", #Id for a cell view to go through
# "options": {
# "table_class": "original_fill_view" #What class this cell view table will have
# }
# }
# {
# "view": "raw1", #Just display some raw html, no key below that needs to match.
# "html": "<table class=\"fill_view_legend\"><tr><td class=\"bolded\" colspan=\"2\">Legend</td></tr><tr><td>Up Air</td><td class=\"fv_upair\">Value</td></tr><tr><td>Down Air</td><td class=\"fv_downair\">Value</td></tr><tr><td>Burners</td><td>PV (SP)</td></tr><tr><td>Full/Drying</td><td class=\"fv_full\"></td></tr><tr><td>Empty</td><td class=\"fv_empty\"></td></tr><tr><td>Shelling</td><td class=\"fv_shelling\"></td></tr><tr><td>Filling</td><td class=\"fv_filling\"></td></tr></table>" #html as a string
# }
# ... other fill_view_cells, or fill_views, or raw lists...
# ],
# "fill_view": [ #What to show in the fill_view
# {
# "label": "Fill #", #Lable to display on the left of fill_view table
# "keys": [ #Array of data keys, could be fill.fill_column or readings.binsection_sensorshortname
# "fill.fill_number"
# "readings.top_temp",
# "readings.bottom_temp"
# ],
# "format": null, #Which format function to send data to. See object "FillViewFormater"
# "class": [ #Which classes the contents of a colum in a fill_view should have
# {
# "func": "upDownAirStyle", #Function to call in "FillViewStyler"
# "keys": [ #data keys that go to function
# "readings.top_temp", "readings.bottom_temp", ...
# ]
# },
# ... More class functions or string for static class...
# ]
# },
# ... more stuff to show in fill_view
# ],
# "fill_view_cell1": [ #What to display in the cell table
# {
# "label": "Burner 1", #Cell name
# "class": "bolded" #Class content should have in cell. Can also be a array with object.func object.keys like in fill_view
# },
# {
# "label": "Burner SP",
# "bin_id": 100, #Which bins can be array of multiple binIds, data keys then being readings0, readings1, ..., instead of just readings
# "colspan": 3, # How many columns the cell should take up, default is 1
# "keys": [ #Data keys similar to fill_view keys
# "readings.burner.sp"
# ],
# "format": "fixed1T" #format function see "FillViewFormater"
# "display": "adjacent" #if "adjacent, there should be no linebreak between label and value
# "readings_func": "upBinsCount" # should get value using a entire readings function, instead of bin/fill based, see "FillViewFunc"
# },
# ... More cells to display ...
# ],
# ... More fill_view_cell# ...
# }
# # diagnostics view
# "view": {
# "interval": 1500 #refresh_in_milliseconds
# }
# # sensor_view
# "view": {
# block: [ #Can have any number of types in any order
# #Type table
# {
# "type": "table",
# "row_type": "bin|section",
# "alignment": "full|left|right",
# "columns": [
# {
# "bin_section_id": int, # If 'bin' row_type, or null if just want a label column
# "read_type_id": int, # Can be null if just want a label column
# "column_label": string, #keys: $bin_section_name$, $read_type_short_name$, $read_type_units$, $read_type_name$
# "value": string # keys: $bin_number$, $bin_name$, $bin_section_name$, $valueF1$, $valueF2$
# }, ...
# ],
# "bin_ids": [int, int, ...], # if 'bin' row_type
#
# "bin_id": int, # if 'section' row_type
# "bin_section_ids": [int, int, ...], # if 'section' row_type
#
# "header": { # or can be null
# "label": string,
# "class": string
# }
# },
# #Type diagram
# {
# "type": "diagram",
# "yindexes": [int, int, ...], # or "all"
# "header": { # or can be null
# "label": string,
# "class": string
# }
# },
# {
# "type": "config"
# }
# ...
# ]
# }
# }
FillViewStyler = {
upDownAirStyle: (topTemp, bottomTemp) ->
if topTemp > bottomTemp
return "fv_downair"
else if(topTemp < bottomTemp)
return "fv_upair"
return null
fillStatusStyle: (type, filled, emptied, air_begin, air_end, roll) ->
if type == 2
return "fv_bypass"
else
if air_end and !emptied
return "fv_shelling"
if air_begin and !air_end
return "fv_drying"
if filled and !air_begin
return "fv_filling"
if not filled
return "fv_empty"
return "fv_unknown"
}
FillViewFormater = {
lastSample: (during_mc) ->
last = null
for mcd in during_mc
mc = mcd[0]
d = newDate(mcd[1])
if not last or d > last[1]
last = [mc, d]
if last
return last[0].toFixed(1)
lastSampleDate: (during_mc) ->
last = null
for mcd in during_mc
mc = mcd[0]
d = newDate(mcd[1])
if not last or d > last[1]
last = [mc, d]
if last
return HTMLHelper.dateToReadableO3(last[1])
_mean: (array) ->
if not array
return null
if not _.isArray(array)
return array
if array.length == 0
return null
s = 0
for a in array
s += a
s=s/array.length
return s
mean: (array) ->
if array
if not _.isArray(array)
return array.toFixed(2)
t = @_mean(array)
if t
return t.toFixed(2)
return null
meanArg: (array...) ->
return @mean(array)
timeUpCalc: (begin, roll) ->
# TODO: Air deducts
# TODO: Support multiple rolls
if begin
begin = newDate(begin)
if roll and roll.length > 0
if _.isArray(roll)
t = newDate(roll[0])
else
t = newDate(roll)
return FillViewFormater.timeDiff(t, begin)
else
return FillViewFormater.timeDiffNow(begin)
return null
timeDiffNow: (time, orend) ->
# TODO: Air deducts
# TODO: Support multiple rolls
if orend and orend != ''
orend = newDate(orend)
else
orend = null
t = null
now = new Date()
if time
if _.isArray(time)
t = newDate(time[0])
else
t = newDate(time)
if orend
t = FillViewFormater.timeDiff(orend, t)
else
t = FillViewFormater.timeDiff(now, t)
return t
timeDiff: (gr, ls) ->
if not gr or not ls
return null
else
return ((gr.getTime() - ls.getTime())/(1000.0*60*60)).toFixed(2)
airDirection: (topt, bott) ->
t = @_mean(topt)
b = @_mean(bott)
if t and b
r=(b-t)
if r > 0
return 'Up'
else if r < 0
return 'Down'
return null
fixed1T: (t, u) ->
t2 = @_mean(t)
if t2
return t2.toFixed(1)
return null
fixed1P: (rh) ->
t2 = @_mean(rh)
if t2
return t2.toFixed(1)
return null
numberSplit: (str) ->
a = str.split(' ')
for v in a
i = parseInt(v, 10)
if(!isNaN(i))
return i
return NaN
twoPerns: (v1, v2) ->
return v1.toFixed(1)+' ('+v2.toFixed(1)+')'
}
FillViewFunc = {
_binCount: (up, readings, fills, nameFilter) ->
upCount = 0
downCount = 0
for binId, bin of readings
binId = parseInt(binId, 10)
if nameFilter
bn = _.findWhere(IsadoreData.bins, {id: binId})
if not bn.name.match(nameFilter)
continue
if bin.top_temp? and bin.bottom_temp?
fill = CurrentDataUtil.getBinFill(fills, binId, false)
if not fill.id?
continue
fstyle = FillViewStyler.fillStatusStyle(fill.fill_type_id, fill.filled_datetime, fill.emptied_datetime, fill.air_begin_datetime, fill.air_end_datetime, fill.roll_datetime)
if fstyle != "fv_drying"
continue
if up and bin.top_temp < bin.bottom_temp
upCount++
if !up and bin.top_temp > bin.bottom_temp
downCount++
if up
return upCount + " Up Bins"
else
return downCount + " Down Bins"
# Calculates and outputs string of number of bins in up air
upBinsCount: (readings, fills) ->
return this._binCount(true, readings, fills)
# Calculates and ouputs string number of bins in down air
downBinsCount: (readings, fills) ->
return this._binCount(false, readings, fills)
#TODO: Be able to send custom arguments to readings_func
# Calculates and outputs string of number of bins in up air
upBinsCountFilter1: (readings, fills) ->
return this._binCount(true, readings, fills, new RegExp('^Bin 1'))
# Calculates and ouputs string number of bins in down air
downBinsCountFilter1: (readings, fills) ->
return this._binCount(false, readings, fills, new RegExp('^Bin 1'))
# Calculates and outputs string of number of bins in up air
upBinsCountFilter2: (readings, fills) ->
return this._binCount(true, readings, fills, new RegExp('^Bin 2'))
# Calculates and ouputs string number of bins in down air
downBinsCountFilter2: (readings, fills) ->
return this._binCount(false, readings, fills, new RegExp('^Bin 2'))
}
window.CurrentDataUtil = {
getBinFill: (fills, bin_id, air_end) ->
now = new Date()
for fill in fills by -1
if fill and fill.bin_id == bin_id and not fill.emptied_datetime? and (not air_end || not fill.air_end_datetime?)
if fill.filled_datetime?
fill.filled_datetime = newDate(fill.filled_datetime)
if fill.air_begin_datetime?
fill.air_begin_datetime = newDate(fill.air_begin_datetime)
#If filled > now and (not emptied) or air_begin > now and not air_end
if ((fill.filled_datetime? and fill.filled_datetime < now) or (fill.air_begin_datetime? and fill.air_begin_datetime < now))
return fill
return {}
}
CurrentDataClick = {
_getFillYear: (yfill) ->
if yfill.filled_datetime?
year = newDate(yfill.filled_datetime).getFullYear()
else
year = newDate(yfill.air_begin_datetime).getFullYear()
return year
_openNewFill: (binId) ->
lightboxHandlers.editFillLightbox.open({
year: new Date().getFullYear()
bin_id: binId
})
_openEditFill: (fill) ->
self=this
lightboxHandlers.editFillLightbox.open({year: self._getFillYear(fill), fill_id: fill.id})
binLightboxClick: (binId, fill) ->
lightboxHandlers.binLightbox.open(binId)
fillDialog: (binId, fill) ->
#TODO: Check privs do binLightboxClick if not enough privs
bin = IsadoreData.getBin(binId)
hasPriv = true
if not hasPriv or bin.name.indexOf('Bin') != 0
this.binLightboxClick(binId, fill)
else
statusStyle = FillViewStyler.fillStatusStyle(fill.fill_type_id, fill.filled_datetime, fill.emptied_datetime, fill.air_begin_datetime, fill.air_end_datetime, fill.roll_datetime)
if statusStyle == 'fv_empty'
this._openNewFill(binId)
else
this._openEditFill(fill)
}
class window.CurrentDataFillViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_fills = []
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
</h1>
""")
@_$overlay = $('<div class="fill_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
_getBinReadings: (bin_id) ->
if @_readings?.hasOwnProperty(bin_id)
return @_readings[bin_id]
return {}
_getCellData: (bin_id) ->
data = {}
if _.isArray(bin_id)
for i in [0...bin_id.length]
data['fill'+i] = CurrentDataUtil.getBinFill(@_fills, bin_id[i], false)
data['readings'+i] = @_getBinReadings(bin_id)
data['bin'+i] = IsadoreData.getBin(bin_id)
else
data = {fill: CurrentDataUtil.getBinFill(@_fills, bin_id, false), readings: @_getBinReadings(bin_id), bin: IsadoreData.getBin(bin_id)}
_getCellValue: (data, onlyIfFill, keys, format) ->
if onlyIfFill and not data.fill?.id?
return null
val = null
if format
try
args = []
for key in keys
obj = data
for k in key.split('.')
obj = obj[k]
args.push(obj)
val = FillViewFormater[format].apply(FillViewFormater, args)
catch e
#console?.error?(e)
val = null
else if keys.length > 0
try
obj = data
for k in keys[0].split('.')
obj = obj[k]
val= obj
if val and k.indexOf('_datetime') == k.length - 9
val = HTMLHelper.dateToReadableO3(newDate(val))
catch e
#console?.error?(e)
val = null
return val
_makeFillViewCellRow: (row) ->
if not @_viewConfig.hasOwnProperty(row.view)
return null
columns = @_viewConfig[row.view]
tr = $('<tr></tr>')
for column in columns
td = $('<td></td>')
cell_value = null
content = null
if column.label?
content = column.label
if column.class?
td.attr('class', column.class)
if column.colspan?
td.attr('colspan', column.colspan)
if column.keys? and column.bin_id?
cell_value = @_getCellValue(@_getCellData(column.bin_id), false, column.keys, column.format)
if cell_value
if content and (!column.display? or column.display != 'adjacent')
content += "<br/>"+cell_value
else
content = cell_value
if column.readings_func?
try
cell_value2 = FillViewFunc[column.readings_func].apply(FillViewFunc, [@_readings, @_fills])
if content and (!column.display? or column.display != 'adjacent')
content += "<br/>"+cell_value2
else
content = cell_value2
catch e
if console?.error?
console.error(e)
if content
td.html(content)
if column.bin_id?
td.attr('data-info', ''+column.bin_id)
tr.append(td)
return tr
_getDynamicClass: (classInfo, bin_id) ->
if _.isString(classInfo)
return classInfo
cssClasses = []
if !_.isArray(classInfo) and _.isObject(classInfo)
cl = @_getDynamicClassFromObj(classInfo, bin_id)
if cl
cssClasses.push(cl)
else if _.isArray(classInfo)
for classObj in classInfo
cl = @_getDynamicClassFromObj(classObj, bin_id)
if cl
cssClasses.push(cl)
return cssClasses.join(' ')
_getDynamicClassFromObj: (classObj, bin_id) ->
if classObj.plain? and _.isString(classObj.plain)
return classObj.plain
if classObj.func? and _.isString(classObj.func)
data = null
if classObj.bin_id?
data = @_getCellData(classObj.bin_id)
else if bin_id
data = @_getCellData(bin_id)
try
args = []
for key in classObj.keys
obj = data
for k in key.split('.')
obj = obj[k]
args.push(obj)
val = FillViewStyler[classObj.func].apply(FillViewStyler, args)
catch e
console?.error?(e)
val = null
return val
return null
_makeRowTable: (row) ->
table = $('<table class="fill_view_table"></table>')
fv = null
arow = row
if @_viewConfig.fill_view?
fv = @_viewConfig.fill_view
table_data = []
if row.view == 'fill_view'
# First row is bin_names
table_row = [{'data-info': -1, content: "Bin"}]
for bin_id in row.bin_ids
if bin_id == "empty"
table_row.push({'data-info': -1, content: ' ', 'data-columnclass': 'fv_nodata'})
else
name = IsadoreData.getBin(bin_id).name.split(" ")
if name.length > 1
name = name[1]
else
name = name[0]
table_column = {'data-info': bin_id, content: name}
if row.options?.column_class?
cl = @_getDynamicClass(row.options.column_class, bin_id)
if cl
table_column['data-columnclass'] = cl
table_row.push(table_column)
table_data.push(table_row)
for fv_row in fv
table_row=[]
table_row.push(fv_row.label)
for bin_id in row.bin_ids
if bin_id == "empty"
table_row.push(' ')
else
cell_value = @_getCellValue(@_getCellData(bin_id), true, fv_row.keys, fv_row.format)
cell_class = null
if fv_row.class?
cell_class = @_getDynamicClass(fv_row.class, bin_id)
table_row.push({'data-info': bin_id, content: cell_value, class: cell_class})
table_data.push(table_row)
#Make HTML from table_data
firstRow = true
thead = $('<thead></thead>')
table.append(thead)
tbody = $('<tbody></tbody>')
table.append(tbody)
for row in table_data
if firstRow
tr = $('<tr></tr>')
thead.append(tr)
else
tr = $('<tr></tr>')
tbody.append(tr)
firstColumn = true
for column in row
if firstColumn or firstRow
td = $('<th></th>')
else
td = $('<td></td>')
if _.isObject(column)
if column.hasOwnProperty('data-columnclass')
td.attr('data-columnclass', column['data-columnclass'])
if column.hasOwnProperty('data-info')
td.attr('data-info', column['data-info'])
if column.content?
td.html(column.content)
if column.class?
td.addClass(column.class)
else
td.html(column)
if not firstColumn or !(arow.options?.hide_labels)
tr.append(td)
firstColumn = false
firstRow = false
return table
_makeColumnClass: ($table) ->
$tr = $('tr:first-child', $table)
$('th, td', $tr).each( (index, element) ->
rc = $(element).attr('data-columnclass')
$(element).addClass(rc)
if rc
$('tbody tr', $table).each( (index2, element2) ->
$('th,td', element2).eq(index).addClass(rc)
)
)
_makeHover: (table, hoverOptions) ->
table.delegate('tbody th,tbody td', 'mouseover mouseleave', (e) ->
$ourTd=$(this)
if e.type == 'mouseover'
if not hoverOptions?.row_disable
$('th,td', $ourTd.parent()).addClass('hover')
if $ourTd.index() != 0
$('tbody tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).addClass('hover')
)
if hoverOptions?.thead_enable
$('thead tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).addClass('hover')
)
$ourTd.removeClass('hover').addClass('super_hover')
else
$('th,td', $ourTd.parent()).removeClass('hover')
$ourTd.removeClass('super_hover')
$('tbody tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).removeClass('hover')
)
$('thead tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).removeClass('hover')
)
)
_makeClick: (table, clickfunc) ->
self = this
$('tbody td, thead th', table).click((e) ->
console.log(this)
console.log(clickfunc)
$ourTd=$(this)
idx = $ourTd.index()
bin_id = $ourTd.attr('data-info')
if not bin_id
bin_id = $('thead tr th', table).eq(idx).attr('data-info')
if not clickfunc
clickfunc = 'binLightboxClick'
if bin_id
bin_id = parseInt(bin_id, 10)
console?.log?("Click bin_id #{bin_id}")
fill = CurrentDataUtil.getBinFill(self._fills, bin_id, false)
CurrentDataClick[clickfunc](bin_id, fill)
e.preventDefault()
)
_updateReadingMap: () ->
# _readings has structure
# { binid#: {'lcsection_sshortname': value, ...}, ..}
@_readings = {}
noOldData = true
hourAgo = HTMLHelper.datetimeDelta({date: new Date(), hours: -1})
if noOldData and (not IsadoreData.lastReadingsDatetime? or IsadoreData.lastReadingsDatetime < hourAgo)
console?.log?('Last Reading too long ago for fill view.')
else
for bin in IsadoreData.bins
@_readings[bin.id] = {}
if bin.readings?
for reading in bin.readings
if reading.value? and reading.datetime > hourAgo
readTypeName = IsadoreData.readTypesIdMap[reading.read_type_id].short_name.toLowerCase()
binSectionName = IsadoreData.binSectionsIdMap[reading.bin_section_id].name.toLowerCase()
key = <KEY> <KEY>
if not @_readings[bin.id].hasOwnProperty(key)
@_readings[bin.id][key] = reading.value
else if _.isArray(@_readings[bin.id][key])
@_readings[bin.id][key].push(reading.value)
else
@_readings[bin.id][key] = [@_readings[bin.id][key], reading.value]
_makeFillViewCellHover: () ->
$('.fill_view_cell_table', @_$overlay).delegate('td', 'mouseover mouseleave', (e) ->
$ourTd=$(this)
dataInfo = $ourTd.attr('data-info')
if e.type == 'mouseover'
$('.fill_view_cell_table td[data-info="'+dataInfo+'"]', @_$overlay).addClass('hover')
else
$('.fill_view_cell_table td[data-info="'+dataInfo+'"]', @_$overlay).removeClass('hover')
)
_makeFillViewCellClick: () ->
$('.fill_view_cell_table td', @_$overlay).click((e) ->
$ourTd=$(this)
bin_id = $ourTd.attr('data-info')
if bin_id
bin_id = parseInt(bin_id, 10)
console?.log?("Click bin_id #{bin_id}")
lightboxHandlers.binLightbox.open(bin_id)
)
_makeFixedWidthCols: ($table) ->
$colgroup = $('<colgroup></colgroup')
s = $('tbody tr:first-child > td, tbody tr:first-child > th', $table).length
p=100.0/s
for i in [0...s]
$colgroup.append($('<col style="width: '+p+'%"/>'))
$table.prepend($colgroup)
refresh: (fills) ->
@_fills = fills
console?.log?('Fill view refresh')
@_$overlay.empty()
@_updateReadingMap()
fillViewCellTable = null
if @_viewConfig?.fill_view_list?
for row in @_viewConfig.fill_view_list
if row.view == 'fill_view'
fillViewCellTable = null
table = @_makeRowTable(row)
if row.options?.table_class?
#TODO: Extended class option
$(table).addClass(row.options.table_class)
@_makeFixedWidthCols(table)
@_$overlay.append(table)
@_makeHover(table, row.options?.hover)
@_makeColumnClass(table)
@_makeClick(table, row.options?.clickfunc)
else if row.view.indexOf('fill_view_cell') == 0
if not fillViewCellTable
fillViewCellTable = $('<table class="fill_view_cell_table"></table>')
if row.options?.table_class?
#TODO: Extended class option
$(fillViewCellTable).addClass(row.options.table_class)
@_$overlay.append(fillViewCellTable)
cellRow = @_makeFillViewCellRow(row)
if cellRow?
fillViewCellTable.append(cellRow)
else if row.view.indexOf('raw') == 0
rawTable = $(row.html)
@_$overlay.append(rawTable)
@_makeFillViewCellHover()
@_makeFillViewCellClick()
else
@_$overlay.html('Contact Exoteric Analytics if you would like a Fill View.')
fixHeights()
class window.DiagnosticsViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
<button class="reset_diag priv_config">Reset</button>
</h1>
""")
if not IsadoreData.selfAccount.hasPrivilege('Config User')
$('.priv_config', @_$selfDiv).hide()
$('.reset_diag', @_$selfDiv).click(() =>
$.ajax(
{
url: "../resources/data/diagnostics_sensor_data_latest_reset"
type: 'DELETE',
dataType: 'text'
}
)
)
@_$overlay = $('<div class="diagnostics_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
@_$spinner = $('<img class="center_margins spinner" src="imgs/ajax-loader.gif" alt="Loading Spinner"/>')
@_$overlay.append(@_$spinner)
@_$table = $('<table class="diagnostics_table display hover" rules="rows"></table>')
@_$overlay.append(@_$table)
@_selfVisible = false
@_$selfDiv.on('DOMAttrModified', () =>
if @_$selfDiv.is(':visible') and not @_$selfVisible
console.log('Diag div visible')
@_$selfVisible = true
@refresh()
else if not @_$selfDiv.is(':visible')
@_$selfVisible = false
);
_update: () ->
if not @_$overlay.closest(document.documentElement)
return
if not @_$overlay.is(':visible')
@_$table.hide()
@_$spinner.show()
return
@_fetchData(
() =>
return
)
_fetchData: (cb) ->
$.ajax(
{
url: "../resources/data/diagnostics_sensor_data_latest"
type: 'GET',
dataType: 'json'
success: (d) =>
@_refreshTable(d.results, cb)
error: () ->
cb()
}
)
_refreshTable: (d, cb) ->
console.log('_refreshTable')
tableColumns = [
{sTitle: 'dT'},
{sTitle: 'MID Name'},
{sTitle: 'Port'},
{sTitle: 'Address'},
{sTitle: 'Info'},
{sTitle: 'Bin'},
{sTitle: 'Bin Section'},
{sTitle: 'Read Type'},
{sTitle: 'Err'},
{sTitle: 'Value'},
{sTitle: 'Raw'}
]
tableData = []
now = new Date()
for row in d
tableData.push([
((now - newDate(row.datetime))/1000.0).toFixed(1)
row.mid_name
row.port
row.address
row.device_info
row.bin_name
row.bin_section_name
row.read_type_short_name
row.error_code
row.value
row.raw_data
])
#@_$spinner.hide()
@_$table.show()
dt = @_$table.dataTable({
bPaginate: false
bRetrieve: true
bFilter: true
# aaData: tableData
aoColumns: tableColumns
})
dt.fnClearTable()
dt.fnAddData(tableData)
fixHeights()
cb()
refresh: () ->
@_$spinner.hide()
#@_$table.hide()
@_update()
class window.SensorViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
</h1>
""")
@_$overlay = $('<div class="diagnostics_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
@_$spinner = $('<img class="center_margins spinner" src="imgs/ajax-loader.gif" alt="Loading Spinner"/>')
@_$overlay.append(@_$spinner)
@_selfVisible = false
@_$selfDiv.on('DOMAttrModified', () =>
if @_$selfDiv.is(':visible') and not @_$selfVisible
console.log('Diag div visible')
@_$selfVisible = true
@refresh()
else if not @_$selfDiv.is(':visible')
@_$selfVisible = false
);
_replace: (str, replaceMap) ->
if str
for key, value of replaceMap
str2 = null
while str != str2
if str2
str = str2
str2 = str.replace(key, value)
return str
_header: (header, $div) ->
$header = $('h2', $div)
if not $header[0]
cssclass=''
label=''
if header.label?
label = header.label
if header.class?
cssclass = header.class
$header = $("<h2 class=\"#{cssclass}\"><span>#{label}</span></h2>")
$div.append($header)
_findWindDirection: (bin_id, readings) ->
if not readings
return 0
if IsadoreData?.general?.configs?.sensor_view?.no_fill_no_arrows? and IsadoreData.general.configs.sensor_view.no_fill_no_arrows and not CurrentDataUtil.getBinFill(@_fills, bin_id, true).id?
return 0
top_temp = 0
bottom_temp = 0
for reading in readings
if IsadoreData.readTypesIdMap[reading.read_type_id].name == 'Temperature'
if IsadoreData.binSectionsIdMap[reading.bin_section_id].name == "Bottom"
bottom_temp = reading.value
else if IsadoreData.binSectionsIdMap[reading.bin_section_id].name == "Top"
top_temp = reading.value
if top_temp != 0 and bottom_temp != 0
return (bottom_temp - top_temp)
return 0
_tableRowClass: (binId) ->
for al in IsadoreData.selfAlarms
# TODO: Fix hard code
if al.alarm_type_id == 14
if al.greater_than_p
alarmReadings = _.filter(IsadoreData.readings, (o) ->
return o.bin_id == binId && (o.bin_section_id == 13 || o.bin_section_id == 14) && o.read_type_id == 10 && o.value > al.value
);
if alarmReadings.length > 0
return 'red'
else
alarmReadings = _.filter(IsadoreData.readings, (o) ->
return o.bin_id == binId && (o.bin_section_id == 13 || o.bin_section_id == 14) && o.read_type_id == 10 && o.value <= al.value
);
if alarmReadings.length > 0
return 'red'
return null
_updateTable: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
divclass = ''
if block.alignment == 'left'
$specificDiv = $('<div class="specific"></div>')
@_$selfDiv.append($specificDiv)
$spleft = $('<div class="spleft"></div>')
$specificDiv.append($spleft)
$div = $('<div name="block'+i+'" style="margin-right: 3.5%;"></div>')
$spleft.append($div)
else if block.alignment == 'right'
$specificDiv = $('div[name="block'+(i-1)+'"]', @_$selfDiv).parent().parent()
divclass = 'spright'
$div = $('<div name="block'+i+'" class="'+divclass+'"></div>')
$specificDiv.append($div)
else
@_$selfDiv.append($('<div class="clears"></div>'))
$div = $('<div name="block'+i+'" class="'+divclass+'"></div>')
@_$selfDiv.append($div)
if block.header?
@_header(block.header, $div)
$table = $('table', $div)
if not $table[0]
$table = $('<table class="display hover" rules="rows"></table>')
$div.append($table)
#First lets make columns
aoColumns = []
for column in block.columns
stringReplacements = {
$bin_section_name$: ''
$read_type_name$: ''
$read_type_short_name$: ''
$read_type_units$: ''
}
if block.row_type == 'bin' and column.bin_section_id?
bin_section = IsadoreData.binSectionsIdMap[column.bin_section_id]
stringReplacements['$bin_section_name$'] = bin_section.name
if column.read_type_id?
read_type = IsadoreData.readTypesIdMap[column.read_type_id]
stringReplacements.$read_type_name$ = read_type.name
stringReplacements.$read_type_short_name$ = read_type.short_name
stringReplacements.$read_type_units$ = read_type.units
sTitle = @_replace(column.column_label, stringReplacements)
aoColumns.push({sTitle: sTitle})
aoColumns.push({sTitle: 'data-bin_id', bVisible: false})
#Now data
tableData = []
if block.row_type == 'bin'
for bin_id in block.bin_ids
bin = _.find(IsadoreData.bins, {id: bin_id})
if not bin
console.log('Could not find bin id: '+bin_id)
row = @_updateTable2(block, bin, null)
row.push(bin_id)
tableData.push(row)
else # 'section' row_type
bin =_.find(IsadoreData.bins, {id: block.bin_id})
for bin_section_id in block.bin_section_ids
bin_section = IsadoreData.binSectionsIdMap[bin_section_id]
row = @_updateTable2(block, bin, bin_section)
row.push(bin.id)
tableData.push(row)
dt = $table.dataTable({
bPaginate: false
bRetrieve: true
bFilter: false
aoColumns: aoColumns
fnRowCallback: (nRow, aData, ididx, ididxf) =>
nRow.setAttribute('data-bin_id', aData[aData.length-1])
rowClass = @_tableRowClass(aData[aData.length-1])
if rowClass
$(nRow).addClass(rowClass)
$('td', $(nRow)).addClass(rowClass)
return nRow
})
dt.fnClearTable()
dt.fnAddData(tableData)
elems = $('tbody tr', $table)
elems.unbind('click', lightboxHandlers.binLightbox.binClick)
elems.click(lightboxHandlers.binLightbox.binClick)
fixHeights()
_updateTable2: (block, bin, bin_section) ->
rowData = []
hourAgo = HTMLHelper.datetimeDelta({date: new Date(), hours: -1})
for column in block.columns
stringReplacements = {
$bin_number$: ''
$bin_name$: ''
$bin_section_name$: ''
$valueF1$: 'NA'
$valueF2$: 'NA'
}
stringReplacements.$bin_name$ = bin.name
binNameSegments = bin.name.split(' ')
bin_section_id = null
read_type_id = null
if binNameSegments.length > 1
stringReplacements.$bin_number$ = binNameSegments[1]
if block.row_type == 'bin' and column.bin_section_id?
bin_section = IsadoreData.binSectionsIdMap[column.bin_section_id]
bin_section_id = bin_section.id
stringReplacements['$bin_section_name$'] = bin_section.name
else if block.row_type == 'section'
bin_section_id = bin_section.id
stringReplacements['$bin_section_name$'] = bin_section.name
if column.read_type_id?
read_type = IsadoreData.readTypesIdMap[column.read_type_id]
read_type_id = read_type.id
reading = _.find(IsadoreData.lastReadings, {bin_id: bin.id, bin_section_id: bin_section_id, read_type_id: read_type_id})
if reading && reading.value && reading.datetime > hourAgo
stringReplacements.$valueF1$ = reading.value.toFixed(1)
stringReplacements.$valueF2$ = reading.value.toFixed(2)
rowData.push(@_replace(column.value, stringReplacements))
return rowData
_updateDiagram: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
$div = $('<div name="block'+i+'"></div>')
@_$selfDiv.append($div)
if block.header?
@_header(block.header, $div)
# reference: jQuery cookbook 5.1
html = []
html[html.length] = '<table class="layout_table" rules="rows" style="table-layout: fixed">'
html[html.length] = '<tbody>'
miny = 999999999
if not IsadoreData.general.configs.hasOwnProperty('bin_layout_empties') or IsadoreData.general.configs.bin_layout_empties
maxy = 0
maxx = 0
for bin in IsadoreData.bins
if bin.y < 0 or not (block.yindexes == 'all' or bin.y in block.yindexes)
continue
if bin.y < miny
miny = bin.y
if bin.y > maxy
maxy = bin.y
if bin.x > maxx
maxx = bin.x
td=[]
for x in [0..maxx]
td[td.length] = '<td class="empty"></td>'
td = td.join('')
# Lets make grid first
for y in [miny..maxy]
if y % 2 == 0
html[html.length] = '<tr class="layout_top">'+td+'</tr>'
html[html.length] = '<tr class="layout_top_labels">'+td+'</tr>'
else if y % 2 == 1
html[html.length] = '<tr class="layout_bottom_labels">'+td+'</tr>'
html[html.length] = '<tr class="layout_bottom">'+td+'</tr>'
else
sortedBins = _.sortBy(IsadoreData.bins, ['y', 'x'])
y = -1
tds = []
miny = 0
if block.yindexes != 'all'
miny = _.min(block.yindexes)
for bin in sortedBins
if (block.yindexes == 'all' or bin.y in block.yindexes) and bin.y >= 0 and y != bin.y
tds.push([])
y = bin.y
if bin.y >= 0 and bin.x >= 0
tds[tds.length-1].push('<td class="empty"></td>')
for y in [0...tds.length]
td = tds[y].join('')
if y % 2 == 0
html.push('<tr class="layout_top">'+td+'</tr>')
html.push('<tr class="layout_top_labels">'+td+'</tr>')
else if y % 2 == 1
html.push('<tr class="layout_bottom_labels">'+td+'</tr>')
html.push('<tr class="layout_bottom">'+td+'</tr>')
html[html.length] = '</tbody>'
html[html.length] = '</table>'
table = $(html.join(''))
# Then fill in the grid.
for bin in IsadoreData.bins
if (block.yindexes == 'all' or bin.y in block.yindexes) and bin.y >= 0
name = bin.name
if name == 'empty'
continue
imgStr=''
# TODO: Check for red status. If so add class="red" in td
# top/bottom
if name.indexOf('Fan') >= 0
imgStr = '<img src="imgs/icon_fan_gray.png" alt="Fan"/>'
else if name.indexOf('Burner') >= 0
imgStr = '<img src="imgs/icon_burner_gray.png" alt="Fan"/>'
else # Normal bin
# Check air flow direction
if bin.readings
windDir = @_findWindDirection(bin.id, bin.readings)
if windDir > 0
imgStr = '<img src="imgs/icon_arrowUP_gray.png" alt="Bin Up" />'
else if windDir < 0
imgStr = '<img src="imgs/icon_arrowDOWN_gray.png" alt="Bin Down" />'
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).removeClass('empty')
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('data-bin_id', bin.id)
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('data-bin_id', bin.id)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).removeClass('empty')
if bin.y % 2 == 0
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).html(imgStr)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).html(name)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan);
else
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).html(name)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).html(imgStr)
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan);
$div.empty()
$div.append($('<div name="wind_instructions">Arrows indicate air direction</div>'))
$div2 = $('<div class="layout"></div>')
$div.append($div2)
$div2.append(table)
elems = $('.layout_table td[data-bin_id]', $div)
elems.unbind('click', lightboxHandlers.binLightbox.binClick)
elems.click(lightboxHandlers.binLightbox.binClick)
tableSize = $('.layout_table', $div).width()
#$('.layout_table td').width(tableSize/(maxx+1))
_updateConfig: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
$div = $('<div name="block'+i+'"></div>')
$div.append($("""
<h1>
<span>Sensor View Config</span>
</h1>
<input data-key="<KEY>" type="checkbox"/> <label for="sensor_view_config_no_fill_no_arrows">Only display arrows when open fill.</label>
"""))
@_$selfDiv.append($div)
no_fill_no_arrows_checkbox = $('input', $div);
if IsadoreData.general?.configs?.sensor_view?.no_fill_no_arrows? and IsadoreData.general.configs.sensor_view.no_fill_no_arrows
no_fill_no_arrows_checkbox.prop('checked', true)
else
no_fill_no_arrows_checkbox.prop('checked', false)
no_fill_no_arrows_checkbox.change(() =>
if(no_fill_no_arrows_checkbox.attr('checked'))
val = true
else
val = false
IsadoreData.general?.configs?.sensor_view?.no_fill_no_arrows = val
if not IsadoreData.selfAccount.configs?
IsadoreData.selfAccount.configs = {}
if not IsadoreData.selfAccount.configs.sensor_view?
IsadoreData.selfAccount.configs.sensor_view = {}
IsadoreData.selfAccount.configs.sensor_view.no_fill_no_arrows = val
newConfigs = _.cloneDeep(IsadoreData.selfAccount.configs)
$.ajax({
url: "../resources/accounts/#{IsadoreData.selfAccount.id}"
type: 'PUT'
dataType: 'text'
data: {configs: JSON.stringify(newConfigs)}
})
@refresh()
)
_update: () ->
for i in [0...@_viewConfig.block.length]
block = @_viewConfig.block[i]
if block.type == 'table'
@_updateTable(i, block)
else if block.type == 'diagram'
@_updateDiagram(i, block)
else if block.type == 'config'
@_updateConfig(i, block)
@_$spinner.hide()
refresh: () ->
@_$spinner.show()
#@_$table.hide()
#@_update()
DataManager.getFills({
year: new Date().getFullYear(),
callback: (d)=>
@_fills = d.fills
@_update()
})
class window.CurrentDataHandler
constructor: () ->
$('#content_current_data').tabs({activate: () -> fixHeights()})
_refresh: () ->
if @fillSub?
DataManager.dataUnSub(@fillSub)
@fillSub = null
@fillSub = DataManager.dataSub({
key: "<KEY>",
type: ['edit', 'add', 'delete'],
year: parseInt(new Date().getFullYear(), 10)
callback: () =>
@refresh()
})
$('.last_update_datetime').html(IsadoreData.lastReadingsTime)
for otherView in @_otherViews
otherView.refresh(@_fills)
fixHeights()
_populateOtherTabs: () ->
if @_otherViews?
return
#Make other tabs and views
if IsadoreData.general.configs?.other_views?
@_otherViews = []
for view in IsadoreData.general.configs.other_views
viewTitle = view.title
viewType = view.type
viewUUID = uuid.v4()
if viewType == "fill_view"
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new CurrentDataFillViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
else if viewType == "diagnostics"
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new DiagnosticsViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
else if viewType == 'sensor_view'
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new SensorViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
$('#content_current_data').tabs('refresh')
$('#content_current_data').tabs('select', 0)
else
$('#content_current_data').tabs('refresh')
# Update the current data page if visible.
refresh: () ->
if not $('#content_current_data').is(':visible')
return
@_populateOtherTabs()
checkClientVersion()
console?.log?('Current Data refresh')
$('#menu_current_data').removeClass('unselected')
$('#menu_current_data').addClass('selected')
DataManager.getFills({
year: new Date().getFullYear(),
callback: (d)=>
@_fills = d.fills
@_refresh()
})
| true | # Copyright 2010-2019 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#Other View format
#"other_views": [ #Array of view objects
# {
# "title": "Fill View", #display title of view
# "type": "fill_view|diagnostics|sensor_view", #Type of view
# #The view object for fill_view
# "view": {
# "fill_view_list": [ # Array list of fill_views, will do it in order
# {
# "view": "fill_view", #name of the view there are fill_view and fill_view_cell# as possibilities
# # fill_view goes through a list of bins and fill_view_cell# is more standalone.
# # you can have multiple fill_view with different bins it goes through.
# # You might want to do fill_view, some fill_view_cells, and fill_view again.
# "bin_ids": [ # Array of bin ID's to go through in the "fill_view" view
# 12, 13, 14, ...
# ],
# "options": { # Fill view options
# "table_class": "original_fill_view" #What class this fill_view table should have original_fill_view or pleasent_fill_view for example
# "hide_labels": true, #default false, this hides the left side labels of a fill_view
# "column_class": [ #Allows settings column css class based off result of a function See "FillViewStyler"
# {
# "func": "fillStatusStyle", #Function to use to determine column css class
# "keys": [ #data keys that go with the function.
# "fill.filled_datetime", "fill.emptied_datetime", "fill.air_begin_datetime", ...
# ]
# }
# ],
# "hover": { #Hoover options
# "row_disable": true, #Disable row hovering, default false
# "thead_enable": true, #Enable hovering head when novered over column default false
# }
# "clickfunc": "fillDialog|binLightBoxClick,.." #Which function in CurrentDataClick to use when clicking on a the table, default 'binLightboxClick'
# }
# },
# {
# "view": "fill_view_cell1", #Id for a cell view to go through
# "options": {
# "table_class": "original_fill_view" #What class this cell view table will have
# }
# }
# {
# "view": "raw1", #Just display some raw html, no key below that needs to match.
# "html": "<table class=\"fill_view_legend\"><tr><td class=\"bolded\" colspan=\"2\">Legend</td></tr><tr><td>Up Air</td><td class=\"fv_upair\">Value</td></tr><tr><td>Down Air</td><td class=\"fv_downair\">Value</td></tr><tr><td>Burners</td><td>PV (SP)</td></tr><tr><td>Full/Drying</td><td class=\"fv_full\"></td></tr><tr><td>Empty</td><td class=\"fv_empty\"></td></tr><tr><td>Shelling</td><td class=\"fv_shelling\"></td></tr><tr><td>Filling</td><td class=\"fv_filling\"></td></tr></table>" #html as a string
# }
# ... other fill_view_cells, or fill_views, or raw lists...
# ],
# "fill_view": [ #What to show in the fill_view
# {
# "label": "Fill #", #Lable to display on the left of fill_view table
# "keys": [ #Array of data keys, could be fill.fill_column or readings.binsection_sensorshortname
# "fill.fill_number"
# "readings.top_temp",
# "readings.bottom_temp"
# ],
# "format": null, #Which format function to send data to. See object "FillViewFormater"
# "class": [ #Which classes the contents of a colum in a fill_view should have
# {
# "func": "upDownAirStyle", #Function to call in "FillViewStyler"
# "keys": [ #data keys that go to function
# "readings.top_temp", "readings.bottom_temp", ...
# ]
# },
# ... More class functions or string for static class...
# ]
# },
# ... more stuff to show in fill_view
# ],
# "fill_view_cell1": [ #What to display in the cell table
# {
# "label": "Burner 1", #Cell name
# "class": "bolded" #Class content should have in cell. Can also be a array with object.func object.keys like in fill_view
# },
# {
# "label": "Burner SP",
# "bin_id": 100, #Which bins can be array of multiple binIds, data keys then being readings0, readings1, ..., instead of just readings
# "colspan": 3, # How many columns the cell should take up, default is 1
# "keys": [ #Data keys similar to fill_view keys
# "readings.burner.sp"
# ],
# "format": "fixed1T" #format function see "FillViewFormater"
# "display": "adjacent" #if "adjacent, there should be no linebreak between label and value
# "readings_func": "upBinsCount" # should get value using a entire readings function, instead of bin/fill based, see "FillViewFunc"
# },
# ... More cells to display ...
# ],
# ... More fill_view_cell# ...
# }
# # diagnostics view
# "view": {
# "interval": 1500 #refresh_in_milliseconds
# }
# # sensor_view
# "view": {
# block: [ #Can have any number of types in any order
# #Type table
# {
# "type": "table",
# "row_type": "bin|section",
# "alignment": "full|left|right",
# "columns": [
# {
# "bin_section_id": int, # If 'bin' row_type, or null if just want a label column
# "read_type_id": int, # Can be null if just want a label column
# "column_label": string, #keys: $bin_section_name$, $read_type_short_name$, $read_type_units$, $read_type_name$
# "value": string # keys: $bin_number$, $bin_name$, $bin_section_name$, $valueF1$, $valueF2$
# }, ...
# ],
# "bin_ids": [int, int, ...], # if 'bin' row_type
#
# "bin_id": int, # if 'section' row_type
# "bin_section_ids": [int, int, ...], # if 'section' row_type
#
# "header": { # or can be null
# "label": string,
# "class": string
# }
# },
# #Type diagram
# {
# "type": "diagram",
# "yindexes": [int, int, ...], # or "all"
# "header": { # or can be null
# "label": string,
# "class": string
# }
# },
# {
# "type": "config"
# }
# ...
# ]
# }
# }
FillViewStyler = {
upDownAirStyle: (topTemp, bottomTemp) ->
if topTemp > bottomTemp
return "fv_downair"
else if(topTemp < bottomTemp)
return "fv_upair"
return null
fillStatusStyle: (type, filled, emptied, air_begin, air_end, roll) ->
if type == 2
return "fv_bypass"
else
if air_end and !emptied
return "fv_shelling"
if air_begin and !air_end
return "fv_drying"
if filled and !air_begin
return "fv_filling"
if not filled
return "fv_empty"
return "fv_unknown"
}
FillViewFormater = {
lastSample: (during_mc) ->
last = null
for mcd in during_mc
mc = mcd[0]
d = newDate(mcd[1])
if not last or d > last[1]
last = [mc, d]
if last
return last[0].toFixed(1)
lastSampleDate: (during_mc) ->
last = null
for mcd in during_mc
mc = mcd[0]
d = newDate(mcd[1])
if not last or d > last[1]
last = [mc, d]
if last
return HTMLHelper.dateToReadableO3(last[1])
_mean: (array) ->
if not array
return null
if not _.isArray(array)
return array
if array.length == 0
return null
s = 0
for a in array
s += a
s=s/array.length
return s
mean: (array) ->
if array
if not _.isArray(array)
return array.toFixed(2)
t = @_mean(array)
if t
return t.toFixed(2)
return null
meanArg: (array...) ->
return @mean(array)
timeUpCalc: (begin, roll) ->
# TODO: Air deducts
# TODO: Support multiple rolls
if begin
begin = newDate(begin)
if roll and roll.length > 0
if _.isArray(roll)
t = newDate(roll[0])
else
t = newDate(roll)
return FillViewFormater.timeDiff(t, begin)
else
return FillViewFormater.timeDiffNow(begin)
return null
timeDiffNow: (time, orend) ->
# TODO: Air deducts
# TODO: Support multiple rolls
if orend and orend != ''
orend = newDate(orend)
else
orend = null
t = null
now = new Date()
if time
if _.isArray(time)
t = newDate(time[0])
else
t = newDate(time)
if orend
t = FillViewFormater.timeDiff(orend, t)
else
t = FillViewFormater.timeDiff(now, t)
return t
timeDiff: (gr, ls) ->
if not gr or not ls
return null
else
return ((gr.getTime() - ls.getTime())/(1000.0*60*60)).toFixed(2)
airDirection: (topt, bott) ->
t = @_mean(topt)
b = @_mean(bott)
if t and b
r=(b-t)
if r > 0
return 'Up'
else if r < 0
return 'Down'
return null
fixed1T: (t, u) ->
t2 = @_mean(t)
if t2
return t2.toFixed(1)
return null
fixed1P: (rh) ->
t2 = @_mean(rh)
if t2
return t2.toFixed(1)
return null
numberSplit: (str) ->
a = str.split(' ')
for v in a
i = parseInt(v, 10)
if(!isNaN(i))
return i
return NaN
twoPerns: (v1, v2) ->
return v1.toFixed(1)+' ('+v2.toFixed(1)+')'
}
FillViewFunc = {
_binCount: (up, readings, fills, nameFilter) ->
upCount = 0
downCount = 0
for binId, bin of readings
binId = parseInt(binId, 10)
if nameFilter
bn = _.findWhere(IsadoreData.bins, {id: binId})
if not bn.name.match(nameFilter)
continue
if bin.top_temp? and bin.bottom_temp?
fill = CurrentDataUtil.getBinFill(fills, binId, false)
if not fill.id?
continue
fstyle = FillViewStyler.fillStatusStyle(fill.fill_type_id, fill.filled_datetime, fill.emptied_datetime, fill.air_begin_datetime, fill.air_end_datetime, fill.roll_datetime)
if fstyle != "fv_drying"
continue
if up and bin.top_temp < bin.bottom_temp
upCount++
if !up and bin.top_temp > bin.bottom_temp
downCount++
if up
return upCount + " Up Bins"
else
return downCount + " Down Bins"
# Calculates and outputs string of number of bins in up air
upBinsCount: (readings, fills) ->
return this._binCount(true, readings, fills)
# Calculates and ouputs string number of bins in down air
downBinsCount: (readings, fills) ->
return this._binCount(false, readings, fills)
#TODO: Be able to send custom arguments to readings_func
# Calculates and outputs string of number of bins in up air
upBinsCountFilter1: (readings, fills) ->
return this._binCount(true, readings, fills, new RegExp('^Bin 1'))
# Calculates and ouputs string number of bins in down air
downBinsCountFilter1: (readings, fills) ->
return this._binCount(false, readings, fills, new RegExp('^Bin 1'))
# Calculates and outputs string of number of bins in up air
upBinsCountFilter2: (readings, fills) ->
return this._binCount(true, readings, fills, new RegExp('^Bin 2'))
# Calculates and ouputs string number of bins in down air
downBinsCountFilter2: (readings, fills) ->
return this._binCount(false, readings, fills, new RegExp('^Bin 2'))
}
window.CurrentDataUtil = {
getBinFill: (fills, bin_id, air_end) ->
now = new Date()
for fill in fills by -1
if fill and fill.bin_id == bin_id and not fill.emptied_datetime? and (not air_end || not fill.air_end_datetime?)
if fill.filled_datetime?
fill.filled_datetime = newDate(fill.filled_datetime)
if fill.air_begin_datetime?
fill.air_begin_datetime = newDate(fill.air_begin_datetime)
#If filled > now and (not emptied) or air_begin > now and not air_end
if ((fill.filled_datetime? and fill.filled_datetime < now) or (fill.air_begin_datetime? and fill.air_begin_datetime < now))
return fill
return {}
}
CurrentDataClick = {
_getFillYear: (yfill) ->
if yfill.filled_datetime?
year = newDate(yfill.filled_datetime).getFullYear()
else
year = newDate(yfill.air_begin_datetime).getFullYear()
return year
_openNewFill: (binId) ->
lightboxHandlers.editFillLightbox.open({
year: new Date().getFullYear()
bin_id: binId
})
_openEditFill: (fill) ->
self=this
lightboxHandlers.editFillLightbox.open({year: self._getFillYear(fill), fill_id: fill.id})
binLightboxClick: (binId, fill) ->
lightboxHandlers.binLightbox.open(binId)
fillDialog: (binId, fill) ->
#TODO: Check privs do binLightboxClick if not enough privs
bin = IsadoreData.getBin(binId)
hasPriv = true
if not hasPriv or bin.name.indexOf('Bin') != 0
this.binLightboxClick(binId, fill)
else
statusStyle = FillViewStyler.fillStatusStyle(fill.fill_type_id, fill.filled_datetime, fill.emptied_datetime, fill.air_begin_datetime, fill.air_end_datetime, fill.roll_datetime)
if statusStyle == 'fv_empty'
this._openNewFill(binId)
else
this._openEditFill(fill)
}
class window.CurrentDataFillViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_fills = []
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
</h1>
""")
@_$overlay = $('<div class="fill_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
_getBinReadings: (bin_id) ->
if @_readings?.hasOwnProperty(bin_id)
return @_readings[bin_id]
return {}
_getCellData: (bin_id) ->
data = {}
if _.isArray(bin_id)
for i in [0...bin_id.length]
data['fill'+i] = CurrentDataUtil.getBinFill(@_fills, bin_id[i], false)
data['readings'+i] = @_getBinReadings(bin_id)
data['bin'+i] = IsadoreData.getBin(bin_id)
else
data = {fill: CurrentDataUtil.getBinFill(@_fills, bin_id, false), readings: @_getBinReadings(bin_id), bin: IsadoreData.getBin(bin_id)}
_getCellValue: (data, onlyIfFill, keys, format) ->
if onlyIfFill and not data.fill?.id?
return null
val = null
if format
try
args = []
for key in keys
obj = data
for k in key.split('.')
obj = obj[k]
args.push(obj)
val = FillViewFormater[format].apply(FillViewFormater, args)
catch e
#console?.error?(e)
val = null
else if keys.length > 0
try
obj = data
for k in keys[0].split('.')
obj = obj[k]
val= obj
if val and k.indexOf('_datetime') == k.length - 9
val = HTMLHelper.dateToReadableO3(newDate(val))
catch e
#console?.error?(e)
val = null
return val
_makeFillViewCellRow: (row) ->
if not @_viewConfig.hasOwnProperty(row.view)
return null
columns = @_viewConfig[row.view]
tr = $('<tr></tr>')
for column in columns
td = $('<td></td>')
cell_value = null
content = null
if column.label?
content = column.label
if column.class?
td.attr('class', column.class)
if column.colspan?
td.attr('colspan', column.colspan)
if column.keys? and column.bin_id?
cell_value = @_getCellValue(@_getCellData(column.bin_id), false, column.keys, column.format)
if cell_value
if content and (!column.display? or column.display != 'adjacent')
content += "<br/>"+cell_value
else
content = cell_value
if column.readings_func?
try
cell_value2 = FillViewFunc[column.readings_func].apply(FillViewFunc, [@_readings, @_fills])
if content and (!column.display? or column.display != 'adjacent')
content += "<br/>"+cell_value2
else
content = cell_value2
catch e
if console?.error?
console.error(e)
if content
td.html(content)
if column.bin_id?
td.attr('data-info', ''+column.bin_id)
tr.append(td)
return tr
_getDynamicClass: (classInfo, bin_id) ->
if _.isString(classInfo)
return classInfo
cssClasses = []
if !_.isArray(classInfo) and _.isObject(classInfo)
cl = @_getDynamicClassFromObj(classInfo, bin_id)
if cl
cssClasses.push(cl)
else if _.isArray(classInfo)
for classObj in classInfo
cl = @_getDynamicClassFromObj(classObj, bin_id)
if cl
cssClasses.push(cl)
return cssClasses.join(' ')
_getDynamicClassFromObj: (classObj, bin_id) ->
if classObj.plain? and _.isString(classObj.plain)
return classObj.plain
if classObj.func? and _.isString(classObj.func)
data = null
if classObj.bin_id?
data = @_getCellData(classObj.bin_id)
else if bin_id
data = @_getCellData(bin_id)
try
args = []
for key in classObj.keys
obj = data
for k in key.split('.')
obj = obj[k]
args.push(obj)
val = FillViewStyler[classObj.func].apply(FillViewStyler, args)
catch e
console?.error?(e)
val = null
return val
return null
_makeRowTable: (row) ->
table = $('<table class="fill_view_table"></table>')
fv = null
arow = row
if @_viewConfig.fill_view?
fv = @_viewConfig.fill_view
table_data = []
if row.view == 'fill_view'
# First row is bin_names
table_row = [{'data-info': -1, content: "Bin"}]
for bin_id in row.bin_ids
if bin_id == "empty"
table_row.push({'data-info': -1, content: ' ', 'data-columnclass': 'fv_nodata'})
else
name = IsadoreData.getBin(bin_id).name.split(" ")
if name.length > 1
name = name[1]
else
name = name[0]
table_column = {'data-info': bin_id, content: name}
if row.options?.column_class?
cl = @_getDynamicClass(row.options.column_class, bin_id)
if cl
table_column['data-columnclass'] = cl
table_row.push(table_column)
table_data.push(table_row)
for fv_row in fv
table_row=[]
table_row.push(fv_row.label)
for bin_id in row.bin_ids
if bin_id == "empty"
table_row.push(' ')
else
cell_value = @_getCellValue(@_getCellData(bin_id), true, fv_row.keys, fv_row.format)
cell_class = null
if fv_row.class?
cell_class = @_getDynamicClass(fv_row.class, bin_id)
table_row.push({'data-info': bin_id, content: cell_value, class: cell_class})
table_data.push(table_row)
#Make HTML from table_data
firstRow = true
thead = $('<thead></thead>')
table.append(thead)
tbody = $('<tbody></tbody>')
table.append(tbody)
for row in table_data
if firstRow
tr = $('<tr></tr>')
thead.append(tr)
else
tr = $('<tr></tr>')
tbody.append(tr)
firstColumn = true
for column in row
if firstColumn or firstRow
td = $('<th></th>')
else
td = $('<td></td>')
if _.isObject(column)
if column.hasOwnProperty('data-columnclass')
td.attr('data-columnclass', column['data-columnclass'])
if column.hasOwnProperty('data-info')
td.attr('data-info', column['data-info'])
if column.content?
td.html(column.content)
if column.class?
td.addClass(column.class)
else
td.html(column)
if not firstColumn or !(arow.options?.hide_labels)
tr.append(td)
firstColumn = false
firstRow = false
return table
_makeColumnClass: ($table) ->
$tr = $('tr:first-child', $table)
$('th, td', $tr).each( (index, element) ->
rc = $(element).attr('data-columnclass')
$(element).addClass(rc)
if rc
$('tbody tr', $table).each( (index2, element2) ->
$('th,td', element2).eq(index).addClass(rc)
)
)
_makeHover: (table, hoverOptions) ->
table.delegate('tbody th,tbody td', 'mouseover mouseleave', (e) ->
$ourTd=$(this)
if e.type == 'mouseover'
if not hoverOptions?.row_disable
$('th,td', $ourTd.parent()).addClass('hover')
if $ourTd.index() != 0
$('tbody tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).addClass('hover')
)
if hoverOptions?.thead_enable
$('thead tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).addClass('hover')
)
$ourTd.removeClass('hover').addClass('super_hover')
else
$('th,td', $ourTd.parent()).removeClass('hover')
$ourTd.removeClass('super_hover')
$('tbody tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).removeClass('hover')
)
$('thead tr', table).each( (index, element) ->
$('th,td', element).eq($ourTd.index()).removeClass('hover')
)
)
_makeClick: (table, clickfunc) ->
self = this
$('tbody td, thead th', table).click((e) ->
console.log(this)
console.log(clickfunc)
$ourTd=$(this)
idx = $ourTd.index()
bin_id = $ourTd.attr('data-info')
if not bin_id
bin_id = $('thead tr th', table).eq(idx).attr('data-info')
if not clickfunc
clickfunc = 'binLightboxClick'
if bin_id
bin_id = parseInt(bin_id, 10)
console?.log?("Click bin_id #{bin_id}")
fill = CurrentDataUtil.getBinFill(self._fills, bin_id, false)
CurrentDataClick[clickfunc](bin_id, fill)
e.preventDefault()
)
_updateReadingMap: () ->
# _readings has structure
# { binid#: {'lcsection_sshortname': value, ...}, ..}
@_readings = {}
noOldData = true
hourAgo = HTMLHelper.datetimeDelta({date: new Date(), hours: -1})
if noOldData and (not IsadoreData.lastReadingsDatetime? or IsadoreData.lastReadingsDatetime < hourAgo)
console?.log?('Last Reading too long ago for fill view.')
else
for bin in IsadoreData.bins
@_readings[bin.id] = {}
if bin.readings?
for reading in bin.readings
if reading.value? and reading.datetime > hourAgo
readTypeName = IsadoreData.readTypesIdMap[reading.read_type_id].short_name.toLowerCase()
binSectionName = IsadoreData.binSectionsIdMap[reading.bin_section_id].name.toLowerCase()
key = PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI
if not @_readings[bin.id].hasOwnProperty(key)
@_readings[bin.id][key] = reading.value
else if _.isArray(@_readings[bin.id][key])
@_readings[bin.id][key].push(reading.value)
else
@_readings[bin.id][key] = [@_readings[bin.id][key], reading.value]
_makeFillViewCellHover: () ->
$('.fill_view_cell_table', @_$overlay).delegate('td', 'mouseover mouseleave', (e) ->
$ourTd=$(this)
dataInfo = $ourTd.attr('data-info')
if e.type == 'mouseover'
$('.fill_view_cell_table td[data-info="'+dataInfo+'"]', @_$overlay).addClass('hover')
else
$('.fill_view_cell_table td[data-info="'+dataInfo+'"]', @_$overlay).removeClass('hover')
)
_makeFillViewCellClick: () ->
$('.fill_view_cell_table td', @_$overlay).click((e) ->
$ourTd=$(this)
bin_id = $ourTd.attr('data-info')
if bin_id
bin_id = parseInt(bin_id, 10)
console?.log?("Click bin_id #{bin_id}")
lightboxHandlers.binLightbox.open(bin_id)
)
_makeFixedWidthCols: ($table) ->
$colgroup = $('<colgroup></colgroup')
s = $('tbody tr:first-child > td, tbody tr:first-child > th', $table).length
p=100.0/s
for i in [0...s]
$colgroup.append($('<col style="width: '+p+'%"/>'))
$table.prepend($colgroup)
refresh: (fills) ->
@_fills = fills
console?.log?('Fill view refresh')
@_$overlay.empty()
@_updateReadingMap()
fillViewCellTable = null
if @_viewConfig?.fill_view_list?
for row in @_viewConfig.fill_view_list
if row.view == 'fill_view'
fillViewCellTable = null
table = @_makeRowTable(row)
if row.options?.table_class?
#TODO: Extended class option
$(table).addClass(row.options.table_class)
@_makeFixedWidthCols(table)
@_$overlay.append(table)
@_makeHover(table, row.options?.hover)
@_makeColumnClass(table)
@_makeClick(table, row.options?.clickfunc)
else if row.view.indexOf('fill_view_cell') == 0
if not fillViewCellTable
fillViewCellTable = $('<table class="fill_view_cell_table"></table>')
if row.options?.table_class?
#TODO: Extended class option
$(fillViewCellTable).addClass(row.options.table_class)
@_$overlay.append(fillViewCellTable)
cellRow = @_makeFillViewCellRow(row)
if cellRow?
fillViewCellTable.append(cellRow)
else if row.view.indexOf('raw') == 0
rawTable = $(row.html)
@_$overlay.append(rawTable)
@_makeFillViewCellHover()
@_makeFillViewCellClick()
else
@_$overlay.html('Contact Exoteric Analytics if you would like a Fill View.')
fixHeights()
class window.DiagnosticsViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
<button class="reset_diag priv_config">Reset</button>
</h1>
""")
if not IsadoreData.selfAccount.hasPrivilege('Config User')
$('.priv_config', @_$selfDiv).hide()
$('.reset_diag', @_$selfDiv).click(() =>
$.ajax(
{
url: "../resources/data/diagnostics_sensor_data_latest_reset"
type: 'DELETE',
dataType: 'text'
}
)
)
@_$overlay = $('<div class="diagnostics_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
@_$spinner = $('<img class="center_margins spinner" src="imgs/ajax-loader.gif" alt="Loading Spinner"/>')
@_$overlay.append(@_$spinner)
@_$table = $('<table class="diagnostics_table display hover" rules="rows"></table>')
@_$overlay.append(@_$table)
@_selfVisible = false
@_$selfDiv.on('DOMAttrModified', () =>
if @_$selfDiv.is(':visible') and not @_$selfVisible
console.log('Diag div visible')
@_$selfVisible = true
@refresh()
else if not @_$selfDiv.is(':visible')
@_$selfVisible = false
);
_update: () ->
if not @_$overlay.closest(document.documentElement)
return
if not @_$overlay.is(':visible')
@_$table.hide()
@_$spinner.show()
return
@_fetchData(
() =>
return
)
_fetchData: (cb) ->
$.ajax(
{
url: "../resources/data/diagnostics_sensor_data_latest"
type: 'GET',
dataType: 'json'
success: (d) =>
@_refreshTable(d.results, cb)
error: () ->
cb()
}
)
_refreshTable: (d, cb) ->
console.log('_refreshTable')
tableColumns = [
{sTitle: 'dT'},
{sTitle: 'MID Name'},
{sTitle: 'Port'},
{sTitle: 'Address'},
{sTitle: 'Info'},
{sTitle: 'Bin'},
{sTitle: 'Bin Section'},
{sTitle: 'Read Type'},
{sTitle: 'Err'},
{sTitle: 'Value'},
{sTitle: 'Raw'}
]
tableData = []
now = new Date()
for row in d
tableData.push([
((now - newDate(row.datetime))/1000.0).toFixed(1)
row.mid_name
row.port
row.address
row.device_info
row.bin_name
row.bin_section_name
row.read_type_short_name
row.error_code
row.value
row.raw_data
])
#@_$spinner.hide()
@_$table.show()
dt = @_$table.dataTable({
bPaginate: false
bRetrieve: true
bFilter: true
# aaData: tableData
aoColumns: tableColumns
})
dt.fnClearTable()
dt.fnAddData(tableData)
fixHeights()
cb()
refresh: () ->
@_$spinner.hide()
#@_$table.hide()
@_update()
class window.SensorViewHandler
constructor: (viewTitle, $selfDiv, viewConfig) ->
@_viewTitle = viewTitle
@_$selfDiv = $selfDiv
@_viewConfig = viewConfig
@_$selfDiv.append("""
<h1>
#{ viewTitle }<span class="last_update">Sensor Data
Updated <span class="last_update_datetime"></span>
</span>
</h1>
""")
@_$overlay = $('<div class="diagnostics_view_overlay"></div>')
@_$selfDiv.append(@_$overlay)
@_$spinner = $('<img class="center_margins spinner" src="imgs/ajax-loader.gif" alt="Loading Spinner"/>')
@_$overlay.append(@_$spinner)
@_selfVisible = false
@_$selfDiv.on('DOMAttrModified', () =>
if @_$selfDiv.is(':visible') and not @_$selfVisible
console.log('Diag div visible')
@_$selfVisible = true
@refresh()
else if not @_$selfDiv.is(':visible')
@_$selfVisible = false
);
_replace: (str, replaceMap) ->
if str
for key, value of replaceMap
str2 = null
while str != str2
if str2
str = str2
str2 = str.replace(key, value)
return str
_header: (header, $div) ->
$header = $('h2', $div)
if not $header[0]
cssclass=''
label=''
if header.label?
label = header.label
if header.class?
cssclass = header.class
$header = $("<h2 class=\"#{cssclass}\"><span>#{label}</span></h2>")
$div.append($header)
_findWindDirection: (bin_id, readings) ->
if not readings
return 0
if IsadoreData?.general?.configs?.sensor_view?.no_fill_no_arrows? and IsadoreData.general.configs.sensor_view.no_fill_no_arrows and not CurrentDataUtil.getBinFill(@_fills, bin_id, true).id?
return 0
top_temp = 0
bottom_temp = 0
for reading in readings
if IsadoreData.readTypesIdMap[reading.read_type_id].name == 'Temperature'
if IsadoreData.binSectionsIdMap[reading.bin_section_id].name == "Bottom"
bottom_temp = reading.value
else if IsadoreData.binSectionsIdMap[reading.bin_section_id].name == "Top"
top_temp = reading.value
if top_temp != 0 and bottom_temp != 0
return (bottom_temp - top_temp)
return 0
_tableRowClass: (binId) ->
for al in IsadoreData.selfAlarms
# TODO: Fix hard code
if al.alarm_type_id == 14
if al.greater_than_p
alarmReadings = _.filter(IsadoreData.readings, (o) ->
return o.bin_id == binId && (o.bin_section_id == 13 || o.bin_section_id == 14) && o.read_type_id == 10 && o.value > al.value
);
if alarmReadings.length > 0
return 'red'
else
alarmReadings = _.filter(IsadoreData.readings, (o) ->
return o.bin_id == binId && (o.bin_section_id == 13 || o.bin_section_id == 14) && o.read_type_id == 10 && o.value <= al.value
);
if alarmReadings.length > 0
return 'red'
return null
_updateTable: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
divclass = ''
if block.alignment == 'left'
$specificDiv = $('<div class="specific"></div>')
@_$selfDiv.append($specificDiv)
$spleft = $('<div class="spleft"></div>')
$specificDiv.append($spleft)
$div = $('<div name="block'+i+'" style="margin-right: 3.5%;"></div>')
$spleft.append($div)
else if block.alignment == 'right'
$specificDiv = $('div[name="block'+(i-1)+'"]', @_$selfDiv).parent().parent()
divclass = 'spright'
$div = $('<div name="block'+i+'" class="'+divclass+'"></div>')
$specificDiv.append($div)
else
@_$selfDiv.append($('<div class="clears"></div>'))
$div = $('<div name="block'+i+'" class="'+divclass+'"></div>')
@_$selfDiv.append($div)
if block.header?
@_header(block.header, $div)
$table = $('table', $div)
if not $table[0]
$table = $('<table class="display hover" rules="rows"></table>')
$div.append($table)
#First lets make columns
aoColumns = []
for column in block.columns
stringReplacements = {
$bin_section_name$: ''
$read_type_name$: ''
$read_type_short_name$: ''
$read_type_units$: ''
}
if block.row_type == 'bin' and column.bin_section_id?
bin_section = IsadoreData.binSectionsIdMap[column.bin_section_id]
stringReplacements['$bin_section_name$'] = bin_section.name
if column.read_type_id?
read_type = IsadoreData.readTypesIdMap[column.read_type_id]
stringReplacements.$read_type_name$ = read_type.name
stringReplacements.$read_type_short_name$ = read_type.short_name
stringReplacements.$read_type_units$ = read_type.units
sTitle = @_replace(column.column_label, stringReplacements)
aoColumns.push({sTitle: sTitle})
aoColumns.push({sTitle: 'data-bin_id', bVisible: false})
#Now data
tableData = []
if block.row_type == 'bin'
for bin_id in block.bin_ids
bin = _.find(IsadoreData.bins, {id: bin_id})
if not bin
console.log('Could not find bin id: '+bin_id)
row = @_updateTable2(block, bin, null)
row.push(bin_id)
tableData.push(row)
else # 'section' row_type
bin =_.find(IsadoreData.bins, {id: block.bin_id})
for bin_section_id in block.bin_section_ids
bin_section = IsadoreData.binSectionsIdMap[bin_section_id]
row = @_updateTable2(block, bin, bin_section)
row.push(bin.id)
tableData.push(row)
dt = $table.dataTable({
bPaginate: false
bRetrieve: true
bFilter: false
aoColumns: aoColumns
fnRowCallback: (nRow, aData, ididx, ididxf) =>
nRow.setAttribute('data-bin_id', aData[aData.length-1])
rowClass = @_tableRowClass(aData[aData.length-1])
if rowClass
$(nRow).addClass(rowClass)
$('td', $(nRow)).addClass(rowClass)
return nRow
})
dt.fnClearTable()
dt.fnAddData(tableData)
elems = $('tbody tr', $table)
elems.unbind('click', lightboxHandlers.binLightbox.binClick)
elems.click(lightboxHandlers.binLightbox.binClick)
fixHeights()
_updateTable2: (block, bin, bin_section) ->
rowData = []
hourAgo = HTMLHelper.datetimeDelta({date: new Date(), hours: -1})
for column in block.columns
stringReplacements = {
$bin_number$: ''
$bin_name$: ''
$bin_section_name$: ''
$valueF1$: 'NA'
$valueF2$: 'NA'
}
stringReplacements.$bin_name$ = bin.name
binNameSegments = bin.name.split(' ')
bin_section_id = null
read_type_id = null
if binNameSegments.length > 1
stringReplacements.$bin_number$ = binNameSegments[1]
if block.row_type == 'bin' and column.bin_section_id?
bin_section = IsadoreData.binSectionsIdMap[column.bin_section_id]
bin_section_id = bin_section.id
stringReplacements['$bin_section_name$'] = bin_section.name
else if block.row_type == 'section'
bin_section_id = bin_section.id
stringReplacements['$bin_section_name$'] = bin_section.name
if column.read_type_id?
read_type = IsadoreData.readTypesIdMap[column.read_type_id]
read_type_id = read_type.id
reading = _.find(IsadoreData.lastReadings, {bin_id: bin.id, bin_section_id: bin_section_id, read_type_id: read_type_id})
if reading && reading.value && reading.datetime > hourAgo
stringReplacements.$valueF1$ = reading.value.toFixed(1)
stringReplacements.$valueF2$ = reading.value.toFixed(2)
rowData.push(@_replace(column.value, stringReplacements))
return rowData
_updateDiagram: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
$div = $('<div name="block'+i+'"></div>')
@_$selfDiv.append($div)
if block.header?
@_header(block.header, $div)
# reference: jQuery cookbook 5.1
html = []
html[html.length] = '<table class="layout_table" rules="rows" style="table-layout: fixed">'
html[html.length] = '<tbody>'
miny = 999999999
if not IsadoreData.general.configs.hasOwnProperty('bin_layout_empties') or IsadoreData.general.configs.bin_layout_empties
maxy = 0
maxx = 0
for bin in IsadoreData.bins
if bin.y < 0 or not (block.yindexes == 'all' or bin.y in block.yindexes)
continue
if bin.y < miny
miny = bin.y
if bin.y > maxy
maxy = bin.y
if bin.x > maxx
maxx = bin.x
td=[]
for x in [0..maxx]
td[td.length] = '<td class="empty"></td>'
td = td.join('')
# Lets make grid first
for y in [miny..maxy]
if y % 2 == 0
html[html.length] = '<tr class="layout_top">'+td+'</tr>'
html[html.length] = '<tr class="layout_top_labels">'+td+'</tr>'
else if y % 2 == 1
html[html.length] = '<tr class="layout_bottom_labels">'+td+'</tr>'
html[html.length] = '<tr class="layout_bottom">'+td+'</tr>'
else
sortedBins = _.sortBy(IsadoreData.bins, ['y', 'x'])
y = -1
tds = []
miny = 0
if block.yindexes != 'all'
miny = _.min(block.yindexes)
for bin in sortedBins
if (block.yindexes == 'all' or bin.y in block.yindexes) and bin.y >= 0 and y != bin.y
tds.push([])
y = bin.y
if bin.y >= 0 and bin.x >= 0
tds[tds.length-1].push('<td class="empty"></td>')
for y in [0...tds.length]
td = tds[y].join('')
if y % 2 == 0
html.push('<tr class="layout_top">'+td+'</tr>')
html.push('<tr class="layout_top_labels">'+td+'</tr>')
else if y % 2 == 1
html.push('<tr class="layout_bottom_labels">'+td+'</tr>')
html.push('<tr class="layout_bottom">'+td+'</tr>')
html[html.length] = '</tbody>'
html[html.length] = '</table>'
table = $(html.join(''))
# Then fill in the grid.
for bin in IsadoreData.bins
if (block.yindexes == 'all' or bin.y in block.yindexes) and bin.y >= 0
name = bin.name
if name == 'empty'
continue
imgStr=''
# TODO: Check for red status. If so add class="red" in td
# top/bottom
if name.indexOf('Fan') >= 0
imgStr = '<img src="imgs/icon_fan_gray.png" alt="Fan"/>'
else if name.indexOf('Burner') >= 0
imgStr = '<img src="imgs/icon_burner_gray.png" alt="Fan"/>'
else # Normal bin
# Check air flow direction
if bin.readings
windDir = @_findWindDirection(bin.id, bin.readings)
if windDir > 0
imgStr = '<img src="imgs/icon_arrowUP_gray.png" alt="Bin Up" />'
else if windDir < 0
imgStr = '<img src="imgs/icon_arrowDOWN_gray.png" alt="Bin Down" />'
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).removeClass('empty')
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('data-bin_id', bin.id)
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('data-bin_id', bin.id)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).removeClass('empty')
if bin.y % 2 == 0
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).html(imgStr)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).html(name)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan);
else
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).html(name)
$('tr:eq('+(bin.y*2+1 - miny)+') td:eq('+bin.x+')', table).html(imgStr)
$('tr:eq('+(bin.y*2 - miny)+') td:eq('+bin.x+')', table).attr('colspan', bin.display_colspan);
$div.empty()
$div.append($('<div name="wind_instructions">Arrows indicate air direction</div>'))
$div2 = $('<div class="layout"></div>')
$div.append($div2)
$div2.append(table)
elems = $('.layout_table td[data-bin_id]', $div)
elems.unbind('click', lightboxHandlers.binLightbox.binClick)
elems.click(lightboxHandlers.binLightbox.binClick)
tableSize = $('.layout_table', $div).width()
#$('.layout_table td').width(tableSize/(maxx+1))
_updateConfig: (i, block) ->
$div = $('div[name="block'+i+'"]', @_$selfDiv)
if not $div[0]
$div = $('<div name="block'+i+'"></div>')
$div.append($("""
<h1>
<span>Sensor View Config</span>
</h1>
<input data-key="PI:KEY:<KEY>END_PI" type="checkbox"/> <label for="sensor_view_config_no_fill_no_arrows">Only display arrows when open fill.</label>
"""))
@_$selfDiv.append($div)
no_fill_no_arrows_checkbox = $('input', $div);
if IsadoreData.general?.configs?.sensor_view?.no_fill_no_arrows? and IsadoreData.general.configs.sensor_view.no_fill_no_arrows
no_fill_no_arrows_checkbox.prop('checked', true)
else
no_fill_no_arrows_checkbox.prop('checked', false)
no_fill_no_arrows_checkbox.change(() =>
if(no_fill_no_arrows_checkbox.attr('checked'))
val = true
else
val = false
IsadoreData.general?.configs?.sensor_view?.no_fill_no_arrows = val
if not IsadoreData.selfAccount.configs?
IsadoreData.selfAccount.configs = {}
if not IsadoreData.selfAccount.configs.sensor_view?
IsadoreData.selfAccount.configs.sensor_view = {}
IsadoreData.selfAccount.configs.sensor_view.no_fill_no_arrows = val
newConfigs = _.cloneDeep(IsadoreData.selfAccount.configs)
$.ajax({
url: "../resources/accounts/#{IsadoreData.selfAccount.id}"
type: 'PUT'
dataType: 'text'
data: {configs: JSON.stringify(newConfigs)}
})
@refresh()
)
_update: () ->
for i in [0...@_viewConfig.block.length]
block = @_viewConfig.block[i]
if block.type == 'table'
@_updateTable(i, block)
else if block.type == 'diagram'
@_updateDiagram(i, block)
else if block.type == 'config'
@_updateConfig(i, block)
@_$spinner.hide()
refresh: () ->
@_$spinner.show()
#@_$table.hide()
#@_update()
DataManager.getFills({
year: new Date().getFullYear(),
callback: (d)=>
@_fills = d.fills
@_update()
})
class window.CurrentDataHandler
constructor: () ->
$('#content_current_data').tabs({activate: () -> fixHeights()})
_refresh: () ->
if @fillSub?
DataManager.dataUnSub(@fillSub)
@fillSub = null
@fillSub = DataManager.dataSub({
key: "PI:KEY:<KEY>END_PI",
type: ['edit', 'add', 'delete'],
year: parseInt(new Date().getFullYear(), 10)
callback: () =>
@refresh()
})
$('.last_update_datetime').html(IsadoreData.lastReadingsTime)
for otherView in @_otherViews
otherView.refresh(@_fills)
fixHeights()
_populateOtherTabs: () ->
if @_otherViews?
return
#Make other tabs and views
if IsadoreData.general.configs?.other_views?
@_otherViews = []
for view in IsadoreData.general.configs.other_views
viewTitle = view.title
viewType = view.type
viewUUID = uuid.v4()
if viewType == "fill_view"
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new CurrentDataFillViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
else if viewType == "diagnostics"
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new DiagnosticsViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
else if viewType == 'sensor_view'
#Make tab and tab div
$viewDiv = $('<div id="' + viewUUID + '"></div>')
$viewUl = $('<li><a href="#' + viewUUID + '">'+viewTitle+'</a></li>')
$('#content_current_data').append($viewDiv)
$('#content_current_data ul').append($viewUl)
#Make object in tab
otherView = new SensorViewHandler(viewTitle, $viewDiv, view.view)
@_otherViews.push(otherView)
$('#content_current_data').tabs('refresh')
$('#content_current_data').tabs('select', 0)
else
$('#content_current_data').tabs('refresh')
# Update the current data page if visible.
refresh: () ->
if not $('#content_current_data').is(':visible')
return
@_populateOtherTabs()
checkClientVersion()
console?.log?('Current Data refresh')
$('#menu_current_data').removeClass('unselected')
$('#menu_current_data').addClass('selected')
DataManager.getFills({
year: new Date().getFullYear(),
callback: (d)=>
@_fills = d.fills
@_refresh()
})
|
[
{
"context": " 1\n timeout : 10000\n user: 'user'\n password: 'password'\n dom",
"end": 394,
"score": 0.8547061085700989,
"start": 390,
"tag": "USERNAME",
"value": "user"
},
{
"context": "0\n user: 'user'\n password: '... | test/MySQL.coffee | rodolforios/MySQLConnector | 0 | 'use strict'
expect = require 'expect.js'
describe 'the MySQLConnector,', ->
MySQLConnector = null
params = null
connector = null
beforeEach ->
delete require.cache[require.resolve('../src/MySQL')]
MySQLConnector = require '../src/MySQL'
params =
host : 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: 'password'
domain: 'databaseName'
resource: 'tableName'
describe 'when creating a new instance', ->
it 'should throw an exception if one or more params was not passed', ->
expect(->
instance = new MySQLConnector {}
instance.init {}
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host empty object', ->
expect(->
params.host = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is null', ->
expect(->
params.host = null
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is undefined', ->
expect(->
params.host = undefined
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is zero', ->
expect(->
params.host = 0
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is empty string', ->
expect(->
params.host = ''
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if domain is not useful', ->
expect(->
params.domain = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if resource is not useful', ->
expect(->
params.resource = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if user is not useful', ->
expect(->
params.user = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if poolSize is not useful', ->
expect(->
params.poolSize = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should verify if the connection pool was created', ->
createPoolCalled = false
params =
host : 'host'
port : 1111
poolSize : 1
timeout : 10000
user: 'user'
password: 'password'
domain: 'databaseName'
resource: 'tableName'
expectedParams =
host: params.host
port: params.port
database: params.domain
user: params.user
password: params.password
connectionLimit: params.poolSize
acquireTimeout: params.timeout
waitForConnections: 0
deps =
mysql:
createPool: (params) ->
expect(params).to.eql expectedParams
createPoolCalled = true
instance = new MySQLConnector params, deps
expect(instance).to.be.ok()
expect(instance.pool).to.be.ok()
expect(createPoolCalled).to.be.ok()
it 'should verify if the connection pool was created with default port', ->
createPoolCalled = false
params =
host : 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: 'password'
domain: 'databaseName'
resource: 'tableName'
expectedParams =
host: params.host
port: 3306
database: params.domain
user: params.user
password: params.password
connectionLimit: params.poolSize
acquireTimeout: params.timeout
waitForConnections: 0
deps =
mysql:
createPool: (params) ->
expect(params).to.eql expectedParams
createPoolCalled = true
instance = new MySQLConnector params, deps
expect(instance).to.be.ok()
expect(instance.pool).to.be.ok()
expect(createPoolCalled).to.be.ok()
describe 'when reading a specific record', ->
it 'should return an error if the order id is null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order id is undefined', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order id is zero', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById 0, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the executing query went wrong', (done) ->
expectedError = 'Internal Error'
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback expectedError
instance.readById 1, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found row', (done) ->
expectedRow =
reference: 1
amount: 100
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback null, expectedRow
instance.readById 1, (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedRow
done()
it 'should return a NOT_FOUND error if nothing was found', (done) ->
expectedError =
name: 'Not found'
message: ''
type: 'Error'
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback()
instance.readById 1, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
describe 'when reading an order', ->
it 'should hand the mysql error to the callback', (done) ->
expectedError = 'Value too large for defined data type'
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback expectedError
instance.read 'SELECT size FROM yo_mama', (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the order found', (done) ->
expectedOrder =
this: 'is'
your: 'order'
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback null, expectedOrder
instance.read 'SELECT weight_reduction FROM yo_mama', (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedOrder
done()
it 'should return a NOT FOUND error if nothing was found (obviously)', (done) ->
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback()
instance.read 'SELECT weight_reduction FROM yo_mama', (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
describe 'when creating an order', ->
it 'should return an error if the order data is null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is Empty object', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the query error if it happens', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.create data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found rows affected', (done) ->
data =
id : 101
reference: 321321
issuer: 'visa'
auth_token: 'token1'
description: 'Teste recarga'
return_url: 'www.google.com'
amount : 201
payment_type: 'credito_a_vista'
installments: 1
tid: '231345644'
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback()
connector.create data, (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'INSERT INTO tableName SET '
expectedQuery += 'id=?,reference=?,issuer=?,auth_token=?,description=?,return_url=?,amount=?,payment_type=?,installments=?,tid=?'
expectedParams = [
101,
321321,
'visa',
'token1',
'Teste recarga',
'www.google.com',
201,
'credito_a_vista',
1,
'231345644'
]
data =
id: 101
reference: 321321
issuer: 'visa'
auth_token: 'token1'
description: 'Teste recarga'
return_url: 'www.google.com'
amount: 201
payment_type: 'credito_a_vista'
installments: 1
tid: '231345644'
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.create data, ->
describe 'when creating an multiple orders', ->
it 'should return an error if the order data is null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is Empty object', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the query error if it happens', (done) ->
expectedError = 'Error Query'
data = [
{
id: 1
other_id: 2
any_id: 99
}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.multiCreate data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found rows affected', (done) ->
data = [
{
id: 1
other_id: 2
any_id: 99
}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback()
connector.multiCreate data, (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'INSERT INTO tableName (id,other_id,any_id) VALUES (?,?,?),(?,?,?),(?,?,?)'
expectedParams = [10,20,30,15,25,35,25,35,45]
data = [
{
id : expectedParams[0]
other_id : expectedParams[1]
any_id : expectedParams[2]
},
{
id : expectedParams[3]
other_id : expectedParams[4]
any_id : expectedParams[5]
},
{
id : expectedParams[6]
other_id : expectedParams[7]
any_id : expectedParams[8]
}
]
console.log ''
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.multiCreate data, ->
describe 'when deleting', ->
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'DELETE FROM tableName WHERE id=?'
expectedParams = [
101
]
data =
id: 101
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.delete data, ->
describe 'when updating an order', ->
it 'deve receber um erro se o id for undefined', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update undefined, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o id for null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o id for zero', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update 0, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for vazio', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se acontecer algum erro ao efetuar um update', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.update 1,data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve retornar sucesso se não ocorreu nenhum erro', (done) ->
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
connector = new MySQLConnector params
expectedRow =
affected_rows: 1
connector._execute = (query, params, callback)->
callback null, expectedRow
connector.update '123', data, (err, row) ->
expect(err).not.to.be.ok()
expect(row).to.be.eql expectedRow
done()
it 'should pass the expected Query and Params', (done) ->
id = '12345678901234567890'
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
expectedQuery = 'UPDATE tableName SET issuer=?,payment_type=?,installments=? WHERE id=?'
expectedParams = [
data.issuer,
data.payment_type,
data.installments,
id
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.update id, data, ->
describe 'when updating by field an order', ->
it 'deve receber um erro se o field for undefined', (done) ->
expectedError = 'Invalid field'
connector = new MySQLConnector params
connector.updateByField undefined, null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field for null', (done) ->
expectedError = 'Invalid field'
connector = new MySQLConnector params
connector.updateByField null, null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for undefined', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', undefined, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for null', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for zero', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', 0, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for vazio', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
id = '12345678901234567890'
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
expectedQuery = 'UPDATE tableName SET issuer=?,payment_type=?,installments=? WHERE order_id=?'
expectedParams = [
data.issuer,
data.payment_type,
data.installments,
id
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.updateByField 'order_id', id, data, ->
it 'deve receber um erro se acontecer algum problema ao efetuar um update', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.updateByField 'order_id', 1, data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve retornar sucesso se não ocorreu nenhum erro', (done) ->
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
connector = new MySQLConnector params
expectedRow =
affected_rows: 1
connector._execute = (query, params, callback)->
callback null, expectedRow
connector.updateByField 'order_id', '123', data, (err, row) ->
expect(err).not.to.be.ok()
expect(row).to.be.eql expectedRow
done()
describe 'when executing a simple query without values', ->
it 'should validate _execute params', (done) ->
expectedQuery = "SELECT * FROM table1"
expectedParams = []
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.query expectedQuery, ->
it 'should return an error if was a executing query problem', (done) ->
expectedError = 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expectedError
connector.query "", (error, success) ->
expect(error).to.eql expectedError
expect(success).not.to.be.ok()
done()
it 'should return a query results if everything is ok', (done) ->
expectedResults = [
{id:1, name: 'Test'}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback null, expectedResults
connector.query "", (error, success) ->
expect(error).not.to.be.ok()
expect(success).to.eql expectedResults
done()
it 'should return a empty callback if no results found', (done) ->
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback()
connector.query "", (error, success) ->
expect(error).not.to.be.ok()
expect(success).not.to.be.ok()
done()
describe 'when executing a query', ->
it 'should return an error if was a get connection problem', (done) ->
expectedError = 'Database connection failed. Error: my error'
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback 'my error'
instance = new MySQLConnector params, deps
instance._execute '', [], (error, response)->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if was a selecting database', (done) ->
expectedError = 'Error selecting database'
mockedConnection =
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback expectedError
instance._execute '', [], (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error after selecting database', (done) ->
expectedError = 'Internal Error'
mockedConnection =
query: (query, params, callback) ->
callback expectedError
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback()
instance._execute '', [], (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return a expected result if everything was ok', (done) ->
expectedResponse =
affected_rows: 1
mockedConnection =
query: (query, params, callback) ->
callback null, expectedResponse
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback()
instance._execute '', [], (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedResponse
done()
describe 'when selecting a database', ->
it 'should pass the expected Query', (done) ->
databaseName = 's2Pay'
expectedQuery = "USE #{databaseName}"
mockedConnection =
query: (query, values, callback) ->
expect(query).to.eql expectedQuery
expect(values).to.eql []
done()
instance = new MySQLConnector params
instance._selectDatabase databaseName, mockedConnection, ->
describe 'when changing a tableName', ->
it 'deve validar se o nome da tabela foi alterada corretamente', ->
connector = new MySQLConnector params
connector.changeTable 'secondTableName'
expect(connector.table).to.eql 'secondTableName'
describe 'when reading a order with join', ->
mysqlParams = null
joinParams = null
beforeEach ->
mysqlParams =
host: 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: 'password'
domain: 'databaseName'
resource: 'table1'
joinParams =
table: 'table2'
condition: 'table1.id = table2.table1_id'
fields: ['field1','field2']
it 'should return an error if the order id is null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector mysqlParams
connector.readJoin null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join table is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.table
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join condition is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.condition
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join fields is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.fields
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error when executing a query', (done) ->
expectedError = 'Internal error'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback expectedError
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return a row if was found', (done) ->
expectedResponse =
id: '123456789'
something: 'something'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback null, expectedResponse
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedResponse
done()
it 'should return an error if the result was not found', (done) ->
expectedError = 'NOT_FOUND'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback()
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should validate a final query with all params possibilities', (done) ->
expectedQuery = "SELECT field1,field2 FROM table1 JOIN table2 ON table1.id = table2.table1_id WHERE table1.id = ? ORDER BY orderField DESC LIMIT 15"
expectedParams = [123456789]
joinParams.orderBy = 'orderField DESC'
joinParams.limit = 15
inputMessage =
data:
id: 123456789
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.readJoin inputMessage, joinParams, ->
describe 'when start a transaction in connection', ->
it 'should call execute start transaction command', (done) ->
expected =
query: 'START TRANSACTION'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.start_transaction ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.start_transaction (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a commit transaction in connection', ->
it 'should call execute commit command', (done) ->
expected =
query: 'COMMIT'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.commit ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.commit (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a rollback transaction in connection', ->
it 'should call execute ->rollback command', (done) ->
expected =
query: 'ROLLBACK'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.rollback ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.rollback (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a call procedure', ->
it 'should call procedure method', (done) ->
expectedError = 'Internal Error'
connector= new MySQLConnector params
connector._execute = (query, params, callback) ->
done()
connector.callProcedure 'baixa_pedido', [], ->
it 'should return an error message if the procedure execution failed', (done) ->
expectedError = 'Internal error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expectedError
connector.callProcedure 'baixa_pedido', [], (error, success)->
expect(error).to.eql expectedError
expect(success).not.to.be.ok()
done()
it 'should return a procedure result if everything is ok', (done) ->
expectedMessage = 'ok'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback null, expectedMessage
connector.callProcedure 'baixa_pedido', [], (error, success) ->
expect(error).not.to.be.ok()
expect(success).to.eql expectedMessage
done() | 103521 | 'use strict'
expect = require 'expect.js'
describe 'the MySQLConnector,', ->
MySQLConnector = null
params = null
connector = null
beforeEach ->
delete require.cache[require.resolve('../src/MySQL')]
MySQLConnector = require '../src/MySQL'
params =
host : 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: '<PASSWORD>'
domain: 'databaseName'
resource: 'tableName'
describe 'when creating a new instance', ->
it 'should throw an exception if one or more params was not passed', ->
expect(->
instance = new MySQLConnector {}
instance.init {}
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host empty object', ->
expect(->
params.host = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is null', ->
expect(->
params.host = null
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is undefined', ->
expect(->
params.host = undefined
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is zero', ->
expect(->
params.host = 0
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is empty string', ->
expect(->
params.host = ''
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if domain is not useful', ->
expect(->
params.domain = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if resource is not useful', ->
expect(->
params.resource = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if user is not useful', ->
expect(->
params.user = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if poolSize is not useful', ->
expect(->
params.poolSize = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should verify if the connection pool was created', ->
createPoolCalled = false
params =
host : 'host'
port : 1111
poolSize : 1
timeout : 10000
user: 'user'
password: '<PASSWORD>'
domain: 'databaseName'
resource: 'tableName'
expectedParams =
host: params.host
port: params.port
database: params.domain
user: params.user
password: <PASSWORD>
connectionLimit: params.poolSize
acquireTimeout: params.timeout
waitForConnections: 0
deps =
mysql:
createPool: (params) ->
expect(params).to.eql expectedParams
createPoolCalled = true
instance = new MySQLConnector params, deps
expect(instance).to.be.ok()
expect(instance.pool).to.be.ok()
expect(createPoolCalled).to.be.ok()
it 'should verify if the connection pool was created with default port', ->
createPoolCalled = false
params =
host : 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: '<PASSWORD>'
domain: 'databaseName'
resource: 'tableName'
expectedParams =
host: params.host
port: 3306
database: params.domain
user: params.user
password: <PASSWORD>
connectionLimit: params.poolSize
acquireTimeout: params.timeout
waitForConnections: 0
deps =
mysql:
createPool: (params) ->
expect(params).to.eql expectedParams
createPoolCalled = true
instance = new MySQLConnector params, deps
expect(instance).to.be.ok()
expect(instance.pool).to.be.ok()
expect(createPoolCalled).to.be.ok()
describe 'when reading a specific record', ->
it 'should return an error if the order id is null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order id is undefined', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order id is zero', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById 0, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the executing query went wrong', (done) ->
expectedError = 'Internal Error'
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback expectedError
instance.readById 1, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found row', (done) ->
expectedRow =
reference: 1
amount: 100
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback null, expectedRow
instance.readById 1, (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedRow
done()
it 'should return a NOT_FOUND error if nothing was found', (done) ->
expectedError =
name: 'Not found'
message: ''
type: 'Error'
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback()
instance.readById 1, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
describe 'when reading an order', ->
it 'should hand the mysql error to the callback', (done) ->
expectedError = 'Value too large for defined data type'
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback expectedError
instance.read 'SELECT size FROM yo_mama', (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the order found', (done) ->
expectedOrder =
this: 'is'
your: 'order'
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback null, expectedOrder
instance.read 'SELECT weight_reduction FROM yo_mama', (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedOrder
done()
it 'should return a NOT FOUND error if nothing was found (obviously)', (done) ->
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback()
instance.read 'SELECT weight_reduction FROM yo_mama', (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
describe 'when creating an order', ->
it 'should return an error if the order data is null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is Empty object', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the query error if it happens', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.create data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found rows affected', (done) ->
data =
id : 101
reference: 321321
issuer: 'visa'
auth_token: '<PASSWORD>'
description: 'Teste recarga'
return_url: 'www.google.com'
amount : 201
payment_type: 'credito_a_vista'
installments: 1
tid: '231345644'
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback()
connector.create data, (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'INSERT INTO tableName SET '
expectedQuery += 'id=?,reference=?,issuer=?,auth_token=?,description=?,return_url=?,amount=?,payment_type=?,installments=?,tid=?'
expectedParams = [
101,
321321,
'visa',
'token<PASSWORD>',
'Teste recarga',
'www.google.com',
201,
'credito_a_vista',
1,
'231345644'
]
data =
id: 101
reference: 321321
issuer: 'visa'
auth_token: '<PASSWORD>'
description: 'Teste recarga'
return_url: 'www.google.com'
amount: 201
payment_type: 'credito_a_vista'
installments: 1
tid: '231345644'
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.create data, ->
describe 'when creating an multiple orders', ->
it 'should return an error if the order data is null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is Empty object', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the query error if it happens', (done) ->
expectedError = 'Error Query'
data = [
{
id: 1
other_id: 2
any_id: 99
}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.multiCreate data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found rows affected', (done) ->
data = [
{
id: 1
other_id: 2
any_id: 99
}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback()
connector.multiCreate data, (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'INSERT INTO tableName (id,other_id,any_id) VALUES (?,?,?),(?,?,?),(?,?,?)'
expectedParams = [10,20,30,15,25,35,25,35,45]
data = [
{
id : expectedParams[0]
other_id : expectedParams[1]
any_id : expectedParams[2]
},
{
id : expectedParams[3]
other_id : expectedParams[4]
any_id : expectedParams[5]
},
{
id : expectedParams[6]
other_id : expectedParams[7]
any_id : expectedParams[8]
}
]
console.log ''
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.multiCreate data, ->
describe 'when deleting', ->
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'DELETE FROM tableName WHERE id=?'
expectedParams = [
101
]
data =
id: 101
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.delete data, ->
describe 'when updating an order', ->
it 'deve receber um erro se o id for undefined', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update undefined, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o id for null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o id for zero', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update 0, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for vazio', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se acontecer algum erro ao efetuar um update', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.update 1,data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve retornar sucesso se não ocorreu nenhum erro', (done) ->
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
connector = new MySQLConnector params
expectedRow =
affected_rows: 1
connector._execute = (query, params, callback)->
callback null, expectedRow
connector.update '123', data, (err, row) ->
expect(err).not.to.be.ok()
expect(row).to.be.eql expectedRow
done()
it 'should pass the expected Query and Params', (done) ->
id = '12345678901234567890'
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
expectedQuery = 'UPDATE tableName SET issuer=?,payment_type=?,installments=? WHERE id=?'
expectedParams = [
data.issuer,
data.payment_type,
data.installments,
id
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.update id, data, ->
describe 'when updating by field an order', ->
it 'deve receber um erro se o field for undefined', (done) ->
expectedError = 'Invalid field'
connector = new MySQLConnector params
connector.updateByField undefined, null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field for null', (done) ->
expectedError = 'Invalid field'
connector = new MySQLConnector params
connector.updateByField null, null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for undefined', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', undefined, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for null', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for zero', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', 0, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for vazio', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
id = '12345678901234567890'
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
expectedQuery = 'UPDATE tableName SET issuer=?,payment_type=?,installments=? WHERE order_id=?'
expectedParams = [
data.issuer,
data.payment_type,
data.installments,
id
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.updateByField 'order_id', id, data, ->
it 'deve receber um erro se acontecer algum problema ao efetuar um update', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.updateByField 'order_id', 1, data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve retornar sucesso se não ocorreu nenhum erro', (done) ->
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
connector = new MySQLConnector params
expectedRow =
affected_rows: 1
connector._execute = (query, params, callback)->
callback null, expectedRow
connector.updateByField 'order_id', '123', data, (err, row) ->
expect(err).not.to.be.ok()
expect(row).to.be.eql expectedRow
done()
describe 'when executing a simple query without values', ->
it 'should validate _execute params', (done) ->
expectedQuery = "SELECT * FROM table1"
expectedParams = []
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.query expectedQuery, ->
it 'should return an error if was a executing query problem', (done) ->
expectedError = 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expectedError
connector.query "", (error, success) ->
expect(error).to.eql expectedError
expect(success).not.to.be.ok()
done()
it 'should return a query results if everything is ok', (done) ->
expectedResults = [
{id:1, name: '<NAME>'}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback null, expectedResults
connector.query "", (error, success) ->
expect(error).not.to.be.ok()
expect(success).to.eql expectedResults
done()
it 'should return a empty callback if no results found', (done) ->
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback()
connector.query "", (error, success) ->
expect(error).not.to.be.ok()
expect(success).not.to.be.ok()
done()
describe 'when executing a query', ->
it 'should return an error if was a get connection problem', (done) ->
expectedError = 'Database connection failed. Error: my error'
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback 'my error'
instance = new MySQLConnector params, deps
instance._execute '', [], (error, response)->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if was a selecting database', (done) ->
expectedError = 'Error selecting database'
mockedConnection =
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback expectedError
instance._execute '', [], (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error after selecting database', (done) ->
expectedError = 'Internal Error'
mockedConnection =
query: (query, params, callback) ->
callback expectedError
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback()
instance._execute '', [], (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return a expected result if everything was ok', (done) ->
expectedResponse =
affected_rows: 1
mockedConnection =
query: (query, params, callback) ->
callback null, expectedResponse
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback()
instance._execute '', [], (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedResponse
done()
describe 'when selecting a database', ->
it 'should pass the expected Query', (done) ->
databaseName = 's2Pay'
expectedQuery = "USE #{databaseName}"
mockedConnection =
query: (query, values, callback) ->
expect(query).to.eql expectedQuery
expect(values).to.eql []
done()
instance = new MySQLConnector params
instance._selectDatabase databaseName, mockedConnection, ->
describe 'when changing a tableName', ->
it 'deve validar se o nome da tabela foi alterada corretamente', ->
connector = new MySQLConnector params
connector.changeTable 'secondTableName'
expect(connector.table).to.eql 'secondTableName'
describe 'when reading a order with join', ->
mysqlParams = null
joinParams = null
beforeEach ->
mysqlParams =
host: 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: '<PASSWORD>'
domain: 'databaseName'
resource: 'table1'
joinParams =
table: 'table2'
condition: 'table1.id = table2.table1_id'
fields: ['field1','field2']
it 'should return an error if the order id is null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector mysqlParams
connector.readJoin null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join table is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.table
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join condition is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.condition
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join fields is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.fields
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error when executing a query', (done) ->
expectedError = 'Internal error'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback expectedError
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return a row if was found', (done) ->
expectedResponse =
id: '123456789'
something: 'something'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback null, expectedResponse
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedResponse
done()
it 'should return an error if the result was not found', (done) ->
expectedError = 'NOT_FOUND'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback()
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should validate a final query with all params possibilities', (done) ->
expectedQuery = "SELECT field1,field2 FROM table1 JOIN table2 ON table1.id = table2.table1_id WHERE table1.id = ? ORDER BY orderField DESC LIMIT 15"
expectedParams = [123456789]
joinParams.orderBy = 'orderField DESC'
joinParams.limit = 15
inputMessage =
data:
id: 123456789
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.readJoin inputMessage, joinParams, ->
describe 'when start a transaction in connection', ->
it 'should call execute start transaction command', (done) ->
expected =
query: 'START TRANSACTION'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.start_transaction ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.start_transaction (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a commit transaction in connection', ->
it 'should call execute commit command', (done) ->
expected =
query: 'COMMIT'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.commit ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.commit (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a rollback transaction in connection', ->
it 'should call execute ->rollback command', (done) ->
expected =
query: 'ROLLBACK'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.rollback ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.rollback (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a call procedure', ->
it 'should call procedure method', (done) ->
expectedError = 'Internal Error'
connector= new MySQLConnector params
connector._execute = (query, params, callback) ->
done()
connector.callProcedure 'baixa_pedido', [], ->
it 'should return an error message if the procedure execution failed', (done) ->
expectedError = 'Internal error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expectedError
connector.callProcedure 'baixa_pedido', [], (error, success)->
expect(error).to.eql expectedError
expect(success).not.to.be.ok()
done()
it 'should return a procedure result if everything is ok', (done) ->
expectedMessage = 'ok'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback null, expectedMessage
connector.callProcedure 'baixa_pedido', [], (error, success) ->
expect(error).not.to.be.ok()
expect(success).to.eql expectedMessage
done() | true | 'use strict'
expect = require 'expect.js'
describe 'the MySQLConnector,', ->
MySQLConnector = null
params = null
connector = null
beforeEach ->
delete require.cache[require.resolve('../src/MySQL')]
MySQLConnector = require '../src/MySQL'
params =
host : 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
domain: 'databaseName'
resource: 'tableName'
describe 'when creating a new instance', ->
it 'should throw an exception if one or more params was not passed', ->
expect(->
instance = new MySQLConnector {}
instance.init {}
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host empty object', ->
expect(->
params.host = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is null', ->
expect(->
params.host = null
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is undefined', ->
expect(->
params.host = undefined
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is zero', ->
expect(->
params.host = 0
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if host is empty string', ->
expect(->
params.host = ''
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if domain is not useful', ->
expect(->
params.domain = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if resource is not useful', ->
expect(->
params.resource = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if user is not useful', ->
expect(->
params.user = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should throw an exception if poolSize is not useful', ->
expect(->
params.poolSize = {}
instance = new MySQLConnector
).to.throwError((e) ->
expect(e.type).to.be 'Fatal'
expect(e.name).to.be 'Invalid argument'
expect(e.message).to.be.ok()
)
it 'should verify if the connection pool was created', ->
createPoolCalled = false
params =
host : 'host'
port : 1111
poolSize : 1
timeout : 10000
user: 'user'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
domain: 'databaseName'
resource: 'tableName'
expectedParams =
host: params.host
port: params.port
database: params.domain
user: params.user
password: PI:PASSWORD:<PASSWORD>END_PI
connectionLimit: params.poolSize
acquireTimeout: params.timeout
waitForConnections: 0
deps =
mysql:
createPool: (params) ->
expect(params).to.eql expectedParams
createPoolCalled = true
instance = new MySQLConnector params, deps
expect(instance).to.be.ok()
expect(instance.pool).to.be.ok()
expect(createPoolCalled).to.be.ok()
it 'should verify if the connection pool was created with default port', ->
createPoolCalled = false
params =
host : 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
domain: 'databaseName'
resource: 'tableName'
expectedParams =
host: params.host
port: 3306
database: params.domain
user: params.user
password: PI:PASSWORD:<PASSWORD>END_PI
connectionLimit: params.poolSize
acquireTimeout: params.timeout
waitForConnections: 0
deps =
mysql:
createPool: (params) ->
expect(params).to.eql expectedParams
createPoolCalled = true
instance = new MySQLConnector params, deps
expect(instance).to.be.ok()
expect(instance.pool).to.be.ok()
expect(createPoolCalled).to.be.ok()
describe 'when reading a specific record', ->
it 'should return an error if the order id is null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order id is undefined', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order id is zero', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.readById 0, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the executing query went wrong', (done) ->
expectedError = 'Internal Error'
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback expectedError
instance.readById 1, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found row', (done) ->
expectedRow =
reference: 1
amount: 100
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback null, expectedRow
instance.readById 1, (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedRow
done()
it 'should return a NOT_FOUND error if nothing was found', (done) ->
expectedError =
name: 'Not found'
message: ''
type: 'Error'
instance = new MySQLConnector params
instance._execute = (query, params, callback) ->
callback()
instance.readById 1, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
describe 'when reading an order', ->
it 'should hand the mysql error to the callback', (done) ->
expectedError = 'Value too large for defined data type'
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback expectedError
instance.read 'SELECT size FROM yo_mama', (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the order found', (done) ->
expectedOrder =
this: 'is'
your: 'order'
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback null, expectedOrder
instance.read 'SELECT weight_reduction FROM yo_mama', (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedOrder
done()
it 'should return a NOT FOUND error if nothing was found (obviously)', (done) ->
instance = new MySQLConnector params
instance._execute = (query, params, callback)->
callback()
instance.read 'SELECT weight_reduction FROM yo_mama', (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
describe 'when creating an order', ->
it 'should return an error if the order data is null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is Empty object', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.create {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the query error if it happens', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.create data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found rows affected', (done) ->
data =
id : 101
reference: 321321
issuer: 'visa'
auth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
description: 'Teste recarga'
return_url: 'www.google.com'
amount : 201
payment_type: 'credito_a_vista'
installments: 1
tid: '231345644'
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback()
connector.create data, (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'INSERT INTO tableName SET '
expectedQuery += 'id=?,reference=?,issuer=?,auth_token=?,description=?,return_url=?,amount=?,payment_type=?,installments=?,tid=?'
expectedParams = [
101,
321321,
'visa',
'tokenPI:PASSWORD:<PASSWORD>END_PI',
'Teste recarga',
'www.google.com',
201,
'credito_a_vista',
1,
'231345644'
]
data =
id: 101
reference: 321321
issuer: 'visa'
auth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
description: 'Teste recarga'
return_url: 'www.google.com'
amount: 201
payment_type: 'credito_a_vista'
installments: 1
tid: '231345644'
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.create data, ->
describe 'when creating an multiple orders', ->
it 'should return an error if the order data is null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the order data is Empty object', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.multiCreate {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the query error if it happens', (done) ->
expectedError = 'Error Query'
data = [
{
id: 1
other_id: 2
any_id: 99
}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.multiCreate data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return the found rows affected', (done) ->
data = [
{
id: 1
other_id: 2
any_id: 99
}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback()
connector.multiCreate data, (error, response) ->
expect(error).not.to.be.ok()
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'INSERT INTO tableName (id,other_id,any_id) VALUES (?,?,?),(?,?,?),(?,?,?)'
expectedParams = [10,20,30,15,25,35,25,35,45]
data = [
{
id : expectedParams[0]
other_id : expectedParams[1]
any_id : expectedParams[2]
},
{
id : expectedParams[3]
other_id : expectedParams[4]
any_id : expectedParams[5]
},
{
id : expectedParams[6]
other_id : expectedParams[7]
any_id : expectedParams[8]
}
]
console.log ''
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.multiCreate data, ->
describe 'when deleting', ->
it 'should pass the expected Query and Params', (done) ->
expectedQuery = 'DELETE FROM tableName WHERE id=?'
expectedParams = [
101
]
data =
id: 101
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.delete data, ->
describe 'when updating an order', ->
it 'deve receber um erro se o id for undefined', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update undefined, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o id for null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o id for zero', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector params
connector.update 0, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for vazio', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.update '1', {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se acontecer algum erro ao efetuar um update', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.update 1,data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve retornar sucesso se não ocorreu nenhum erro', (done) ->
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
connector = new MySQLConnector params
expectedRow =
affected_rows: 1
connector._execute = (query, params, callback)->
callback null, expectedRow
connector.update '123', data, (err, row) ->
expect(err).not.to.be.ok()
expect(row).to.be.eql expectedRow
done()
it 'should pass the expected Query and Params', (done) ->
id = '12345678901234567890'
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
expectedQuery = 'UPDATE tableName SET issuer=?,payment_type=?,installments=? WHERE id=?'
expectedParams = [
data.issuer,
data.payment_type,
data.installments,
id
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.update id, data, ->
describe 'when updating by field an order', ->
it 'deve receber um erro se o field for undefined', (done) ->
expectedError = 'Invalid field'
connector = new MySQLConnector params
connector.updateByField undefined, null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field for null', (done) ->
expectedError = 'Invalid field'
connector = new MySQLConnector params
connector.updateByField null, null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for undefined', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', undefined, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for null', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o field_value for zero', (done) ->
expectedError = 'Invalid field_value'
connector = new MySQLConnector params
connector.updateByField 'order_id', 0, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for undefined', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, undefined, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for null', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve receber um erro se o data for vazio', (done) ->
expectedError = 'Invalid data'
connector = new MySQLConnector params
connector.updateByField '1', 1, {}, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should pass the expected Query and Params', (done) ->
id = '12345678901234567890'
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
expectedQuery = 'UPDATE tableName SET issuer=?,payment_type=?,installments=? WHERE order_id=?'
expectedParams = [
data.issuer,
data.payment_type,
data.installments,
id
]
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.updateByField 'order_id', id, data, ->
it 'deve receber um erro se acontecer algum problema ao efetuar um update', (done) ->
expectedError = 'Error Query'
data =
id:1
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
callback expectedError
connector.updateByField 'order_id', 1, data, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'deve retornar sucesso se não ocorreu nenhum erro', (done) ->
data =
issuer: "visa"
payment_type: "credito_a_vista"
installments: 1
connector = new MySQLConnector params
expectedRow =
affected_rows: 1
connector._execute = (query, params, callback)->
callback null, expectedRow
connector.updateByField 'order_id', '123', data, (err, row) ->
expect(err).not.to.be.ok()
expect(row).to.be.eql expectedRow
done()
describe 'when executing a simple query without values', ->
it 'should validate _execute params', (done) ->
expectedQuery = "SELECT * FROM table1"
expectedParams = []
connector = new MySQLConnector params
connector._execute = (query, params, callback)->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.query expectedQuery, ->
it 'should return an error if was a executing query problem', (done) ->
expectedError = 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expectedError
connector.query "", (error, success) ->
expect(error).to.eql expectedError
expect(success).not.to.be.ok()
done()
it 'should return a query results if everything is ok', (done) ->
expectedResults = [
{id:1, name: 'PI:NAME:<NAME>END_PI'}
]
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback null, expectedResults
connector.query "", (error, success) ->
expect(error).not.to.be.ok()
expect(success).to.eql expectedResults
done()
it 'should return a empty callback if no results found', (done) ->
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback()
connector.query "", (error, success) ->
expect(error).not.to.be.ok()
expect(success).not.to.be.ok()
done()
describe 'when executing a query', ->
it 'should return an error if was a get connection problem', (done) ->
expectedError = 'Database connection failed. Error: my error'
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback 'my error'
instance = new MySQLConnector params, deps
instance._execute '', [], (error, response)->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if was a selecting database', (done) ->
expectedError = 'Error selecting database'
mockedConnection =
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback expectedError
instance._execute '', [], (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error after selecting database', (done) ->
expectedError = 'Internal Error'
mockedConnection =
query: (query, params, callback) ->
callback expectedError
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback()
instance._execute '', [], (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return a expected result if everything was ok', (done) ->
expectedResponse =
affected_rows: 1
mockedConnection =
query: (query, params, callback) ->
callback null, expectedResponse
release: ->
deps =
mysql:
createPool: (params) ->
getConnection: (callback) ->
callback null, mockedConnection
instance = new MySQLConnector params, deps
instance._selectDatabase = (databaseName, connection, callback) ->
callback()
instance._execute '', [], (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedResponse
done()
describe 'when selecting a database', ->
it 'should pass the expected Query', (done) ->
databaseName = 's2Pay'
expectedQuery = "USE #{databaseName}"
mockedConnection =
query: (query, values, callback) ->
expect(query).to.eql expectedQuery
expect(values).to.eql []
done()
instance = new MySQLConnector params
instance._selectDatabase databaseName, mockedConnection, ->
describe 'when changing a tableName', ->
it 'deve validar se o nome da tabela foi alterada corretamente', ->
connector = new MySQLConnector params
connector.changeTable 'secondTableName'
expect(connector.table).to.eql 'secondTableName'
describe 'when reading a order with join', ->
mysqlParams = null
joinParams = null
beforeEach ->
mysqlParams =
host: 'host'
poolSize : 1
timeout : 10000
user: 'user'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
domain: 'databaseName'
resource: 'table1'
joinParams =
table: 'table2'
condition: 'table1.id = table2.table1_id'
fields: ['field1','field2']
it 'should return an error if the order id is null', (done) ->
expectedError = 'Invalid id'
connector = new MySQLConnector mysqlParams
connector.readJoin null, null, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join table is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.table
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join condition is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.condition
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error if the join fields is null', (done) ->
expectedError = 'Invalid join parameters'
delete joinParams.fields
connector = new MySQLConnector mysqlParams
connector.readJoin '123465789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return an error when executing a query', (done) ->
expectedError = 'Internal error'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback expectedError
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should return a row if was found', (done) ->
expectedResponse =
id: '123456789'
something: 'something'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback null, expectedResponse
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).not.to.be.ok()
expect(response).to.eql expectedResponse
done()
it 'should return an error if the result was not found', (done) ->
expectedError = 'NOT_FOUND'
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
callback()
connector.readJoin '123456789', joinParams, (error, response) ->
expect(error).to.eql expectedError
expect(response).not.to.be.ok()
done()
it 'should validate a final query with all params possibilities', (done) ->
expectedQuery = "SELECT field1,field2 FROM table1 JOIN table2 ON table1.id = table2.table1_id WHERE table1.id = ? ORDER BY orderField DESC LIMIT 15"
expectedParams = [123456789]
joinParams.orderBy = 'orderField DESC'
joinParams.limit = 15
inputMessage =
data:
id: 123456789
connector = new MySQLConnector mysqlParams
connector._execute = (query, params, callback) ->
expect(query).to.eql expectedQuery
expect(params).to.eql expectedParams
done()
connector.readJoin inputMessage, joinParams, ->
describe 'when start a transaction in connection', ->
it 'should call execute start transaction command', (done) ->
expected =
query: 'START TRANSACTION'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.start_transaction ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.start_transaction (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a commit transaction in connection', ->
it 'should call execute commit command', (done) ->
expected =
query: 'COMMIT'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.commit ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.commit (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a rollback transaction in connection', ->
it 'should call execute ->rollback command', (done) ->
expected =
query: 'ROLLBACK'
params: []
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
expect(query).to.eql expected.query
expect(params).to.eql expected.params
done()
connector.rollback ->
it 'should return an error message if the database is out', (done) ->
expected =
errorMessage: 'Internal Error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expected
connector.rollback (error, success) ->
expect(error).to.eql expected
expect(success).not.to.be.ok()
done()
describe 'when a call procedure', ->
it 'should call procedure method', (done) ->
expectedError = 'Internal Error'
connector= new MySQLConnector params
connector._execute = (query, params, callback) ->
done()
connector.callProcedure 'baixa_pedido', [], ->
it 'should return an error message if the procedure execution failed', (done) ->
expectedError = 'Internal error'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback expectedError
connector.callProcedure 'baixa_pedido', [], (error, success)->
expect(error).to.eql expectedError
expect(success).not.to.be.ok()
done()
it 'should return a procedure result if everything is ok', (done) ->
expectedMessage = 'ok'
connector = new MySQLConnector params
connector._execute = (query, params, callback) ->
callback null, expectedMessage
connector.callProcedure 'baixa_pedido', [], (error, success) ->
expect(error).not.to.be.ok()
expect(success).to.eql expectedMessage
done() |
[
{
"context": "tial bootstraping task\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\n\n#\n# The actual bootstrapping\n#\n# @param {Strin",
"end": 79,
"score": 0.9998916387557983,
"start": 62,
"tag": "NAME",
"value": "Nikolay Nemshilov"
},
{
"context": "'\n lovelyrc.port = '300... | cli/commands/bootstrap.coffee | lovely-io/lovely.io-stl | 2 | #
# The initial bootstraping task
#
# Copyright (C) 2011-2012 Nikolay Nemshilov
#
#
# The actual bootstrapping
#
# @param {String} optional base_dir
# @return void
#
bootstrap = (base_dir) ->
fs = require('fs')
lovelyrc = require('../lovelyrc')
home_dir = process.env.HOME
base_dir or= "#{home_dir}/.lovely/"
print "Making the base at: #{base_dir}"
if fs.existsSync(base_dir)
print " » " + "Already exists".yellow
else
fs.mkdirSync(base_dir, 0o0755)
print "Initial RC file at: ~/.lovelyrc"
if fs.existsSync("#{home_dir}/.lovelyrc")
print " » " + "Already exists".yellow
else
lovelyrc.base = base_dir
lovelyrc.host = 'http://lovely.io'
lovelyrc.port = '3000'
lovelyrc.name = 'Vasily Pupkin'
lovelyrc.lang = 'coffee,sass'
print "Copying shared server content"
if fs.existsSync("#{base_dir}/server")
print " » " + "Already exists".yellow
else
system "cp -r #{__dirname + "/../server"} #{base_dir}"
print "Installing STL packages"
stl_dir = "#{__dirname}/../../stl/"
for name in fs.readdirSync(stl_dir)
system("cd #{stl_dir + name}; #{__dirname}/../../bin/lovely install")
print "» " + "Done".green
#
# Initializes the task
#
# @param {Array} arguments
# @return void
#
exports.init = (args) ->
bootstrap(args[0])
# lovely help bootstrap response
exports.help = (args) ->
"""
Bootstraps the LovelyIO infrastructure
Usage:
lovely bootstrap
""" | 42324 | #
# The initial bootstraping task
#
# Copyright (C) 2011-2012 <NAME>
#
#
# The actual bootstrapping
#
# @param {String} optional base_dir
# @return void
#
bootstrap = (base_dir) ->
fs = require('fs')
lovelyrc = require('../lovelyrc')
home_dir = process.env.HOME
base_dir or= "#{home_dir}/.lovely/"
print "Making the base at: #{base_dir}"
if fs.existsSync(base_dir)
print " » " + "Already exists".yellow
else
fs.mkdirSync(base_dir, 0o0755)
print "Initial RC file at: ~/.lovelyrc"
if fs.existsSync("#{home_dir}/.lovelyrc")
print " » " + "Already exists".yellow
else
lovelyrc.base = base_dir
lovelyrc.host = 'http://lovely.io'
lovelyrc.port = '3000'
lovelyrc.name = '<NAME>'
lovelyrc.lang = 'coffee,sass'
print "Copying shared server content"
if fs.existsSync("#{base_dir}/server")
print " » " + "Already exists".yellow
else
system "cp -r #{__dirname + "/../server"} #{base_dir}"
print "Installing STL packages"
stl_dir = "#{__dirname}/../../stl/"
for name in fs.readdirSync(stl_dir)
system("cd #{stl_dir + name}; #{__dirname}/../../bin/lovely install")
print "» " + "Done".green
#
# Initializes the task
#
# @param {Array} arguments
# @return void
#
exports.init = (args) ->
bootstrap(args[0])
# lovely help bootstrap response
exports.help = (args) ->
"""
Bootstraps the LovelyIO infrastructure
Usage:
lovely bootstrap
""" | true | #
# The initial bootstraping task
#
# Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI
#
#
# The actual bootstrapping
#
# @param {String} optional base_dir
# @return void
#
bootstrap = (base_dir) ->
fs = require('fs')
lovelyrc = require('../lovelyrc')
home_dir = process.env.HOME
base_dir or= "#{home_dir}/.lovely/"
print "Making the base at: #{base_dir}"
if fs.existsSync(base_dir)
print " » " + "Already exists".yellow
else
fs.mkdirSync(base_dir, 0o0755)
print "Initial RC file at: ~/.lovelyrc"
if fs.existsSync("#{home_dir}/.lovelyrc")
print " » " + "Already exists".yellow
else
lovelyrc.base = base_dir
lovelyrc.host = 'http://lovely.io'
lovelyrc.port = '3000'
lovelyrc.name = 'PI:NAME:<NAME>END_PI'
lovelyrc.lang = 'coffee,sass'
print "Copying shared server content"
if fs.existsSync("#{base_dir}/server")
print " » " + "Already exists".yellow
else
system "cp -r #{__dirname + "/../server"} #{base_dir}"
print "Installing STL packages"
stl_dir = "#{__dirname}/../../stl/"
for name in fs.readdirSync(stl_dir)
system("cd #{stl_dir + name}; #{__dirname}/../../bin/lovely install")
print "» " + "Done".green
#
# Initializes the task
#
# @param {Array} arguments
# @return void
#
exports.init = (args) ->
bootstrap(args[0])
# lovely help bootstrap response
exports.help = (args) ->
"""
Bootstraps the LovelyIO infrastructure
Usage:
lovely bootstrap
""" |
[
{
"context": "0\n\n Collapsible paper cards.\n\n Made with love by bbo - ©2015 Alexander Rühle\n MIT License http://open",
"end": 81,
"score": 0.952896773815155,
"start": 78,
"tag": "USERNAME",
"value": "bbo"
},
{
"context": "ible paper cards.\n\n Made with love by bbo - ©2015 Al... | js/paper-collapse.coffee | mobeale/TS-candidates | 2 | ###!
Paper Collapse v0.4.0
Collapsible paper cards.
Made with love by bbo - ©2015 Alexander Rühle
MIT License http://opensource.org/licenses/MIT
###
(($) ->
'use strict'
$.fn.paperCollapse = (options) ->
settings = $.extend({}, $.fn.paperCollapse.defaults, options)
$(this).find('.collapse-card__heading').add(settings.closeHandler).click ->
if $(this).closest('.collapse-card').hasClass('active')
settings.onHide.call this
$(this).closest('.collapse-card').removeClass 'active'
$(this).closest('.collapse-card').find('.collapse-card__body').slideUp settings.animationDuration, settings.onHideComplete
else
settings.onShow.call this
$(this).closest('.collapse-card').addClass 'active'
$(this).closest('.collapse-card').find('.collapse-card__body').slideDown settings.animationDuration, settings.onShowComplete
return
this
$.fn.paperCollapse.defaults =
animationDuration: 400
easing: 'swing'
closeHandler: '.collapse-card__close_handler'
onShow: ->
onHide: ->
onShowComplete: ->
onHideComplete: ->
return) jQuery | 55039 | ###!
Paper Collapse v0.4.0
Collapsible paper cards.
Made with love by bbo - ©2015 <NAME>
MIT License http://opensource.org/licenses/MIT
###
(($) ->
'use strict'
$.fn.paperCollapse = (options) ->
settings = $.extend({}, $.fn.paperCollapse.defaults, options)
$(this).find('.collapse-card__heading').add(settings.closeHandler).click ->
if $(this).closest('.collapse-card').hasClass('active')
settings.onHide.call this
$(this).closest('.collapse-card').removeClass 'active'
$(this).closest('.collapse-card').find('.collapse-card__body').slideUp settings.animationDuration, settings.onHideComplete
else
settings.onShow.call this
$(this).closest('.collapse-card').addClass 'active'
$(this).closest('.collapse-card').find('.collapse-card__body').slideDown settings.animationDuration, settings.onShowComplete
return
this
$.fn.paperCollapse.defaults =
animationDuration: 400
easing: 'swing'
closeHandler: '.collapse-card__close_handler'
onShow: ->
onHide: ->
onShowComplete: ->
onHideComplete: ->
return) jQuery | true | ###!
Paper Collapse v0.4.0
Collapsible paper cards.
Made with love by bbo - ©2015 PI:NAME:<NAME>END_PI
MIT License http://opensource.org/licenses/MIT
###
(($) ->
'use strict'
$.fn.paperCollapse = (options) ->
settings = $.extend({}, $.fn.paperCollapse.defaults, options)
$(this).find('.collapse-card__heading').add(settings.closeHandler).click ->
if $(this).closest('.collapse-card').hasClass('active')
settings.onHide.call this
$(this).closest('.collapse-card').removeClass 'active'
$(this).closest('.collapse-card').find('.collapse-card__body').slideUp settings.animationDuration, settings.onHideComplete
else
settings.onShow.call this
$(this).closest('.collapse-card').addClass 'active'
$(this).closest('.collapse-card').find('.collapse-card__body').slideDown settings.animationDuration, settings.onShowComplete
return
this
$.fn.paperCollapse.defaults =
animationDuration: 400
easing: 'swing'
closeHandler: '.collapse-card__close_handler'
onShow: ->
onHide: ->
onShowComplete: ->
onHideComplete: ->
return) jQuery |
[
{
"context": "e = Ember.Route.extend({\n model: ->\n [{name: \"abc\", age: 5}, {name: \"pqr\", age: 10}, {name: \"xyz\", ",
"end": 86,
"score": 0.9921630620956421,
"start": 83,
"tag": "NAME",
"value": "abc"
},
{
"context": "{\n model: ->\n [{name: \"abc\", age: 5}, {name: \"p... | tests/dummy/app/routes/home.coffee | vikas-gup/ember-cli-d3-charts | 0 | `import Ember from "ember"`
route = Ember.Route.extend({
model: ->
[{name: "abc", age: 5}, {name: "pqr", age: 10}, {name: "xyz", age: 15}]
setupController: (controller, model) ->
controller.set('model', model)
controller.set('color', ["red", "green"])
})
`export default route`
| 193038 | `import Ember from "ember"`
route = Ember.Route.extend({
model: ->
[{name: "<NAME>", age: 5}, {name: "<NAME>", age: 10}, {name: "<NAME>", age: 15}]
setupController: (controller, model) ->
controller.set('model', model)
controller.set('color', ["red", "green"])
})
`export default route`
| true | `import Ember from "ember"`
route = Ember.Route.extend({
model: ->
[{name: "PI:NAME:<NAME>END_PI", age: 5}, {name: "PI:NAME:<NAME>END_PI", age: 10}, {name: "PI:NAME:<NAME>END_PI", age: 15}]
setupController: (controller, model) ->
controller.set('model', model)
controller.set('color', ["red", "green"])
})
`export default route`
|
[
{
"context": " opponent1.teamId = team.id\n opponent1.name = \"Valiant Opponent\"\n teamsnap.saveOpponent opponent1, (err, resul",
"end": 201,
"score": 0.8914077877998352,
"start": 185,
"tag": "NAME",
"value": "Valiant Opponent"
},
{
"context": " opponent2.teamId = team.id\n ... | test/opponentResults.coffee | teamsnap/teamsnap-javascript-sdk | 9 | describe 'Opponent Results', ->
opponent1 = null
opponent2 = null
before (done) ->
opponent1 = teamsnap.createOpponent()
opponent1.teamId = team.id
opponent1.name = "Valiant Opponent"
teamsnap.saveOpponent opponent1, (err, result) ->
expect(err).to.be.null
done()
before (done) ->
opponent2 = teamsnap.createOpponent()
opponent2.teamId = team.id
opponent2.name = "A More Valiant Opponent"
teamsnap.saveOpponent opponent2, (err, result) ->
expect(err).to.be.null
done()
after (done) ->
teamsnap.deleteOpponent opponent1, (err, result) ->
expect(err).to.be.null
done()
after (done) ->
teamsnap.deleteOpponent opponent2, (err, result) ->
expect(err).to.be.null
done()
it 'should be able to load results for all team opponents', (done) ->
teamsnap.loadMe().then (me) ->
teamsnap.loadOpponentsResults teamId: team.id, (err, result) ->
expect(err).to.be.null
result.should.be.an('array')
result.should.have.length(2)
done()
it 'should be able to load results for single opponent', (done) ->
teamsnap.loadOpponentResults opponent1.id, (err, result) ->
expect(err).to.be.null
result.should.have.property('type', 'opponentResults')
done()
| 190529 | describe 'Opponent Results', ->
opponent1 = null
opponent2 = null
before (done) ->
opponent1 = teamsnap.createOpponent()
opponent1.teamId = team.id
opponent1.name = "<NAME>"
teamsnap.saveOpponent opponent1, (err, result) ->
expect(err).to.be.null
done()
before (done) ->
opponent2 = teamsnap.createOpponent()
opponent2.teamId = team.id
opponent2.name = "<NAME>"
teamsnap.saveOpponent opponent2, (err, result) ->
expect(err).to.be.null
done()
after (done) ->
teamsnap.deleteOpponent opponent1, (err, result) ->
expect(err).to.be.null
done()
after (done) ->
teamsnap.deleteOpponent opponent2, (err, result) ->
expect(err).to.be.null
done()
it 'should be able to load results for all team opponents', (done) ->
teamsnap.loadMe().then (me) ->
teamsnap.loadOpponentsResults teamId: team.id, (err, result) ->
expect(err).to.be.null
result.should.be.an('array')
result.should.have.length(2)
done()
it 'should be able to load results for single opponent', (done) ->
teamsnap.loadOpponentResults opponent1.id, (err, result) ->
expect(err).to.be.null
result.should.have.property('type', 'opponentResults')
done()
| true | describe 'Opponent Results', ->
opponent1 = null
opponent2 = null
before (done) ->
opponent1 = teamsnap.createOpponent()
opponent1.teamId = team.id
opponent1.name = "PI:NAME:<NAME>END_PI"
teamsnap.saveOpponent opponent1, (err, result) ->
expect(err).to.be.null
done()
before (done) ->
opponent2 = teamsnap.createOpponent()
opponent2.teamId = team.id
opponent2.name = "PI:NAME:<NAME>END_PI"
teamsnap.saveOpponent opponent2, (err, result) ->
expect(err).to.be.null
done()
after (done) ->
teamsnap.deleteOpponent opponent1, (err, result) ->
expect(err).to.be.null
done()
after (done) ->
teamsnap.deleteOpponent opponent2, (err, result) ->
expect(err).to.be.null
done()
it 'should be able to load results for all team opponents', (done) ->
teamsnap.loadMe().then (me) ->
teamsnap.loadOpponentsResults teamId: team.id, (err, result) ->
expect(err).to.be.null
result.should.be.an('array')
result.should.have.length(2)
done()
it 'should be able to load results for single opponent', (done) ->
teamsnap.loadOpponentResults opponent1.id, (err, result) ->
expect(err).to.be.null
result.should.have.property('type', 'opponentResults')
done()
|
[
{
"context": "g.port', 123)\n container.register('mockName', 'charles')\n\n port = container.get('config.port')\n ex",
"end": 281,
"score": 0.9247575402259827,
"start": 274,
"tag": "NAME",
"value": "charles"
},
{
"context": "ner.get('mockName')\n expect(port).to.be.equal ... | test/unit/dependencyResolverTest.coffee | deepdancer/deepdancer | 0 | {expect} = require 'chai'
Container = require 'deepdancer/Container'
container = new Container()
describe 'deepdancer/dependencyResolver', ->
it 'should lookup for value dependencies', ->
container.register('config.port', 123)
container.register('mockName', 'charles')
port = container.get('config.port')
expect(port).to.be.equal 123
port = container.get('mockName')
expect(port).to.be.equal 'charles'
it 'should lookup for factory dependencies', ->
appFactory = (port, extraObject, descriptionObject) ->
app =
description: 'A nice app'
port: port
extra: extraObject
descriptionObject: descriptionObject
app
container.register('descriptionObject', ( -> field1: 'value1'),
type: 'factory')
container.get('descriptionObject').field1 = 'something tweaked'
container.register('app', appFactory, {
type: 'factory',
dependencies: ['config.port', 'key1': 'value1', 'descriptionObject']
})
container.register('app-alias', 'app', type: 'alias')
app = container.get('app')
expect(app.description).to.be.equal 'A nice app'
expect(app.port).to.be.equal 123
expect(app.extra.key1).to.be.equal 'value1'
expect(app.descriptionObject.field1).to.be.equal 'something tweaked'
app.port = 122
app = container.get('app')
expect(app.port).to.be.equal 122
app.port = 122
app = container.get('app', 'call')
expect(app.port).to.be.equal 123
expect(app.descriptionObject.field1).to.be.equal 'value1'
app = container.get('app', 'call', {'config.port': 42})
expect(app.port).to.be.equal 42
it 'should lookup for class dependencies', ->
mockInstanceCount = 0
class MockClass
constructor: (@name) ->
mockInstanceCount += 1
@flickCount = 0
getName: =>
'Mock ' + @name
flick: (increment = 1) =>
@flickCount += increment
setupCall1 =
method: 'flick'
args: []
setupCall2 =
method: 'flick'
args: [3]
setupCalls = [setupCall1, setupCall2]
container.register('mock', MockClass, {
type: 'class',
lifespan: 'call',
dependencies: ['mockName'],
setupCalls: setupCalls
})
retrievedMock = container.get('mock')
retrievedMock.flickCount += 1
expect(retrievedMock.flickCount).to.be.equal 5
retrievedMock = container.get('mock')
expect(retrievedMock.flickCount).to.be.equal 4
expect(retrievedMock.getName()).to.be.equal 'Mock charles'
it 'should lookup for alias dependencies', ->
container.register('christmas', tree: true)
container.register('forest', 'christmas', type: 'alias')
expect(container.get('forest').tree).to.be.true
container.get('christmas').tree = false
expect(container.get('forest').tree).to.be.false
container.get('forest').tree = true
expect(container.get('forest').tree).to.be.true
it 'should lookup in the normal modules if needed', ->
dictEmitter = (someThing) ->
myDict =
myThing: someThing
myDict
container.register('dict', dictEmitter, {
type: 'factory'
dependencies: ['chai']
})
dict = container.get('dict')
expect(dict.myThing).to.include.property('expect')
expect(dict.myThing).to.not.include.property('zorro')
testDescription = 'should properly load setup type, lifespan, calls and '+
'dependencies from the values'
it testDescription, ->
container.register('config.port', 123)
class TestClass
@__dependencies: [12]
@__type = 'class'
@__lifespan = 'call'
constructor: (@someValue) ->
@port = undefined
setPort: (port) =>
@port = port
TestClass.__setupCalls = [{method: 'setPort', args: ['config.port']}]
container.register('testObject', TestClass)
testObject = container.get('testObject')
expect(testObject.port).to.be.equal 123
expect(testObject.someValue).to.be.equal 12 | 166985 | {expect} = require 'chai'
Container = require 'deepdancer/Container'
container = new Container()
describe 'deepdancer/dependencyResolver', ->
it 'should lookup for value dependencies', ->
container.register('config.port', 123)
container.register('mockName', '<NAME>')
port = container.get('config.port')
expect(port).to.be.equal 123
port = container.get('mockName')
expect(port).to.be.equal '<NAME>'
it 'should lookup for factory dependencies', ->
appFactory = (port, extraObject, descriptionObject) ->
app =
description: 'A nice app'
port: port
extra: extraObject
descriptionObject: descriptionObject
app
container.register('descriptionObject', ( -> field1: 'value1'),
type: 'factory')
container.get('descriptionObject').field1 = 'something tweaked'
container.register('app', appFactory, {
type: 'factory',
dependencies: ['config.port', 'key1': 'value1', 'descriptionObject']
})
container.register('app-alias', 'app', type: 'alias')
app = container.get('app')
expect(app.description).to.be.equal 'A nice app'
expect(app.port).to.be.equal 123
expect(app.extra.key1).to.be.equal 'value1'
expect(app.descriptionObject.field1).to.be.equal 'something tweaked'
app.port = 122
app = container.get('app')
expect(app.port).to.be.equal 122
app.port = 122
app = container.get('app', 'call')
expect(app.port).to.be.equal 123
expect(app.descriptionObject.field1).to.be.equal 'value1'
app = container.get('app', 'call', {'config.port': 42})
expect(app.port).to.be.equal 42
it 'should lookup for class dependencies', ->
mockInstanceCount = 0
class MockClass
constructor: (@name) ->
mockInstanceCount += 1
@flickCount = 0
getName: =>
'Mock ' + @name
flick: (increment = 1) =>
@flickCount += increment
setupCall1 =
method: 'flick'
args: []
setupCall2 =
method: 'flick'
args: [3]
setupCalls = [setupCall1, setupCall2]
container.register('mock', MockClass, {
type: 'class',
lifespan: 'call',
dependencies: ['mockName'],
setupCalls: setupCalls
})
retrievedMock = container.get('mock')
retrievedMock.flickCount += 1
expect(retrievedMock.flickCount).to.be.equal 5
retrievedMock = container.get('mock')
expect(retrievedMock.flickCount).to.be.equal 4
expect(retrievedMock.getName()).to.be.equal 'Mock charles'
it 'should lookup for alias dependencies', ->
container.register('christmas', tree: true)
container.register('forest', 'christmas', type: 'alias')
expect(container.get('forest').tree).to.be.true
container.get('christmas').tree = false
expect(container.get('forest').tree).to.be.false
container.get('forest').tree = true
expect(container.get('forest').tree).to.be.true
it 'should lookup in the normal modules if needed', ->
dictEmitter = (someThing) ->
myDict =
myThing: someThing
myDict
container.register('dict', dictEmitter, {
type: 'factory'
dependencies: ['chai']
})
dict = container.get('dict')
expect(dict.myThing).to.include.property('expect')
expect(dict.myThing).to.not.include.property('zorro')
testDescription = 'should properly load setup type, lifespan, calls and '+
'dependencies from the values'
it testDescription, ->
container.register('config.port', 123)
class TestClass
@__dependencies: [12]
@__type = 'class'
@__lifespan = 'call'
constructor: (@someValue) ->
@port = undefined
setPort: (port) =>
@port = port
TestClass.__setupCalls = [{method: 'setPort', args: ['config.port']}]
container.register('testObject', TestClass)
testObject = container.get('testObject')
expect(testObject.port).to.be.equal 123
expect(testObject.someValue).to.be.equal 12 | true | {expect} = require 'chai'
Container = require 'deepdancer/Container'
container = new Container()
describe 'deepdancer/dependencyResolver', ->
it 'should lookup for value dependencies', ->
container.register('config.port', 123)
container.register('mockName', 'PI:NAME:<NAME>END_PI')
port = container.get('config.port')
expect(port).to.be.equal 123
port = container.get('mockName')
expect(port).to.be.equal 'PI:NAME:<NAME>END_PI'
it 'should lookup for factory dependencies', ->
appFactory = (port, extraObject, descriptionObject) ->
app =
description: 'A nice app'
port: port
extra: extraObject
descriptionObject: descriptionObject
app
container.register('descriptionObject', ( -> field1: 'value1'),
type: 'factory')
container.get('descriptionObject').field1 = 'something tweaked'
container.register('app', appFactory, {
type: 'factory',
dependencies: ['config.port', 'key1': 'value1', 'descriptionObject']
})
container.register('app-alias', 'app', type: 'alias')
app = container.get('app')
expect(app.description).to.be.equal 'A nice app'
expect(app.port).to.be.equal 123
expect(app.extra.key1).to.be.equal 'value1'
expect(app.descriptionObject.field1).to.be.equal 'something tweaked'
app.port = 122
app = container.get('app')
expect(app.port).to.be.equal 122
app.port = 122
app = container.get('app', 'call')
expect(app.port).to.be.equal 123
expect(app.descriptionObject.field1).to.be.equal 'value1'
app = container.get('app', 'call', {'config.port': 42})
expect(app.port).to.be.equal 42
it 'should lookup for class dependencies', ->
mockInstanceCount = 0
class MockClass
constructor: (@name) ->
mockInstanceCount += 1
@flickCount = 0
getName: =>
'Mock ' + @name
flick: (increment = 1) =>
@flickCount += increment
setupCall1 =
method: 'flick'
args: []
setupCall2 =
method: 'flick'
args: [3]
setupCalls = [setupCall1, setupCall2]
container.register('mock', MockClass, {
type: 'class',
lifespan: 'call',
dependencies: ['mockName'],
setupCalls: setupCalls
})
retrievedMock = container.get('mock')
retrievedMock.flickCount += 1
expect(retrievedMock.flickCount).to.be.equal 5
retrievedMock = container.get('mock')
expect(retrievedMock.flickCount).to.be.equal 4
expect(retrievedMock.getName()).to.be.equal 'Mock charles'
it 'should lookup for alias dependencies', ->
container.register('christmas', tree: true)
container.register('forest', 'christmas', type: 'alias')
expect(container.get('forest').tree).to.be.true
container.get('christmas').tree = false
expect(container.get('forest').tree).to.be.false
container.get('forest').tree = true
expect(container.get('forest').tree).to.be.true
it 'should lookup in the normal modules if needed', ->
dictEmitter = (someThing) ->
myDict =
myThing: someThing
myDict
container.register('dict', dictEmitter, {
type: 'factory'
dependencies: ['chai']
})
dict = container.get('dict')
expect(dict.myThing).to.include.property('expect')
expect(dict.myThing).to.not.include.property('zorro')
testDescription = 'should properly load setup type, lifespan, calls and '+
'dependencies from the values'
it testDescription, ->
container.register('config.port', 123)
class TestClass
@__dependencies: [12]
@__type = 'class'
@__lifespan = 'call'
constructor: (@someValue) ->
@port = undefined
setPort: (port) =>
@port = port
TestClass.__setupCalls = [{method: 'setPort', args: ['config.port']}]
container.register('testObject', TestClass)
testObject = container.get('testObject')
expect(testObject.port).to.be.equal 123
expect(testObject.someValue).to.be.equal 12 |
[
{
"context": "itter client for the led ticker deamon\n# Author: \tManuel Stofer\n#\n\nnet \t= require 'net'\nutil = require 'uti",
"end": 69,
"score": 0.9998806715011597,
"start": 56,
"tag": "NAME",
"value": "Manuel Stofer"
}
] | clients/twitter/twitter.coffee | manuelstofer/led-ticker | 4 | #
# Twitter client for the led ticker deamon
# Author: Manuel Stofer
#
net = require 'net'
util = require 'util'
twitter = require 'twitter'
fs = require 'fs'
configFile = process.env.HOME + '/.ledticker/twitter.json'
try
settings = JSON.parse fs.readFileSync(configFile)
catch err
console.log 'could not load config file: ' + configFile
console.log err
process.exit()
#
# the screen_name and message are displayed
formatTweet = (tweet)-> '@' + tweet.user.screen_name + ': ' + tweet.text + '\r\n'
#
# checks if a tweet is valid
isValidTweet = (tweet)-> tweet? and tweet.text? and tweet.user? and tweet.user.screen_name?
#
# connect to twitter stream
connectToTwitterStream = (callback)->
twit = new twitter(settings.api)
console.log 'tracking: ' + settings.track
twit.stream 'user', {track: settings.track}, (stream)-> callback stream
#
# connect to led ticker daemon
connectToLedTicker = (callback)->
client = net.connect settings.daemon.port, settings.daemon.host, (err)-> callback client, err
#
# connects to the led ticker deamon and to the twitter stream
connectToLedTicker (ticker)-> connectToTwitterStream (stream)->
# add an event listener for new tweets
stream.on 'data', (tweet) -> ticker.write formatTweet(tweet) if isValidTweet tweet
| 61227 | #
# Twitter client for the led ticker deamon
# Author: <NAME>
#
net = require 'net'
util = require 'util'
twitter = require 'twitter'
fs = require 'fs'
configFile = process.env.HOME + '/.ledticker/twitter.json'
try
settings = JSON.parse fs.readFileSync(configFile)
catch err
console.log 'could not load config file: ' + configFile
console.log err
process.exit()
#
# the screen_name and message are displayed
formatTweet = (tweet)-> '@' + tweet.user.screen_name + ': ' + tweet.text + '\r\n'
#
# checks if a tweet is valid
isValidTweet = (tweet)-> tweet? and tweet.text? and tweet.user? and tweet.user.screen_name?
#
# connect to twitter stream
connectToTwitterStream = (callback)->
twit = new twitter(settings.api)
console.log 'tracking: ' + settings.track
twit.stream 'user', {track: settings.track}, (stream)-> callback stream
#
# connect to led ticker daemon
connectToLedTicker = (callback)->
client = net.connect settings.daemon.port, settings.daemon.host, (err)-> callback client, err
#
# connects to the led ticker deamon and to the twitter stream
connectToLedTicker (ticker)-> connectToTwitterStream (stream)->
# add an event listener for new tweets
stream.on 'data', (tweet) -> ticker.write formatTweet(tweet) if isValidTweet tweet
| true | #
# Twitter client for the led ticker deamon
# Author: PI:NAME:<NAME>END_PI
#
net = require 'net'
util = require 'util'
twitter = require 'twitter'
fs = require 'fs'
configFile = process.env.HOME + '/.ledticker/twitter.json'
try
settings = JSON.parse fs.readFileSync(configFile)
catch err
console.log 'could not load config file: ' + configFile
console.log err
process.exit()
#
# the screen_name and message are displayed
formatTweet = (tweet)-> '@' + tweet.user.screen_name + ': ' + tweet.text + '\r\n'
#
# checks if a tweet is valid
isValidTweet = (tweet)-> tweet? and tweet.text? and tweet.user? and tweet.user.screen_name?
#
# connect to twitter stream
connectToTwitterStream = (callback)->
twit = new twitter(settings.api)
console.log 'tracking: ' + settings.track
twit.stream 'user', {track: settings.track}, (stream)-> callback stream
#
# connect to led ticker daemon
connectToLedTicker = (callback)->
client = net.connect settings.daemon.port, settings.daemon.host, (err)-> callback client, err
#
# connects to the led ticker deamon and to the twitter stream
connectToLedTicker (ticker)-> connectToTwitterStream (stream)->
# add an event listener for new tweets
stream.on 'data', (tweet) -> ticker.write formatTweet(tweet) if isValidTweet tweet
|
[
{
"context": "pKeys, (pgpKey) ->\n PGPKey\n key: \"pgp-key-#{pgpKey.name}\"\n pgpKey: pgpKey\n DOM",
"end": 1170,
"score": 0.9473026990890503,
"start": 1162,
"tag": "KEY",
"value": "pgp-key-"
}
] | src/components/manage.coffee | brianshaler/kerplunk-pgp | 0 | _ = require 'lodash'
React = require 'react'
{DOM} = React
PGPKey = React.createFactory React.createClass
getInitialState: ->
showKey: false
toggleKey: (e) ->
e.preventDefault()
@setState
showKey: !@state.showKey
render: ->
DOM.form
method: 'post'
action: "/admin/pgp/#{@props.pgpKey._id}/edit"
,
DOM.p null,
DOM.input
name: 'name'
defaultValue: @props.pgpKey.name
DOM.div null,
DOM.p null,
DOM.a
href: '#'
onClick: @toggleKey
,
if @state.showKey
'hide key'
else
'show key'
if @state.showKey
DOM.pre null, @props.pgpKey.publicKey
else
null
DOM.p null,
DOM.input
type: 'submit'
value: 'save'
DOM.a
href: "/admin/pgp/#{@props.pgpKey._id}/remove"
, 'delete'
module.exports = React.createFactory React.createClass
render: ->
DOM.section
className: 'content'
,
DOM.h3 null, 'PGP Keys'
_.map @props.pgpKeys, (pgpKey) ->
PGPKey
key: "pgp-key-#{pgpKey.name}"
pgpKey: pgpKey
DOM.h3 null, 'Generate a new key'
DOM.form
method: 'post'
action: '/admin/pgp/new'
,
DOM.input
name: 'name'
placeholder: 'name'
DOM.input
type: 'submit'
value: 'create'
| 70539 | _ = require 'lodash'
React = require 'react'
{DOM} = React
PGPKey = React.createFactory React.createClass
getInitialState: ->
showKey: false
toggleKey: (e) ->
e.preventDefault()
@setState
showKey: !@state.showKey
render: ->
DOM.form
method: 'post'
action: "/admin/pgp/#{@props.pgpKey._id}/edit"
,
DOM.p null,
DOM.input
name: 'name'
defaultValue: @props.pgpKey.name
DOM.div null,
DOM.p null,
DOM.a
href: '#'
onClick: @toggleKey
,
if @state.showKey
'hide key'
else
'show key'
if @state.showKey
DOM.pre null, @props.pgpKey.publicKey
else
null
DOM.p null,
DOM.input
type: 'submit'
value: 'save'
DOM.a
href: "/admin/pgp/#{@props.pgpKey._id}/remove"
, 'delete'
module.exports = React.createFactory React.createClass
render: ->
DOM.section
className: 'content'
,
DOM.h3 null, 'PGP Keys'
_.map @props.pgpKeys, (pgpKey) ->
PGPKey
key: "<KEY>#{pgpKey.name}"
pgpKey: pgpKey
DOM.h3 null, 'Generate a new key'
DOM.form
method: 'post'
action: '/admin/pgp/new'
,
DOM.input
name: 'name'
placeholder: 'name'
DOM.input
type: 'submit'
value: 'create'
| true | _ = require 'lodash'
React = require 'react'
{DOM} = React
PGPKey = React.createFactory React.createClass
getInitialState: ->
showKey: false
toggleKey: (e) ->
e.preventDefault()
@setState
showKey: !@state.showKey
render: ->
DOM.form
method: 'post'
action: "/admin/pgp/#{@props.pgpKey._id}/edit"
,
DOM.p null,
DOM.input
name: 'name'
defaultValue: @props.pgpKey.name
DOM.div null,
DOM.p null,
DOM.a
href: '#'
onClick: @toggleKey
,
if @state.showKey
'hide key'
else
'show key'
if @state.showKey
DOM.pre null, @props.pgpKey.publicKey
else
null
DOM.p null,
DOM.input
type: 'submit'
value: 'save'
DOM.a
href: "/admin/pgp/#{@props.pgpKey._id}/remove"
, 'delete'
module.exports = React.createFactory React.createClass
render: ->
DOM.section
className: 'content'
,
DOM.h3 null, 'PGP Keys'
_.map @props.pgpKeys, (pgpKey) ->
PGPKey
key: "PI:KEY:<KEY>END_PI#{pgpKey.name}"
pgpKey: pgpKey
DOM.h3 null, 'Generate a new key'
DOM.form
method: 'post'
action: '/admin/pgp/new'
,
DOM.input
name: 'name'
placeholder: 'name'
DOM.input
type: 'submit'
value: 'create'
|
[
{
"context": "'follows an artist', ->\n @user.followArtist 'andy-foobar', {}\n _.last(Backbone.sync.args)[1].url().sh",
"end": 1391,
"score": 0.9852132797241211,
"start": 1380,
"tag": "USERNAME",
"value": "andy-foobar"
},
{
"context": "e access token', ->\n @user.set a... | test/models/current_user.coffee | l2succes/force | 1 | Q = require 'bluebird-q'
_ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../models/current_user'
describe 'CurrentUser', ->
beforeEach ->
@sd = require('sharify').data
@sd.SESSION_ID = 'cool-session-id'
@user = new CurrentUser fabricate 'user'
sinon.stub(Backbone, 'sync')
afterEach ->
Backbone.sync.restore()
describe '#defaultArtworkCollection', ->
it 'throws a sensible error when you forget to initialize artwork collections', ->
(=> @user.defaultArtworkCollection()).should.throw /Must call/
describe '#saveArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.saveArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'create'
describe '#removeArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.removeArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'delete'
describe '#fetchSuggestedHomepageArtworks', ->
it 'fetches homepages artworks', ->
@user.fetchSuggestedHomepageArtworks({})
Backbone.sync.args[0][2].url.should.containEql 'suggested/artworks/homepage'
describe '#followArtist', ->
it 'follows an artist', ->
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[1].url().should.containEql 'me/follow/artist'
it 'injects the access token', ->
@user.set accessToken: 'xfoobar'
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[2].access_token.should.equal 'xfoobar'
describe '#addToPendingOrder', ->
it 'includes session_id if user does not have access_token', ->
# @user.set accessToken: null
@user.addToPendingOrder
editionSetId: '123'
artworkId: 'artwork-id'
quantity: 1
success: sinon.stub()
error: sinon.stub()
_.last(Backbone.sync.args)[1].attributes.session_id.should.equal 'cool-session-id'
it 'does not include session_id if user has access token', ->
@user.set accessToken: 'xfoobar'
@user.addToPendingOrder
editionSetId: '123'
artworkId: 'artwork-id'
quantity: 1
success: sinon.stub()
error: sinon.stub()
_.isUndefined(_.last(Backbone.sync.args)[1].attributes.session_id).should.be.ok()
describe '#checkRegisteredForAuction', ->
it 'makes the correct API call, accepts normal options', (done) ->
@user.checkRegisteredForAuction
saleId: 'an-auction'
success: (status) ->
status.should.be.true()
done()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/bidders'
Backbone.sync.args[0][2].data.sale_id.should.equal 'an-auction'
Backbone.sync.args[0][2].success ['existy']
describe '#fetchNotifications', ->
it 'makes the correct API call and has default size of 10', ->
@user.fetchNotificationBundles
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications/feed'
Backbone.sync.args[0][2].data.size.should.equal 10
describe '#fetchAndMarkNotifications', ->
it 'makes the correct API call and has defaults', ->
@user.fetchAndMarkNotifications
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications'
Backbone.sync.args[0][2].data.type.should.equal 'ArtworkPublished'
Backbone.sync.args[0][2].data.unread.should.be.true()
Backbone.sync.args[0][2].data.size.should.equal 100
describe '#prepareForInquiry', ->
beforeEach ->
Backbone.sync.restore()
@user = new CurrentUser
sinon.stub Backbone, 'sync'
.returns Q.resolve()
it 'creates or persists everything needed to make an inquiry', ->
@user.prepareForInquiry().then ->
Backbone.sync.callCount.should.equal 2
Backbone.sync.args[0][1].url()
.should.containEql '/api/v1/me'
Backbone.sync.args[1][1].url
.should.containEql '/api/v1/me/collector_profile'
describe '#isChecked', ->
it 'translates a boolean attribute to on or off', ->
@user.set weekly_email: false, follow_email: true, offer_emails: false
_.isUndefined(@user.isChecked('weekly_email')).should.be.true()
_.isUndefined(@user.isChecked('offer_emails')).should.be.true()
@user.isChecked('follow_email').should.be.true()
describe 'authentications', ->
beforeEach ->
@authentications = [
{ id: '1', uid: '123456789', provider: 'twitter' }
{ id: '2', uid: '987654321', provider: 'facebook' }
]
describe 'relation', ->
it 'should inject initial authentications', ->
user = new CurrentUser authentications: @authentications
user.isLinkedTo('twitter').should.be.true()
user.isLinkedTo('facebook').should.be.true()
describe '#isLinkedTo', ->
it 'determines if an account is linked to an app provider', ->
@user.isLinkedTo 'twitter'
.should.be.false()
@user.related().authentications.reset @authentications
@user.isLinkedTo 'twitter'
.should.be.true()
@user.isLinkedTo 'facebook'
.should.be.true()
| 158730 | Q = require 'bluebird-q'
_ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../models/current_user'
describe 'CurrentUser', ->
beforeEach ->
@sd = require('sharify').data
@sd.SESSION_ID = 'cool-session-id'
@user = new CurrentUser fabricate 'user'
sinon.stub(Backbone, 'sync')
afterEach ->
Backbone.sync.restore()
describe '#defaultArtworkCollection', ->
it 'throws a sensible error when you forget to initialize artwork collections', ->
(=> @user.defaultArtworkCollection()).should.throw /Must call/
describe '#saveArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.saveArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'create'
describe '#removeArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.removeArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'delete'
describe '#fetchSuggestedHomepageArtworks', ->
it 'fetches homepages artworks', ->
@user.fetchSuggestedHomepageArtworks({})
Backbone.sync.args[0][2].url.should.containEql 'suggested/artworks/homepage'
describe '#followArtist', ->
it 'follows an artist', ->
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[1].url().should.containEql 'me/follow/artist'
it 'injects the access token', ->
@user.set accessToken: '<KEY>'
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[2].access_token.should.equal 'x<KEY>'
describe '#addToPendingOrder', ->
it 'includes session_id if user does not have access_token', ->
# @user.set accessToken: null
@user.addToPendingOrder
editionSetId: '123'
artworkId: 'artwork-id'
quantity: 1
success: sinon.stub()
error: sinon.stub()
_.last(Backbone.sync.args)[1].attributes.session_id.should.equal 'cool-session-id'
it 'does not include session_id if user has access token', ->
@user.set accessToken: '<KEY>'
@user.addToPendingOrder
editionSetId: '123'
artworkId: 'artwork-id'
quantity: 1
success: sinon.stub()
error: sinon.stub()
_.isUndefined(_.last(Backbone.sync.args)[1].attributes.session_id).should.be.ok()
describe '#checkRegisteredForAuction', ->
it 'makes the correct API call, accepts normal options', (done) ->
@user.checkRegisteredForAuction
saleId: 'an-auction'
success: (status) ->
status.should.be.true()
done()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/bidders'
Backbone.sync.args[0][2].data.sale_id.should.equal 'an-auction'
Backbone.sync.args[0][2].success ['existy']
describe '#fetchNotifications', ->
it 'makes the correct API call and has default size of 10', ->
@user.fetchNotificationBundles
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications/feed'
Backbone.sync.args[0][2].data.size.should.equal 10
describe '#fetchAndMarkNotifications', ->
it 'makes the correct API call and has defaults', ->
@user.fetchAndMarkNotifications
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications'
Backbone.sync.args[0][2].data.type.should.equal 'ArtworkPublished'
Backbone.sync.args[0][2].data.unread.should.be.true()
Backbone.sync.args[0][2].data.size.should.equal 100
describe '#prepareForInquiry', ->
beforeEach ->
Backbone.sync.restore()
@user = new CurrentUser
sinon.stub Backbone, 'sync'
.returns Q.resolve()
it 'creates or persists everything needed to make an inquiry', ->
@user.prepareForInquiry().then ->
Backbone.sync.callCount.should.equal 2
Backbone.sync.args[0][1].url()
.should.containEql '/api/v1/me'
Backbone.sync.args[1][1].url
.should.containEql '/api/v1/me/collector_profile'
describe '#isChecked', ->
it 'translates a boolean attribute to on or off', ->
@user.set weekly_email: false, follow_email: true, offer_emails: false
_.isUndefined(@user.isChecked('weekly_email')).should.be.true()
_.isUndefined(@user.isChecked('offer_emails')).should.be.true()
@user.isChecked('follow_email').should.be.true()
describe 'authentications', ->
beforeEach ->
@authentications = [
{ id: '1', uid: '123456789', provider: 'twitter' }
{ id: '2', uid: '987654321', provider: 'facebook' }
]
describe 'relation', ->
it 'should inject initial authentications', ->
user = new CurrentUser authentications: @authentications
user.isLinkedTo('twitter').should.be.true()
user.isLinkedTo('facebook').should.be.true()
describe '#isLinkedTo', ->
it 'determines if an account is linked to an app provider', ->
@user.isLinkedTo 'twitter'
.should.be.false()
@user.related().authentications.reset @authentications
@user.isLinkedTo 'twitter'
.should.be.true()
@user.isLinkedTo 'facebook'
.should.be.true()
| true | Q = require 'bluebird-q'
_ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../models/current_user'
describe 'CurrentUser', ->
beforeEach ->
@sd = require('sharify').data
@sd.SESSION_ID = 'cool-session-id'
@user = new CurrentUser fabricate 'user'
sinon.stub(Backbone, 'sync')
afterEach ->
Backbone.sync.restore()
describe '#defaultArtworkCollection', ->
it 'throws a sensible error when you forget to initialize artwork collections', ->
(=> @user.defaultArtworkCollection()).should.throw /Must call/
describe '#saveArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.saveArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'create'
describe '#removeArtwork', ->
it 'makes the correct api call', ->
@user.initializeDefaultArtworkCollection()
@user.removeArtwork('masterpiece', null)
Backbone.sync.args[1][0].should.equal 'delete'
describe '#fetchSuggestedHomepageArtworks', ->
it 'fetches homepages artworks', ->
@user.fetchSuggestedHomepageArtworks({})
Backbone.sync.args[0][2].url.should.containEql 'suggested/artworks/homepage'
describe '#followArtist', ->
it 'follows an artist', ->
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[1].url().should.containEql 'me/follow/artist'
it 'injects the access token', ->
@user.set accessToken: 'PI:KEY:<KEY>END_PI'
@user.followArtist 'andy-foobar', {}
_.last(Backbone.sync.args)[2].access_token.should.equal 'xPI:KEY:<KEY>END_PI'
describe '#addToPendingOrder', ->
it 'includes session_id if user does not have access_token', ->
# @user.set accessToken: null
@user.addToPendingOrder
editionSetId: '123'
artworkId: 'artwork-id'
quantity: 1
success: sinon.stub()
error: sinon.stub()
_.last(Backbone.sync.args)[1].attributes.session_id.should.equal 'cool-session-id'
it 'does not include session_id if user has access token', ->
@user.set accessToken: 'PI:KEY:<KEY>END_PI'
@user.addToPendingOrder
editionSetId: '123'
artworkId: 'artwork-id'
quantity: 1
success: sinon.stub()
error: sinon.stub()
_.isUndefined(_.last(Backbone.sync.args)[1].attributes.session_id).should.be.ok()
describe '#checkRegisteredForAuction', ->
it 'makes the correct API call, accepts normal options', (done) ->
@user.checkRegisteredForAuction
saleId: 'an-auction'
success: (status) ->
status.should.be.true()
done()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/bidders'
Backbone.sync.args[0][2].data.sale_id.should.equal 'an-auction'
Backbone.sync.args[0][2].success ['existy']
describe '#fetchNotifications', ->
it 'makes the correct API call and has default size of 10', ->
@user.fetchNotificationBundles
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications/feed'
Backbone.sync.args[0][2].data.size.should.equal 10
describe '#fetchAndMarkNotifications', ->
it 'makes the correct API call and has defaults', ->
@user.fetchAndMarkNotifications
success: (status) ->
status.should.be.true()
Backbone.sync.args[0][2].url.should.containEql '/api/v1/me/notifications'
Backbone.sync.args[0][2].data.type.should.equal 'ArtworkPublished'
Backbone.sync.args[0][2].data.unread.should.be.true()
Backbone.sync.args[0][2].data.size.should.equal 100
describe '#prepareForInquiry', ->
beforeEach ->
Backbone.sync.restore()
@user = new CurrentUser
sinon.stub Backbone, 'sync'
.returns Q.resolve()
it 'creates or persists everything needed to make an inquiry', ->
@user.prepareForInquiry().then ->
Backbone.sync.callCount.should.equal 2
Backbone.sync.args[0][1].url()
.should.containEql '/api/v1/me'
Backbone.sync.args[1][1].url
.should.containEql '/api/v1/me/collector_profile'
describe '#isChecked', ->
it 'translates a boolean attribute to on or off', ->
@user.set weekly_email: false, follow_email: true, offer_emails: false
_.isUndefined(@user.isChecked('weekly_email')).should.be.true()
_.isUndefined(@user.isChecked('offer_emails')).should.be.true()
@user.isChecked('follow_email').should.be.true()
describe 'authentications', ->
beforeEach ->
@authentications = [
{ id: '1', uid: '123456789', provider: 'twitter' }
{ id: '2', uid: '987654321', provider: 'facebook' }
]
describe 'relation', ->
it 'should inject initial authentications', ->
user = new CurrentUser authentications: @authentications
user.isLinkedTo('twitter').should.be.true()
user.isLinkedTo('facebook').should.be.true()
describe '#isLinkedTo', ->
it 'determines if an account is linked to an app provider', ->
@user.isLinkedTo 'twitter'
.should.be.false()
@user.related().authentications.reset @authentications
@user.isLinkedTo 'twitter'
.should.be.true()
@user.isLinkedTo 'facebook'
.should.be.true()
|
[
{
"context": ": 'h0'\n 'body': '= $1 =\\n${2:Author Name} <${3:mail@address.com}>\\nv1.0, `date`\\n\\n$0'\n 'Heading 1 (one-liner)':",
"end": 559,
"score": 0.9998546838760376,
"start": 543,
"tag": "EMAIL",
"value": "mail@address.com"
}
] | .atom/.atom/packages/language-asciidoc/snippets/language-asciidoc.cson | thepieuvre/dotfiles | 0 | '.source.asciidoc':
'Comment Block':
'prefix': 'bl//'
'body': '////////////////////////////////////////////////////////////////////////////\n$1\n////////////////////////////////////////////////////////////////////////////\n$0'
'Example Block':
'prefix': 'bl=='
'body': '============================================================================\n$1\n============================================================================\n$0'
'Heading 0 (one-liner)':
'prefix': 'h0'
'body': '= $1 =\n${2:Author Name} <${3:mail@address.com}>\nv1.0, `date`\n\n$0'
'Heading 1 (one-liner)':
'prefix': 'h1'
'body': '== $1 ==\n\n$0'
'Heading 2 (one-liner)':
'prefix': 'h2'
'body': '=== $1 ===\n\n$0'
'Heading 3 (one-liner)':
'prefix': 'h3'
'body': '==== $1 ====\n\n$0'
'Heading 4 (one-liner)':
'prefix': 'h4'
'body': '===== $1 =====\n\n$0'
'Listing Block':
'prefix': 'bl--'
'body': '[source,$1]\n----\n$2\n----\n$0'
'Literal Block':
'prefix': 'bl..'
'body': '............................................................................\n$1\n............................................................................\n$0'
'Passthrough Block':
'prefix': 'bl++'
'body': '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n$1\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n$0'
'Quote Block':
'prefix': 'bl__'
'body': '____________________________________________________________________________\n$1\n____________________________________________________________________________\n$0'
'Sidebar Block':
'prefix': 'bl**'
'body': '****************************************************************************\n$1\n****************************************************************************\n$0'
'Table':
'prefix': '|='
'body': '.${1:Legend}\n[width="${2:100%}",cols="$3",options="$4"]\n|===\n|$5\n|==='
| 7711 | '.source.asciidoc':
'Comment Block':
'prefix': 'bl//'
'body': '////////////////////////////////////////////////////////////////////////////\n$1\n////////////////////////////////////////////////////////////////////////////\n$0'
'Example Block':
'prefix': 'bl=='
'body': '============================================================================\n$1\n============================================================================\n$0'
'Heading 0 (one-liner)':
'prefix': 'h0'
'body': '= $1 =\n${2:Author Name} <${3:<EMAIL>}>\nv1.0, `date`\n\n$0'
'Heading 1 (one-liner)':
'prefix': 'h1'
'body': '== $1 ==\n\n$0'
'Heading 2 (one-liner)':
'prefix': 'h2'
'body': '=== $1 ===\n\n$0'
'Heading 3 (one-liner)':
'prefix': 'h3'
'body': '==== $1 ====\n\n$0'
'Heading 4 (one-liner)':
'prefix': 'h4'
'body': '===== $1 =====\n\n$0'
'Listing Block':
'prefix': 'bl--'
'body': '[source,$1]\n----\n$2\n----\n$0'
'Literal Block':
'prefix': 'bl..'
'body': '............................................................................\n$1\n............................................................................\n$0'
'Passthrough Block':
'prefix': 'bl++'
'body': '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n$1\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n$0'
'Quote Block':
'prefix': 'bl__'
'body': '____________________________________________________________________________\n$1\n____________________________________________________________________________\n$0'
'Sidebar Block':
'prefix': 'bl**'
'body': '****************************************************************************\n$1\n****************************************************************************\n$0'
'Table':
'prefix': '|='
'body': '.${1:Legend}\n[width="${2:100%}",cols="$3",options="$4"]\n|===\n|$5\n|==='
| true | '.source.asciidoc':
'Comment Block':
'prefix': 'bl//'
'body': '////////////////////////////////////////////////////////////////////////////\n$1\n////////////////////////////////////////////////////////////////////////////\n$0'
'Example Block':
'prefix': 'bl=='
'body': '============================================================================\n$1\n============================================================================\n$0'
'Heading 0 (one-liner)':
'prefix': 'h0'
'body': '= $1 =\n${2:Author Name} <${3:PI:EMAIL:<EMAIL>END_PI}>\nv1.0, `date`\n\n$0'
'Heading 1 (one-liner)':
'prefix': 'h1'
'body': '== $1 ==\n\n$0'
'Heading 2 (one-liner)':
'prefix': 'h2'
'body': '=== $1 ===\n\n$0'
'Heading 3 (one-liner)':
'prefix': 'h3'
'body': '==== $1 ====\n\n$0'
'Heading 4 (one-liner)':
'prefix': 'h4'
'body': '===== $1 =====\n\n$0'
'Listing Block':
'prefix': 'bl--'
'body': '[source,$1]\n----\n$2\n----\n$0'
'Literal Block':
'prefix': 'bl..'
'body': '............................................................................\n$1\n............................................................................\n$0'
'Passthrough Block':
'prefix': 'bl++'
'body': '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n$1\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n$0'
'Quote Block':
'prefix': 'bl__'
'body': '____________________________________________________________________________\n$1\n____________________________________________________________________________\n$0'
'Sidebar Block':
'prefix': 'bl**'
'body': '****************************************************************************\n$1\n****************************************************************************\n$0'
'Table':
'prefix': '|='
'body': '.${1:Legend}\n[width="${2:100%}",cols="$3",options="$4"]\n|===\n|$5\n|==='
|
[
{
"context": " tags: []\n socialMailsReceived:\n name: \"Mails Received\"\n description: \"The number of mails",
"end": 28431,
"score": 0.6348803043365479,
"start": 28426,
"tag": "NAME",
"value": "Mails"
},
{
"context": "\n tags: []\n socialMailsSent:\n na... | src/javascript/character_stats.coffee | seriallos/eve-year-in-review | 18 | _ = require 'lodash'
class CharacterStats
constructor: (stats) ->
for key, val of stats
@[key] = val
@secSuffixes = [
'HighSec'
'LowSec'
'NullSec'
'Wormhole'
]
@calcDerived()
# not tested, may not be useful since names are all over the place
#getByPrefix: (prefix) ->
# return _.map @, (key, val) -> {key: key, val: val}
total: (prefix) ->
statNames = _.map @secSuffixes, (suffix) -> prefix + suffix
return _.reduce statNames, ((sum, stat) => sum + @[stat]), 0
percent: (prefix, suffix) ->
total = @total prefix
pct = @[prefix + suffix] / total
return pct
perMinute: (stat) ->
if @characterMinutes
return @[stat] / @characterMinutes
else
return null
perHour: (stat) ->
perMinute = @perMinute(stat)
if perMinute
return perMinute * 60
else
return null
get: (stat) ->
return @[stat]
calcDerived: ->
# fix a few stats
@iskOut = -(@iskOut)
# derive some stats
@averageSessionLength = @characterMinutes / @characterSessionsStarted
@combatKillsTotal = @total 'combatKills'
@combatDeathsTotal = @total 'combatDeaths'
@kdRatioTotal = @combatKillsTotal / @combatDeathsTotal
@combatDeathsPodTotal = @combatDeathsPodHighSec +
@combatDeathsPodLowSec +
@combatDeathsPodNullSec +
@combatDeathsPodWormhole
@combatKillsPodTotal = @combatKillsPodHighSec +
@combatKillsPodLowSec +
@combatKillsPodNullSec +
@combatKillsPodWormhole
@kdRatioHigh = @combatKillsHighSec / @combatDeathsHighSec
@kdRatioLow = @combatKillsLowSec / @combatDeathsLowSec
@kdRatioNull = @combatKillsNullSec / @combatDeathsNullSec
@kdRatioWormhole = @combatKillsWormhole / @combatDeathsWormhole
@travelDistanceWarpedTotal = @total 'travelDistanceWarped'
@totalDamageDealt = @combatDamageToPlayersBombAmount +
@combatDamageToPlayersCombatDroneAmount +
@combatDamageToPlayersEnergyAmount +
@combatDamageToPlayersFighterBomberAmount +
@combatDamageToPlayersFighterDroneAmount +
@combatDamageToPlayersHybridAmount +
@combatDamageToPlayersMissileAmount +
@combatDamageToPlayersProjectileAmount +
@combatDamageToPlayersSmartBombAmount +
@combatDamageToPlayersSuperAmount
@iskSpentPercent = 100 * (@iskOut / @iskIn)
metadata:
daysOfActivity:
name: "Active Days"
description: "The number of days in the period with recorded activity"
tags: ['general']
characterMinutes:
name: "Minutes Logged In"
description: "The number of minutes logged in as this character"
tags: ['general']
characterSessionsStarted:
name: "Logins"
description: "The number of times the character has logged into the game"
tags: ['general']
iskIn:
name: "ISK Earned"
description: "The total amount of positive ISK transactions in the character wallet"
tags: ['general']
iskOut:
name: "ISK Spent"
description: "The total amount of negative ISK transactions in the character wallet"
tags: ['general']
travelJumpsStargateHighSec:
name: "High Sec Jumps"
description: "The number of jumps through a gate in high security space"
tags: ['travel']
travelJumpsStargateLowSec:
name: "Low Sec Jumps"
description: "The number of jumps through a gate in low security space"
tags: ['travel']
travelJumpsStargateNullSec:
name: "Null Sec Jumps"
description: "The number of jumps through a gate in null security space"
tags: ['travel']
travelJumpsWormhole:
name: "Wormhole Jumps"
description: "The number of jumps through a wormhole"
tags: ['travel']
travelDocksHighSec:
name: "Docked in High Sec"
description: "The number of docks in high security space"
tags: ['travel']
travelDocksLowSec:
name: "Docked in Low Sec"
description: "The number of docks in low security space"
tags: ['travel']
travelDocksNullSec:
name: "Docked in Null Sec"
description: "The number of docks in null security space"
tags: ['travel']
pveMissionsSucceeded:
name: "Missions Completed"
description: "The number of missions completed"
tags: ['pve']
pveMissionsSucceededEpicArc:
name: "Epic Arcs Completed"
description: "The number of epic arc missions completed"
tags: ['pve']
combatKillsHighSec:
name: "High Sec Kills"
description: "The number of kills in high security space"
tags: ['pvp']
combatKillsLowSec:
name: "Low Sec Kills"
description: "The number of kills in low security space"
tags: ['pvp']
combatKillsNullSec:
name: "Null Sec Kills"
description: "The number of kills in null security space"
tags: ['pvp']
combatKillsWormhole:
name: "Wormhole Kills"
description: "The number of kills in wormhole space"
tags: ['pvp']
combatKillsPodTotal:
name: "Pods Killed"
description: "The total number of capsule kills (final blows)"
tags: ['pvp']
combatDeathsHighSec:
name: "High Sec Deaths"
description: "The number of deaths in high security space"
tags: ['deaths']
combatDeathsLowSec:
name: "Low Sec Deaths"
description: "The number of deaths in low security space"
tags: ['deaths']
combatDeathsNullSec:
name: "Null Sec Deaths"
description: "The number of deaths in null security space"
tags: ['deaths']
combatDeathsWormhole:
name: "Wormhole Deaths"
description: "The number of deaths in wormhole space"
tags: ['deaths']
combatDeathsPodTotal:
name: "Times Podded"
description: "The total number of capsule deaths (times podded)"
tags: ['deaths']
combatKillsAssists:
name: "Assists"
description: "The total number of kill assists"
tags: ['pvp']
combatCapDrainedbyPC:
name: "Cap Drained by Players"
description: "The amount of the characters capacitor that has been drained by other player"
tags: ['pvp']
combatCapDrainingPC:
name: "Cap Drained from Players"
description: "The amount of capacitor the character has drained from other players"
tags: ['pvp']
combatCriminalFlagSet:
name: "Times Criminal Flagged"
description: "The number of times the character has had the crimewatch criminal flag set"
tags: ['pvp']
combatDamageFromNPCsAmount:
name: "Damage Taken from NPCs"
description: "The total amount of damage taken from NPCs."
tags: ['pve']
combatDamageFromNPCsNumShots:
name: "Times Shot by NPCs"
description: "The total number of times NPCs have shot the character."
tags: ['pve']
combatDamageFromPlayersBombAmount:
name: "Damage Taken from Bombs"
description: "The total damage taken from bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersBombNumShots:
name: "Hits Taken from Bombs"
description: "The total number of hits taken from bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersEnergyAmount:
name: "Damage Taken from Lasers"
description: "The total damage taken from laser turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersEnergyNumShots:
name: "Hits Taken from Lasers"
description: "The total number of hits taken from laser turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersCombatDroneAmount:
name: "Damage Taken from Combat Drones"
description: "The total damage taken from combat drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersCombatDroneNumShots:
name: "Hits Taken from Combat Drones"
description: "The total number of hits taken from combat drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterBomberAmount:
name: "Damage Taken from Fighter Bombers"
description: "The total damage taken from fighter bombers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterBomberNumShots:
name: "Hits Taken from Fighter Bombers"
description: "The total number of hits taken from fighter bombers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterDroneAmount:
name: "Damage Taken from Fighter Drones"
description: "The total damage taken from fighter drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterDroneNumShots:
name: "Hits Taken from Fighter Drones"
description: "The total number of hits taken from fighter drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersHybridAmount:
name: "Damage Taken from Hybrids"
description: "The total damage taken from hybrid turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersHybridNumShots:
name: "Hits Taken from Hybrids"
description: "The total number of hits taken from hybrid turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersMissileAmount:
name: "Damage Taken from Missiles"
description: "The total damage taken from missile launchers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersMissileNumShots:
name: "Hits Taken from Missiles"
description: "The total number of hits taken from missile launchers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersProjectileAmount:
name: "Damage Taken from Projectiles"
description: "The total damage taken from projectile turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersProjectileNumShots:
name: "Hits Taken from Projectiles"
description: "The total number of hits taken from projectile turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSmartBombAmount:
name: "Damage Taken from Smart Bombs"
description: "The total damage taken from smart bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSmartBombNumShots:
name: "Hits Taken from Smart Bombs"
description: "The total number of hits taken from smart bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSuperAmount:
name: "Damage Taken from Doomsdays"
description: "The total damage taken from doomsday devices"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSuperNumShots:
name: "Hits Taken from Doomsdays"
description: "The total number of hits taken from doomsday devices"
tags: ['damageDone','pvp']
combatDamageToPlayersCombatDroneAmount:
name: "Damage Dealt with Combat Drones"
description: "The total amount damage dealt to other players using combat drones"
tags: ['damageDone','pvp']
combatDamageToPlayersCombatDroneNumShots:
name: "Hits Dealt with Combat Drones"
description: "The total number of hits made to other players using combat drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterDroneAmount:
name: "Damage Dealt with Fighter Drones"
description: "The total amount damage dealt to other players using fighter drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterDroneNumShots:
name: "Hits Dealt with Fighter Drones"
description: "The total number of hits made to other players using fighter drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterBomberAmount:
name: "Damage Dealt with Fighter Drones"
description: "The total amount damage dealt to other players using fighter bombers"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterBomberNumShots:
name: "Hits Dealt with Fighter Drones"
description: "The total number of hits made to other players using fighter bombers"
tags: ['damageDone','pvp']
combatDamageToPlayersBombAmount:
name: "Damage Dealt with Bombs"
description: "The total amount damage dealt to other players using bombs"
tags: ['damageDone','pvp']
combatDamageToPlayersBombNumShots:
name: "Hits Dealt with Bombs"
description: "The total number of hits made to other players using bombs"
tags: ['damageDone','pvp']
combatDamageToPlayersEnergyAmount:
name: "Damage Dealt with Lasers"
description: "The total amount damage dealt to other players using laser turrets"
tags: []
combatDamageToPlayersEnergyNumShots:
name: "Number of Laser Shots"
description: "The total number of shots made with laser turrets"
tags: []
combatDamageToPlayersHybridAmount:
name: "Damage Dealt with Hybrids"
description: "The total amount damage dealt to other players using hybrid turrets"
tags: []
combatDamageToPlayersHybridNumShots:
name: "Number of Hybrid Shots"
description: "The total number of shots made with hybrid turrets"
tags: []
combatDamageToPlayersMissileAmount:
name: "Damage Dealt with Missiles"
description: "The total amount damage dealt to other players using missile launchers"
tags: []
combatDamageToPlayersMissileNumShots:
name: "Number of Missile Shots"
description: "The total number of shots made with missile launchers"
tags: []
combatDamageToPlayersProjectileAmount:
name: "Damage Dealt with Projectiles"
description: "The total amount damage dealt to other players using projectile turrets"
tags: []
combatDamageToPlayersProjectileNumShots:
name: "Number of Projectile Shots"
description: "The total number of shots made with projectile turrets"
tags: []
combatDamageToPlayersSmartBombAmount:
name: "Damage Dealth with Smart Bombs"
description: "The total amount damage dealt to other players using smart bombs"
tags: []
combatDamageToPlayersSmartBombNumShots:
name: "Number of Smart Bomb Hits"
description: "The total number of hits made with smart bombs"
tags: []
combatDamageToPlayersStructureAmount:
description: "REMOVE: Always 0...#wellshit"
disabled: true
tags: []
combatDamageToPlayersStructureNumShots:
description: "REMOVE: Always 0...#wellshit"
disabled: true
tags: []
combatDamageToPlayersSuperAmount:
name: "Damage Dealth with Doomsdays"
description: "The total amount of damage dealt using doomsday devices"
tags: []
combatDamageToPlayersSuperNumShots:
name: "Number of Doomsday Shots"
description: "The total number of shots made with doomsday devices"
tags: []
combatDuelRequested:
names: "Duel Requests"
description: "The total number of times the character requested a duel against another player"
tags: []
combatNpcFlagSet:
names: "Aggressed against NPCs"
description: "The number of times aggression flag was set against NPCs"
tags: []
combatPvpFlagSet:
name: "Aggressed against Players"
description: "The number of times aggression flag was set against Players"
tags: []
combatRepairArmorByRemoteAmount:
name: "Armor Reps Received"
description: "The total amount received from remote armor repairers"
tags: []
combatRepairArmorRemoteAmount:
name: "Armor Reps Given"
description: "The total amount repaired using remote armor repairers"
tags: []
combatRepairArmorSelfAmount:
name: "Armor Self Repped"
description: "The total amount repaired using local armor repairers"
tags: []
combatRepairCapacitorByRemoteAmount:
name: "Energy Transfer Received"
description: "The total amount of energy received from energy transfers"
tags: []
combatRepairCapacitorRemoteAmount:
name: "Energy Transfer Given"
description: "The total amount of energy sent using energy tranfers"
tags: []
combatRepairHullByRemoteAmount:
name: "Hull Reps Received"
description: "The total amount received from remote hull repairers"
tags: []
combatRepairHullRemoteAmount:
name: "Hull Reps Given"
description: "The total amount repaired using remote hull repairers"
tags: []
combatRepairHullSelfAmount:
name: "Hull Self Repped"
description: "The total amount repaired using local hull repairers"
tags: []
combatRepairShieldByRemoteAmount:
name: "Shield Reps Receieved"
description: "The total amount received from remote shield transfers"
tags: []
combatRepairShieldRemoteAmount:
name: "Shield Reps Given"
description: "The total amount repaired using remote shield transfers"
tags: []
combatRepairShieldSelfAmount:
name: "Shield Self Repped"
description: "The total amount repaired using local shield transfers"
tags: []
combatSelfDestructs:
name: "Self Destructs"
description: "The number of successful self destructs"
tags: []
combatWarpScramblePC:
name: "Scrammed Player"
description: "The number of times warp scrambled other players"
tags: []
combatWarpScrambledbyNPC:
name: "Scrammed by NPC"
description: "The number of times warp scrambled by NPCs"
tags: []
combatWarpScrambledbyPC:
name: "Scrammed by Player"
description: "The number of times warp scrambled by other players"
tags: []
combatWebifiedbyNPC:
name: "Webbed Player"
description: "The number of times webbed other players"
tags: []
combatWebifiedbyPC:
name: "Webbed by NPCs"
description: "The number of times webbed by NPCs"
tags: []
combatWebifyingPC:
name: "Webbed by Player"
description: "The number of times webbed by other players"
tags: []
genericConeScans:
name: "Times Dscanned"
description: "The number of directional scans made"
tags: []
genericRequestScans:
name: "Probe Scans"
description: "The number of probe scans made"
tags: []
industryHackingSuccesses:
name: "Data Cans Hacked"
description: "The number of successful hacking attempts"
tags: []
industryJobsCompletedCopyBlueprint:
name: "Blueprints Copied"
description: "The number of copy jobs completed"
tags: []
industryJobsCompletedInvention:
name: "Invention Jobs"
description: "The number of invention jobs completed"
tags: []
industryJobsCompletedManufacture:
name: "Manufacturing Jobs"
description: "The total number of manufacturing jobs completed"
tags: []
industryJobsCompletedManufactureAsteroidQuantity:
name: "Mineral Compression Jobs"
description: "The total units of"
tags: []
industryJobsCompletedManufactureChargeQuantity:
name: "Charges Produced"
description: "The total units of charges produced"
tags: []
industryJobsCompletedManufactureCommodityQuantity:
name: "Commodities Produced"
description: "The total units of commodities produced"
tags: []
industryJobsCompletedManufactureDeployableQuantity:
name: "Deployables Produced"
description: "The total units of deployables produced"
tags: []
industryJobsCompletedManufactureDroneQuantity:
name: "Drones Produced"
description: "The total units of drones produced"
tags: []
industryJobsCompletedManufactureImplantQuantity:
name: "Implants Produced"
description: "The total units of implants produced"
tags: []
industryJobsCompletedManufactureModuleQuantity:
name: "Modules Produced"
description: "The total units of modules produced"
tags: []
industryJobsCompletedManufactureShipQuantity:
name: "Ships Produced"
description: "The total units of ships produced"
tags: []
industryJobsCompletedManufactureStructureQuantity:
name: "Structures Produced"
description: "The total units of structures produced"
tags: []
industryJobsCompletedManufactureSubsystemQuantity:
name: "Subsystems Produced"
description: "The total units of subsystems produced"
tags: []
industryJobsCompletedMaterialProductivity:
name: "ME Jobs"
description: "The number of material efficiency jobs completed"
tags: []
industryJobsCompletedReverseEngineering:
name: "Reverse Engineering Jobs"
description: "The number of reverse engineering jobs completed (merged into invention as of ?)"
tags: []
industryJobsCompletedTimeProductivity:
name: "TE Jobs"
description: "The number of production efficiency jobs completed"
tags: []
inventoryTrashItemQuantity:
# stack size or number of times used?
name: "Items Trashed"
description: "The number of items trashed"
tags: []
marketISKGained:
name: "ISK Received from Sell Orders"
description: "The amount of isk from sell-orders"
tags: []
marketISKSpent:
name: "ISK Spent on Buy Orders"
description: "The amount of isk from buy-orders"
tags: []
marketAcceptContractsCourier:
name: "Courier Contracts Accepted"
description: "The number of times accepted a courier contract"
tags: []
marketAcceptContractsItemExchange:
name: "Item Contracts Accepted"
description: "The number of times accepted an item exchange contract"
tags: []
marketBuyOrdersPlaced:
name: "Buy Orders Placed"
description: "The number of buy orders placed"
tags: []
marketSellOrdersPlaced:
name: "Sell Orders Placed"
description: "The number of sell orders placed"
tags: []
marketCancelMarketOrder:
name: "Orders Cancelled"
description: "The number of orders cancelled"
tags: []
marketCreateContractsTotal:
# personal only? corp contracts as well?
name: "Contracts Created"
description: "The number of contracts created"
tags: []
marketDeliverCourierContract:
name: "Courier Contracts Delivered"
description: "The number of courier contracts delivered"
tags: []
marketModifyMarketOrder:
name: "Orders Modified"
description: "The number of modifications made to market orders"
tags: []
miningOreArkonor:
name: "Arkanor Mined"
description: "The total amount of Arkonor mined (units)"
tags: []
miningOreBistot:
name: "Bistot Mined"
description: "The total amount of Bistot mined (units)"
tags: []
miningOreCrokite:
name: "Crokite Mined"
description: "The total amount of Crokite mined (units)"
tags: []
miningOreDarkOchre:
name: "Dark Ochre Mined"
description: "The total amount of DarkOchre mined (units)"
tags: []
miningOreGneiss:
name: "Gneiss Mined"
description: "The total amount of Gneiss mined (units)"
tags: []
miningOreHarvestableCloud:
name: "Gas Huffed"
description: "The total amount of HarvestableCloud mined (units)"
tags: []
miningOreHedbergite:
name: "Hedbergite Mined"
description: "The total amount of Hedbergite mined (units)"
tags: []
miningOreHemorphite:
name: "Hemorphite Mined"
description: "The total amount of Hemorphite mined (units)"
tags: []
miningOreIce:
name: "Ice Mined"
description: "The total amount of Ice mined (units)"
tags: []
miningOreJaspet:
name: "Jaspet Mined"
description: "The total amount of Jaspet mined (units)"
tags: []
miningOreKernite:
name: "Kernite Mined"
description: "The total amount of Kernite mined (units)"
tags: []
miningOreMercoxit:
name: "Mercoxit Mined"
description: "The total amount of Mercoxit mined (units)"
tags: []
miningOreOmber:
name: "Omber Mined"
description: "The total amount of Omber mined (units)"
tags: []
miningOrePlagioclase:
name: "Plagioclase Mined"
description: "The total amount of Plagioclase mined (units)"
tags: []
miningOrePyroxeres:
name: "Pyroxeres Mined"
description: "The total amount of Pyroxeres mined (units)"
tags: []
miningOreScordite:
name: "Scordite Mined"
description: "The total amount of Scordite mined (units)"
tags: []
miningOreSpodumain:
name: "Spodumain Mined"
description: "The total amount of Spodumain mined (units)"
tags: []
miningOreVeldspar:
name: "Veldspar Mined"
description: "The total amount of Veldspar mined (units)"
tags: []
moduleActivationsCloakingDevice:
name: "Times Cloaked"
description: "The total number of cloak activations"
tags: []
moduleActivationsCynosuralField:
name: "Cynos Activated"
description: "The total number of cyno activations"
tags: []
moduleActivationsRemoteSensorSamper:
name: "Sensor Damps Used"
description: "The total number of sensor dampener activations"
tags: []
moduleActivationsECM:
name: "ECM Activations"
description: "The total number of ECM activations"
tags: []
moduleActivationsTargetPainter:
name: "Target Painter Activations"
description: "The total number of target painter activations"
tags: []
moduleActivationsEnergyVampire:
name: "Energy Vampire Activations"
description: "The total number of energy vampire activations"
tags: []
moduleActivationsGangCoordinator:
name: "Links Activated"
description: "The total number of gang link module activations"
tags: []
moduleOverload:
name: "Modules Overloaded"
description: "The number of times a module was overloaded"
tags: []
socialAddContactBad:
name: "Added Contact with Bad Standing"
description: "The number of contacts added with bad standings"
tags: []
socialAddContactGood:
name: "Added Contact with Good Standing"
description: "The number of contacts added with good standings"
tags: []
socialAddContactHigh:
name: "Added Contact with High Standing"
description: "The number of contacts added with high standings"
tags: []
socialAddContactHorrible:
name: "Added Contact with Horrible Standing"
description: "The number of contacts added with horrible standings"
tags: []
socialAddContactNeutral:
name: "Added Contact with Neutral Standing"
description: "The number of contacts added with neutral standings"
tags: []
socialAddedAsContactBad:
name: "Added as Bad Contact by Another Player"
description: "The number of times added as a contact with bad standings"
tags: []
socialAddedAsContactGood:
name: "Added as Good Contact by Another Player"
description: "The number of times added as a contact with good standings"
tags: []
socialAddedAsContactHigh:
name: "Added as High Contact by Another Player"
description: "The number of times added as a contact with high standings"
tags: []
socialAddedAsContactHorrible:
name: "Added as Horrible Contact by Another Player"
description: "The number of times added as a contact with horrible standings"
tags: []
socialAddedAsContactNeutral:
name: "Added as Neutral Contact by Another Player"
description: "The number of times added as a contact with neutral standings"
tags: []
socialChatTotalMessageLength:
name: "Total Length of All Chat"
description: "The total length of all chat messages -NSA"
tags: []
socialDirectTrades:
name: "Direct Trades"
description: "The number of direct trades made"
tags: []
socialFleetJoins:
name: "Fleets Joined"
description: "The number of fleets joined"
tags: []
socialFleetBroadcasts:
name: "Fleet Broadcasts"
description: "The number of broadcasts made in fleet"
tags: []
socialMailsReceived:
name: "Mails Received"
description: "The number of mails received -NSA"
tags: []
socialMailsSent:
name: "Mails Sent"
description: "The number of mails sent -NSA"
tags: []
travelAccelerationGateActivations:
name: "Acceleration Gates Activated"
description: "The number of acceleration gates activated"
tags: []
travelAlignTo:
name: "Times Aligned"
description: "The number of times ship alignment was made"
tags: []
travelDistanceWarpedHighSec:
name: "AU Traveled in High Sec"
description: "The total distance(AU) traveled in warp while in high security space"
tags: []
travelDistanceWarpedLowSec:
name: "AU Traveled in Low Sec"
description: "The total distance(AU) traveled in warp while in low security space"
tags: []
travelDistanceWarpedNullSec:
name: "AU Traveled in Null Sec"
description: "The total distance(AU) traveled in warp while in null security space"
tags: []
travelDistanceWarpedWormhole:
name: "AU Traveled in Wormholes"
description: "The total distance(AU) traveled in warp while in wormhole space"
tags: []
travelWarpsHighSec:
name: "Initiated Warp in High Sec"
description: "The total number of warps initiated while in high security space"
tags: []
travelWarpsLowSec:
name: "Initiated Warp in Low Sec"
description: "The total number of warps initiated while in low security space"
tags: []
travelWarpsNullSec:
name: "Initiated Warp in Null Sec"
description: "The total number of warps initiated while in null security space"
tags: []
travelWarpsWormhole:
name: "Initiated Warp in Wormholes"
description: "The total number of warps initiated while in wormhole space"
tags: []
travelWarpsToBookmark:
name: "Initiated Warp to Bookmark"
description: "The total number of warps initiated to a bookmark"
tags: []
travelWarpsToCelestial:
name: "Initiated Warp to Celestial"
description: "The total number of warps initiated to a celestial"
tags: []
travelWarpsToFleetMember:
name: "Initiated Warp to Fleet Member"
description: "The total number of warps initiated to a fleet member"
tags: []
travelWarpsToScanResult:
name: "Initiated Warp to Scan Result"
description: "The total number of warps initiated to a scan result"
tags: []
# derived fields
combatKillsTotal:
name: 'Total Kills'
tags: ['pvp']
combatDeathsTotal:
name: 'Total Deaths'
tags: ['pvp']
iskSpentPercent:
name: 'Percent of Income Spent, Overall'
tags: ['general']
units: 'percent'
kdRatioTotal:
name: 'Kill/Death Ratio'
tags: ['pvp']
averageSessionLength:
name: 'Average Session Length'
tags: ['general']
units: 'minutes'
module.exports = CharacterStats
| 173545 | _ = require 'lodash'
class CharacterStats
constructor: (stats) ->
for key, val of stats
@[key] = val
@secSuffixes = [
'HighSec'
'LowSec'
'NullSec'
'Wormhole'
]
@calcDerived()
# not tested, may not be useful since names are all over the place
#getByPrefix: (prefix) ->
# return _.map @, (key, val) -> {key: key, val: val}
total: (prefix) ->
statNames = _.map @secSuffixes, (suffix) -> prefix + suffix
return _.reduce statNames, ((sum, stat) => sum + @[stat]), 0
percent: (prefix, suffix) ->
total = @total prefix
pct = @[prefix + suffix] / total
return pct
perMinute: (stat) ->
if @characterMinutes
return @[stat] / @characterMinutes
else
return null
perHour: (stat) ->
perMinute = @perMinute(stat)
if perMinute
return perMinute * 60
else
return null
get: (stat) ->
return @[stat]
calcDerived: ->
# fix a few stats
@iskOut = -(@iskOut)
# derive some stats
@averageSessionLength = @characterMinutes / @characterSessionsStarted
@combatKillsTotal = @total 'combatKills'
@combatDeathsTotal = @total 'combatDeaths'
@kdRatioTotal = @combatKillsTotal / @combatDeathsTotal
@combatDeathsPodTotal = @combatDeathsPodHighSec +
@combatDeathsPodLowSec +
@combatDeathsPodNullSec +
@combatDeathsPodWormhole
@combatKillsPodTotal = @combatKillsPodHighSec +
@combatKillsPodLowSec +
@combatKillsPodNullSec +
@combatKillsPodWormhole
@kdRatioHigh = @combatKillsHighSec / @combatDeathsHighSec
@kdRatioLow = @combatKillsLowSec / @combatDeathsLowSec
@kdRatioNull = @combatKillsNullSec / @combatDeathsNullSec
@kdRatioWormhole = @combatKillsWormhole / @combatDeathsWormhole
@travelDistanceWarpedTotal = @total 'travelDistanceWarped'
@totalDamageDealt = @combatDamageToPlayersBombAmount +
@combatDamageToPlayersCombatDroneAmount +
@combatDamageToPlayersEnergyAmount +
@combatDamageToPlayersFighterBomberAmount +
@combatDamageToPlayersFighterDroneAmount +
@combatDamageToPlayersHybridAmount +
@combatDamageToPlayersMissileAmount +
@combatDamageToPlayersProjectileAmount +
@combatDamageToPlayersSmartBombAmount +
@combatDamageToPlayersSuperAmount
@iskSpentPercent = 100 * (@iskOut / @iskIn)
metadata:
daysOfActivity:
name: "Active Days"
description: "The number of days in the period with recorded activity"
tags: ['general']
characterMinutes:
name: "Minutes Logged In"
description: "The number of minutes logged in as this character"
tags: ['general']
characterSessionsStarted:
name: "Logins"
description: "The number of times the character has logged into the game"
tags: ['general']
iskIn:
name: "ISK Earned"
description: "The total amount of positive ISK transactions in the character wallet"
tags: ['general']
iskOut:
name: "ISK Spent"
description: "The total amount of negative ISK transactions in the character wallet"
tags: ['general']
travelJumpsStargateHighSec:
name: "High Sec Jumps"
description: "The number of jumps through a gate in high security space"
tags: ['travel']
travelJumpsStargateLowSec:
name: "Low Sec Jumps"
description: "The number of jumps through a gate in low security space"
tags: ['travel']
travelJumpsStargateNullSec:
name: "Null Sec Jumps"
description: "The number of jumps through a gate in null security space"
tags: ['travel']
travelJumpsWormhole:
name: "Wormhole Jumps"
description: "The number of jumps through a wormhole"
tags: ['travel']
travelDocksHighSec:
name: "Docked in High Sec"
description: "The number of docks in high security space"
tags: ['travel']
travelDocksLowSec:
name: "Docked in Low Sec"
description: "The number of docks in low security space"
tags: ['travel']
travelDocksNullSec:
name: "Docked in Null Sec"
description: "The number of docks in null security space"
tags: ['travel']
pveMissionsSucceeded:
name: "Missions Completed"
description: "The number of missions completed"
tags: ['pve']
pveMissionsSucceededEpicArc:
name: "Epic Arcs Completed"
description: "The number of epic arc missions completed"
tags: ['pve']
combatKillsHighSec:
name: "High Sec Kills"
description: "The number of kills in high security space"
tags: ['pvp']
combatKillsLowSec:
name: "Low Sec Kills"
description: "The number of kills in low security space"
tags: ['pvp']
combatKillsNullSec:
name: "Null Sec Kills"
description: "The number of kills in null security space"
tags: ['pvp']
combatKillsWormhole:
name: "Wormhole Kills"
description: "The number of kills in wormhole space"
tags: ['pvp']
combatKillsPodTotal:
name: "Pods Killed"
description: "The total number of capsule kills (final blows)"
tags: ['pvp']
combatDeathsHighSec:
name: "High Sec Deaths"
description: "The number of deaths in high security space"
tags: ['deaths']
combatDeathsLowSec:
name: "Low Sec Deaths"
description: "The number of deaths in low security space"
tags: ['deaths']
combatDeathsNullSec:
name: "Null Sec Deaths"
description: "The number of deaths in null security space"
tags: ['deaths']
combatDeathsWormhole:
name: "Wormhole Deaths"
description: "The number of deaths in wormhole space"
tags: ['deaths']
combatDeathsPodTotal:
name: "Times Podded"
description: "The total number of capsule deaths (times podded)"
tags: ['deaths']
combatKillsAssists:
name: "Assists"
description: "The total number of kill assists"
tags: ['pvp']
combatCapDrainedbyPC:
name: "Cap Drained by Players"
description: "The amount of the characters capacitor that has been drained by other player"
tags: ['pvp']
combatCapDrainingPC:
name: "Cap Drained from Players"
description: "The amount of capacitor the character has drained from other players"
tags: ['pvp']
combatCriminalFlagSet:
name: "Times Criminal Flagged"
description: "The number of times the character has had the crimewatch criminal flag set"
tags: ['pvp']
combatDamageFromNPCsAmount:
name: "Damage Taken from NPCs"
description: "The total amount of damage taken from NPCs."
tags: ['pve']
combatDamageFromNPCsNumShots:
name: "Times Shot by NPCs"
description: "The total number of times NPCs have shot the character."
tags: ['pve']
combatDamageFromPlayersBombAmount:
name: "Damage Taken from Bombs"
description: "The total damage taken from bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersBombNumShots:
name: "Hits Taken from Bombs"
description: "The total number of hits taken from bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersEnergyAmount:
name: "Damage Taken from Lasers"
description: "The total damage taken from laser turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersEnergyNumShots:
name: "Hits Taken from Lasers"
description: "The total number of hits taken from laser turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersCombatDroneAmount:
name: "Damage Taken from Combat Drones"
description: "The total damage taken from combat drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersCombatDroneNumShots:
name: "Hits Taken from Combat Drones"
description: "The total number of hits taken from combat drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterBomberAmount:
name: "Damage Taken from Fighter Bombers"
description: "The total damage taken from fighter bombers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterBomberNumShots:
name: "Hits Taken from Fighter Bombers"
description: "The total number of hits taken from fighter bombers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterDroneAmount:
name: "Damage Taken from Fighter Drones"
description: "The total damage taken from fighter drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterDroneNumShots:
name: "Hits Taken from Fighter Drones"
description: "The total number of hits taken from fighter drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersHybridAmount:
name: "Damage Taken from Hybrids"
description: "The total damage taken from hybrid turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersHybridNumShots:
name: "Hits Taken from Hybrids"
description: "The total number of hits taken from hybrid turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersMissileAmount:
name: "Damage Taken from Missiles"
description: "The total damage taken from missile launchers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersMissileNumShots:
name: "Hits Taken from Missiles"
description: "The total number of hits taken from missile launchers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersProjectileAmount:
name: "Damage Taken from Projectiles"
description: "The total damage taken from projectile turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersProjectileNumShots:
name: "Hits Taken from Projectiles"
description: "The total number of hits taken from projectile turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSmartBombAmount:
name: "Damage Taken from Smart Bombs"
description: "The total damage taken from smart bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSmartBombNumShots:
name: "Hits Taken from Smart Bombs"
description: "The total number of hits taken from smart bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSuperAmount:
name: "Damage Taken from Doomsdays"
description: "The total damage taken from doomsday devices"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSuperNumShots:
name: "Hits Taken from Doomsdays"
description: "The total number of hits taken from doomsday devices"
tags: ['damageDone','pvp']
combatDamageToPlayersCombatDroneAmount:
name: "Damage Dealt with Combat Drones"
description: "The total amount damage dealt to other players using combat drones"
tags: ['damageDone','pvp']
combatDamageToPlayersCombatDroneNumShots:
name: "Hits Dealt with Combat Drones"
description: "The total number of hits made to other players using combat drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterDroneAmount:
name: "Damage Dealt with Fighter Drones"
description: "The total amount damage dealt to other players using fighter drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterDroneNumShots:
name: "Hits Dealt with Fighter Drones"
description: "The total number of hits made to other players using fighter drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterBomberAmount:
name: "Damage Dealt with Fighter Drones"
description: "The total amount damage dealt to other players using fighter bombers"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterBomberNumShots:
name: "Hits Dealt with Fighter Drones"
description: "The total number of hits made to other players using fighter bombers"
tags: ['damageDone','pvp']
combatDamageToPlayersBombAmount:
name: "Damage Dealt with Bombs"
description: "The total amount damage dealt to other players using bombs"
tags: ['damageDone','pvp']
combatDamageToPlayersBombNumShots:
name: "Hits Dealt with Bombs"
description: "The total number of hits made to other players using bombs"
tags: ['damageDone','pvp']
combatDamageToPlayersEnergyAmount:
name: "Damage Dealt with Lasers"
description: "The total amount damage dealt to other players using laser turrets"
tags: []
combatDamageToPlayersEnergyNumShots:
name: "Number of Laser Shots"
description: "The total number of shots made with laser turrets"
tags: []
combatDamageToPlayersHybridAmount:
name: "Damage Dealt with Hybrids"
description: "The total amount damage dealt to other players using hybrid turrets"
tags: []
combatDamageToPlayersHybridNumShots:
name: "Number of Hybrid Shots"
description: "The total number of shots made with hybrid turrets"
tags: []
combatDamageToPlayersMissileAmount:
name: "Damage Dealt with Missiles"
description: "The total amount damage dealt to other players using missile launchers"
tags: []
combatDamageToPlayersMissileNumShots:
name: "Number of Missile Shots"
description: "The total number of shots made with missile launchers"
tags: []
combatDamageToPlayersProjectileAmount:
name: "Damage Dealt with Projectiles"
description: "The total amount damage dealt to other players using projectile turrets"
tags: []
combatDamageToPlayersProjectileNumShots:
name: "Number of Projectile Shots"
description: "The total number of shots made with projectile turrets"
tags: []
combatDamageToPlayersSmartBombAmount:
name: "Damage Dealth with Smart Bombs"
description: "The total amount damage dealt to other players using smart bombs"
tags: []
combatDamageToPlayersSmartBombNumShots:
name: "Number of Smart Bomb Hits"
description: "The total number of hits made with smart bombs"
tags: []
combatDamageToPlayersStructureAmount:
description: "REMOVE: Always 0...#wellshit"
disabled: true
tags: []
combatDamageToPlayersStructureNumShots:
description: "REMOVE: Always 0...#wellshit"
disabled: true
tags: []
combatDamageToPlayersSuperAmount:
name: "Damage Dealth with Doomsdays"
description: "The total amount of damage dealt using doomsday devices"
tags: []
combatDamageToPlayersSuperNumShots:
name: "Number of Doomsday Shots"
description: "The total number of shots made with doomsday devices"
tags: []
combatDuelRequested:
names: "Duel Requests"
description: "The total number of times the character requested a duel against another player"
tags: []
combatNpcFlagSet:
names: "Aggressed against NPCs"
description: "The number of times aggression flag was set against NPCs"
tags: []
combatPvpFlagSet:
name: "Aggressed against Players"
description: "The number of times aggression flag was set against Players"
tags: []
combatRepairArmorByRemoteAmount:
name: "Armor Reps Received"
description: "The total amount received from remote armor repairers"
tags: []
combatRepairArmorRemoteAmount:
name: "Armor Reps Given"
description: "The total amount repaired using remote armor repairers"
tags: []
combatRepairArmorSelfAmount:
name: "Armor Self Repped"
description: "The total amount repaired using local armor repairers"
tags: []
combatRepairCapacitorByRemoteAmount:
name: "Energy Transfer Received"
description: "The total amount of energy received from energy transfers"
tags: []
combatRepairCapacitorRemoteAmount:
name: "Energy Transfer Given"
description: "The total amount of energy sent using energy tranfers"
tags: []
combatRepairHullByRemoteAmount:
name: "Hull Reps Received"
description: "The total amount received from remote hull repairers"
tags: []
combatRepairHullRemoteAmount:
name: "Hull Reps Given"
description: "The total amount repaired using remote hull repairers"
tags: []
combatRepairHullSelfAmount:
name: "Hull Self Repped"
description: "The total amount repaired using local hull repairers"
tags: []
combatRepairShieldByRemoteAmount:
name: "Shield Reps Receieved"
description: "The total amount received from remote shield transfers"
tags: []
combatRepairShieldRemoteAmount:
name: "Shield Reps Given"
description: "The total amount repaired using remote shield transfers"
tags: []
combatRepairShieldSelfAmount:
name: "Shield Self Repped"
description: "The total amount repaired using local shield transfers"
tags: []
combatSelfDestructs:
name: "Self Destructs"
description: "The number of successful self destructs"
tags: []
combatWarpScramblePC:
name: "Scrammed Player"
description: "The number of times warp scrambled other players"
tags: []
combatWarpScrambledbyNPC:
name: "Scrammed by NPC"
description: "The number of times warp scrambled by NPCs"
tags: []
combatWarpScrambledbyPC:
name: "Scrammed by Player"
description: "The number of times warp scrambled by other players"
tags: []
combatWebifiedbyNPC:
name: "Webbed Player"
description: "The number of times webbed other players"
tags: []
combatWebifiedbyPC:
name: "Webbed by NPCs"
description: "The number of times webbed by NPCs"
tags: []
combatWebifyingPC:
name: "Webbed by Player"
description: "The number of times webbed by other players"
tags: []
genericConeScans:
name: "Times Dscanned"
description: "The number of directional scans made"
tags: []
genericRequestScans:
name: "Probe Scans"
description: "The number of probe scans made"
tags: []
industryHackingSuccesses:
name: "Data Cans Hacked"
description: "The number of successful hacking attempts"
tags: []
industryJobsCompletedCopyBlueprint:
name: "Blueprints Copied"
description: "The number of copy jobs completed"
tags: []
industryJobsCompletedInvention:
name: "Invention Jobs"
description: "The number of invention jobs completed"
tags: []
industryJobsCompletedManufacture:
name: "Manufacturing Jobs"
description: "The total number of manufacturing jobs completed"
tags: []
industryJobsCompletedManufactureAsteroidQuantity:
name: "Mineral Compression Jobs"
description: "The total units of"
tags: []
industryJobsCompletedManufactureChargeQuantity:
name: "Charges Produced"
description: "The total units of charges produced"
tags: []
industryJobsCompletedManufactureCommodityQuantity:
name: "Commodities Produced"
description: "The total units of commodities produced"
tags: []
industryJobsCompletedManufactureDeployableQuantity:
name: "Deployables Produced"
description: "The total units of deployables produced"
tags: []
industryJobsCompletedManufactureDroneQuantity:
name: "Drones Produced"
description: "The total units of drones produced"
tags: []
industryJobsCompletedManufactureImplantQuantity:
name: "Implants Produced"
description: "The total units of implants produced"
tags: []
industryJobsCompletedManufactureModuleQuantity:
name: "Modules Produced"
description: "The total units of modules produced"
tags: []
industryJobsCompletedManufactureShipQuantity:
name: "Ships Produced"
description: "The total units of ships produced"
tags: []
industryJobsCompletedManufactureStructureQuantity:
name: "Structures Produced"
description: "The total units of structures produced"
tags: []
industryJobsCompletedManufactureSubsystemQuantity:
name: "Subsystems Produced"
description: "The total units of subsystems produced"
tags: []
industryJobsCompletedMaterialProductivity:
name: "ME Jobs"
description: "The number of material efficiency jobs completed"
tags: []
industryJobsCompletedReverseEngineering:
name: "Reverse Engineering Jobs"
description: "The number of reverse engineering jobs completed (merged into invention as of ?)"
tags: []
industryJobsCompletedTimeProductivity:
name: "TE Jobs"
description: "The number of production efficiency jobs completed"
tags: []
inventoryTrashItemQuantity:
# stack size or number of times used?
name: "Items Trashed"
description: "The number of items trashed"
tags: []
marketISKGained:
name: "ISK Received from Sell Orders"
description: "The amount of isk from sell-orders"
tags: []
marketISKSpent:
name: "ISK Spent on Buy Orders"
description: "The amount of isk from buy-orders"
tags: []
marketAcceptContractsCourier:
name: "Courier Contracts Accepted"
description: "The number of times accepted a courier contract"
tags: []
marketAcceptContractsItemExchange:
name: "Item Contracts Accepted"
description: "The number of times accepted an item exchange contract"
tags: []
marketBuyOrdersPlaced:
name: "Buy Orders Placed"
description: "The number of buy orders placed"
tags: []
marketSellOrdersPlaced:
name: "Sell Orders Placed"
description: "The number of sell orders placed"
tags: []
marketCancelMarketOrder:
name: "Orders Cancelled"
description: "The number of orders cancelled"
tags: []
marketCreateContractsTotal:
# personal only? corp contracts as well?
name: "Contracts Created"
description: "The number of contracts created"
tags: []
marketDeliverCourierContract:
name: "Courier Contracts Delivered"
description: "The number of courier contracts delivered"
tags: []
marketModifyMarketOrder:
name: "Orders Modified"
description: "The number of modifications made to market orders"
tags: []
miningOreArkonor:
name: "Arkanor Mined"
description: "The total amount of Arkonor mined (units)"
tags: []
miningOreBistot:
name: "Bistot Mined"
description: "The total amount of Bistot mined (units)"
tags: []
miningOreCrokite:
name: "Crokite Mined"
description: "The total amount of Crokite mined (units)"
tags: []
miningOreDarkOchre:
name: "Dark Ochre Mined"
description: "The total amount of DarkOchre mined (units)"
tags: []
miningOreGneiss:
name: "Gneiss Mined"
description: "The total amount of Gneiss mined (units)"
tags: []
miningOreHarvestableCloud:
name: "Gas Huffed"
description: "The total amount of HarvestableCloud mined (units)"
tags: []
miningOreHedbergite:
name: "Hedbergite Mined"
description: "The total amount of Hedbergite mined (units)"
tags: []
miningOreHemorphite:
name: "Hemorphite Mined"
description: "The total amount of Hemorphite mined (units)"
tags: []
miningOreIce:
name: "Ice Mined"
description: "The total amount of Ice mined (units)"
tags: []
miningOreJaspet:
name: "Jaspet Mined"
description: "The total amount of Jaspet mined (units)"
tags: []
miningOreKernite:
name: "Kernite Mined"
description: "The total amount of Kernite mined (units)"
tags: []
miningOreMercoxit:
name: "Mercoxit Mined"
description: "The total amount of Mercoxit mined (units)"
tags: []
miningOreOmber:
name: "Omber Mined"
description: "The total amount of Omber mined (units)"
tags: []
miningOrePlagioclase:
name: "Plagioclase Mined"
description: "The total amount of Plagioclase mined (units)"
tags: []
miningOrePyroxeres:
name: "Pyroxeres Mined"
description: "The total amount of Pyroxeres mined (units)"
tags: []
miningOreScordite:
name: "Scordite Mined"
description: "The total amount of Scordite mined (units)"
tags: []
miningOreSpodumain:
name: "Spodumain Mined"
description: "The total amount of Spodumain mined (units)"
tags: []
miningOreVeldspar:
name: "Veldspar Mined"
description: "The total amount of Veldspar mined (units)"
tags: []
moduleActivationsCloakingDevice:
name: "Times Cloaked"
description: "The total number of cloak activations"
tags: []
moduleActivationsCynosuralField:
name: "Cynos Activated"
description: "The total number of cyno activations"
tags: []
moduleActivationsRemoteSensorSamper:
name: "Sensor Damps Used"
description: "The total number of sensor dampener activations"
tags: []
moduleActivationsECM:
name: "ECM Activations"
description: "The total number of ECM activations"
tags: []
moduleActivationsTargetPainter:
name: "Target Painter Activations"
description: "The total number of target painter activations"
tags: []
moduleActivationsEnergyVampire:
name: "Energy Vampire Activations"
description: "The total number of energy vampire activations"
tags: []
moduleActivationsGangCoordinator:
name: "Links Activated"
description: "The total number of gang link module activations"
tags: []
moduleOverload:
name: "Modules Overloaded"
description: "The number of times a module was overloaded"
tags: []
socialAddContactBad:
name: "Added Contact with Bad Standing"
description: "The number of contacts added with bad standings"
tags: []
socialAddContactGood:
name: "Added Contact with Good Standing"
description: "The number of contacts added with good standings"
tags: []
socialAddContactHigh:
name: "Added Contact with High Standing"
description: "The number of contacts added with high standings"
tags: []
socialAddContactHorrible:
name: "Added Contact with Horrible Standing"
description: "The number of contacts added with horrible standings"
tags: []
socialAddContactNeutral:
name: "Added Contact with Neutral Standing"
description: "The number of contacts added with neutral standings"
tags: []
socialAddedAsContactBad:
name: "Added as Bad Contact by Another Player"
description: "The number of times added as a contact with bad standings"
tags: []
socialAddedAsContactGood:
name: "Added as Good Contact by Another Player"
description: "The number of times added as a contact with good standings"
tags: []
socialAddedAsContactHigh:
name: "Added as High Contact by Another Player"
description: "The number of times added as a contact with high standings"
tags: []
socialAddedAsContactHorrible:
name: "Added as Horrible Contact by Another Player"
description: "The number of times added as a contact with horrible standings"
tags: []
socialAddedAsContactNeutral:
name: "Added as Neutral Contact by Another Player"
description: "The number of times added as a contact with neutral standings"
tags: []
socialChatTotalMessageLength:
name: "Total Length of All Chat"
description: "The total length of all chat messages -NSA"
tags: []
socialDirectTrades:
name: "Direct Trades"
description: "The number of direct trades made"
tags: []
socialFleetJoins:
name: "Fleets Joined"
description: "The number of fleets joined"
tags: []
socialFleetBroadcasts:
name: "Fleet Broadcasts"
description: "The number of broadcasts made in fleet"
tags: []
socialMailsReceived:
name: "<NAME> Received"
description: "The number of mails received -NSA"
tags: []
socialMailsSent:
name: "<NAME> Sent"
description: "The number of mails sent -NSA"
tags: []
travelAccelerationGateActivations:
name: "Acceleration Gates Activated"
description: "The number of acceleration gates activated"
tags: []
travelAlignTo:
name: "Times Aligned"
description: "The number of times ship alignment was made"
tags: []
travelDistanceWarpedHighSec:
name: "AU Traveled in High Sec"
description: "The total distance(AU) traveled in warp while in high security space"
tags: []
travelDistanceWarpedLowSec:
name: "AU Traveled in Low Sec"
description: "The total distance(AU) traveled in warp while in low security space"
tags: []
travelDistanceWarpedNullSec:
name: "AU Traveled in Null Sec"
description: "The total distance(AU) traveled in warp while in null security space"
tags: []
travelDistanceWarpedWormhole:
name: "AU Traveled in Wormholes"
description: "The total distance(AU) traveled in warp while in wormhole space"
tags: []
travelWarpsHighSec:
name: "Initiated Warp in High Sec"
description: "The total number of warps initiated while in high security space"
tags: []
travelWarpsLowSec:
name: "Initiated Warp in Low Sec"
description: "The total number of warps initiated while in low security space"
tags: []
travelWarpsNullSec:
name: "Initiated Warp in Null Sec"
description: "The total number of warps initiated while in null security space"
tags: []
travelWarpsWormhole:
name: "Initiated Warp in Wormholes"
description: "The total number of warps initiated while in wormhole space"
tags: []
travelWarpsToBookmark:
name: "Initiated Warp to Bookmark"
description: "The total number of warps initiated to a bookmark"
tags: []
travelWarpsToCelestial:
name: "Initiated Warp to Celestial"
description: "The total number of warps initiated to a celestial"
tags: []
travelWarpsToFleetMember:
name: "Initiated Warp to Fleet Member"
description: "The total number of warps initiated to a fleet member"
tags: []
travelWarpsToScanResult:
name: "Initiated Warp to Scan Result"
description: "The total number of warps initiated to a scan result"
tags: []
# derived fields
combatKillsTotal:
name: 'Total Kills'
tags: ['pvp']
combatDeathsTotal:
name: 'Total Deaths'
tags: ['pvp']
iskSpentPercent:
name: 'Percent of Income Spent, Overall'
tags: ['general']
units: 'percent'
kdRatioTotal:
name: 'Kill/Death Ratio'
tags: ['pvp']
averageSessionLength:
name: 'Average Session Length'
tags: ['general']
units: 'minutes'
module.exports = CharacterStats
| true | _ = require 'lodash'
class CharacterStats
constructor: (stats) ->
for key, val of stats
@[key] = val
@secSuffixes = [
'HighSec'
'LowSec'
'NullSec'
'Wormhole'
]
@calcDerived()
# not tested, may not be useful since names are all over the place
#getByPrefix: (prefix) ->
# return _.map @, (key, val) -> {key: key, val: val}
total: (prefix) ->
statNames = _.map @secSuffixes, (suffix) -> prefix + suffix
return _.reduce statNames, ((sum, stat) => sum + @[stat]), 0
percent: (prefix, suffix) ->
total = @total prefix
pct = @[prefix + suffix] / total
return pct
perMinute: (stat) ->
if @characterMinutes
return @[stat] / @characterMinutes
else
return null
perHour: (stat) ->
perMinute = @perMinute(stat)
if perMinute
return perMinute * 60
else
return null
get: (stat) ->
return @[stat]
calcDerived: ->
# fix a few stats
@iskOut = -(@iskOut)
# derive some stats
@averageSessionLength = @characterMinutes / @characterSessionsStarted
@combatKillsTotal = @total 'combatKills'
@combatDeathsTotal = @total 'combatDeaths'
@kdRatioTotal = @combatKillsTotal / @combatDeathsTotal
@combatDeathsPodTotal = @combatDeathsPodHighSec +
@combatDeathsPodLowSec +
@combatDeathsPodNullSec +
@combatDeathsPodWormhole
@combatKillsPodTotal = @combatKillsPodHighSec +
@combatKillsPodLowSec +
@combatKillsPodNullSec +
@combatKillsPodWormhole
@kdRatioHigh = @combatKillsHighSec / @combatDeathsHighSec
@kdRatioLow = @combatKillsLowSec / @combatDeathsLowSec
@kdRatioNull = @combatKillsNullSec / @combatDeathsNullSec
@kdRatioWormhole = @combatKillsWormhole / @combatDeathsWormhole
@travelDistanceWarpedTotal = @total 'travelDistanceWarped'
@totalDamageDealt = @combatDamageToPlayersBombAmount +
@combatDamageToPlayersCombatDroneAmount +
@combatDamageToPlayersEnergyAmount +
@combatDamageToPlayersFighterBomberAmount +
@combatDamageToPlayersFighterDroneAmount +
@combatDamageToPlayersHybridAmount +
@combatDamageToPlayersMissileAmount +
@combatDamageToPlayersProjectileAmount +
@combatDamageToPlayersSmartBombAmount +
@combatDamageToPlayersSuperAmount
@iskSpentPercent = 100 * (@iskOut / @iskIn)
metadata:
daysOfActivity:
name: "Active Days"
description: "The number of days in the period with recorded activity"
tags: ['general']
characterMinutes:
name: "Minutes Logged In"
description: "The number of minutes logged in as this character"
tags: ['general']
characterSessionsStarted:
name: "Logins"
description: "The number of times the character has logged into the game"
tags: ['general']
iskIn:
name: "ISK Earned"
description: "The total amount of positive ISK transactions in the character wallet"
tags: ['general']
iskOut:
name: "ISK Spent"
description: "The total amount of negative ISK transactions in the character wallet"
tags: ['general']
travelJumpsStargateHighSec:
name: "High Sec Jumps"
description: "The number of jumps through a gate in high security space"
tags: ['travel']
travelJumpsStargateLowSec:
name: "Low Sec Jumps"
description: "The number of jumps through a gate in low security space"
tags: ['travel']
travelJumpsStargateNullSec:
name: "Null Sec Jumps"
description: "The number of jumps through a gate in null security space"
tags: ['travel']
travelJumpsWormhole:
name: "Wormhole Jumps"
description: "The number of jumps through a wormhole"
tags: ['travel']
travelDocksHighSec:
name: "Docked in High Sec"
description: "The number of docks in high security space"
tags: ['travel']
travelDocksLowSec:
name: "Docked in Low Sec"
description: "The number of docks in low security space"
tags: ['travel']
travelDocksNullSec:
name: "Docked in Null Sec"
description: "The number of docks in null security space"
tags: ['travel']
pveMissionsSucceeded:
name: "Missions Completed"
description: "The number of missions completed"
tags: ['pve']
pveMissionsSucceededEpicArc:
name: "Epic Arcs Completed"
description: "The number of epic arc missions completed"
tags: ['pve']
combatKillsHighSec:
name: "High Sec Kills"
description: "The number of kills in high security space"
tags: ['pvp']
combatKillsLowSec:
name: "Low Sec Kills"
description: "The number of kills in low security space"
tags: ['pvp']
combatKillsNullSec:
name: "Null Sec Kills"
description: "The number of kills in null security space"
tags: ['pvp']
combatKillsWormhole:
name: "Wormhole Kills"
description: "The number of kills in wormhole space"
tags: ['pvp']
combatKillsPodTotal:
name: "Pods Killed"
description: "The total number of capsule kills (final blows)"
tags: ['pvp']
combatDeathsHighSec:
name: "High Sec Deaths"
description: "The number of deaths in high security space"
tags: ['deaths']
combatDeathsLowSec:
name: "Low Sec Deaths"
description: "The number of deaths in low security space"
tags: ['deaths']
combatDeathsNullSec:
name: "Null Sec Deaths"
description: "The number of deaths in null security space"
tags: ['deaths']
combatDeathsWormhole:
name: "Wormhole Deaths"
description: "The number of deaths in wormhole space"
tags: ['deaths']
combatDeathsPodTotal:
name: "Times Podded"
description: "The total number of capsule deaths (times podded)"
tags: ['deaths']
combatKillsAssists:
name: "Assists"
description: "The total number of kill assists"
tags: ['pvp']
combatCapDrainedbyPC:
name: "Cap Drained by Players"
description: "The amount of the characters capacitor that has been drained by other player"
tags: ['pvp']
combatCapDrainingPC:
name: "Cap Drained from Players"
description: "The amount of capacitor the character has drained from other players"
tags: ['pvp']
combatCriminalFlagSet:
name: "Times Criminal Flagged"
description: "The number of times the character has had the crimewatch criminal flag set"
tags: ['pvp']
combatDamageFromNPCsAmount:
name: "Damage Taken from NPCs"
description: "The total amount of damage taken from NPCs."
tags: ['pve']
combatDamageFromNPCsNumShots:
name: "Times Shot by NPCs"
description: "The total number of times NPCs have shot the character."
tags: ['pve']
combatDamageFromPlayersBombAmount:
name: "Damage Taken from Bombs"
description: "The total damage taken from bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersBombNumShots:
name: "Hits Taken from Bombs"
description: "The total number of hits taken from bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersEnergyAmount:
name: "Damage Taken from Lasers"
description: "The total damage taken from laser turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersEnergyNumShots:
name: "Hits Taken from Lasers"
description: "The total number of hits taken from laser turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersCombatDroneAmount:
name: "Damage Taken from Combat Drones"
description: "The total damage taken from combat drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersCombatDroneNumShots:
name: "Hits Taken from Combat Drones"
description: "The total number of hits taken from combat drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterBomberAmount:
name: "Damage Taken from Fighter Bombers"
description: "The total damage taken from fighter bombers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterBomberNumShots:
name: "Hits Taken from Fighter Bombers"
description: "The total number of hits taken from fighter bombers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterDroneAmount:
name: "Damage Taken from Fighter Drones"
description: "The total damage taken from fighter drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersFighterDroneNumShots:
name: "Hits Taken from Fighter Drones"
description: "The total number of hits taken from fighter drones"
tags: ['damageTaken','pvp']
combatDamageFromPlayersHybridAmount:
name: "Damage Taken from Hybrids"
description: "The total damage taken from hybrid turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersHybridNumShots:
name: "Hits Taken from Hybrids"
description: "The total number of hits taken from hybrid turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersMissileAmount:
name: "Damage Taken from Missiles"
description: "The total damage taken from missile launchers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersMissileNumShots:
name: "Hits Taken from Missiles"
description: "The total number of hits taken from missile launchers"
tags: ['damageTaken','pvp']
combatDamageFromPlayersProjectileAmount:
name: "Damage Taken from Projectiles"
description: "The total damage taken from projectile turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersProjectileNumShots:
name: "Hits Taken from Projectiles"
description: "The total number of hits taken from projectile turrets"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSmartBombAmount:
name: "Damage Taken from Smart Bombs"
description: "The total damage taken from smart bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSmartBombNumShots:
name: "Hits Taken from Smart Bombs"
description: "The total number of hits taken from smart bombs"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSuperAmount:
name: "Damage Taken from Doomsdays"
description: "The total damage taken from doomsday devices"
tags: ['damageTaken','pvp']
combatDamageFromPlayersSuperNumShots:
name: "Hits Taken from Doomsdays"
description: "The total number of hits taken from doomsday devices"
tags: ['damageDone','pvp']
combatDamageToPlayersCombatDroneAmount:
name: "Damage Dealt with Combat Drones"
description: "The total amount damage dealt to other players using combat drones"
tags: ['damageDone','pvp']
combatDamageToPlayersCombatDroneNumShots:
name: "Hits Dealt with Combat Drones"
description: "The total number of hits made to other players using combat drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterDroneAmount:
name: "Damage Dealt with Fighter Drones"
description: "The total amount damage dealt to other players using fighter drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterDroneNumShots:
name: "Hits Dealt with Fighter Drones"
description: "The total number of hits made to other players using fighter drones"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterBomberAmount:
name: "Damage Dealt with Fighter Drones"
description: "The total amount damage dealt to other players using fighter bombers"
tags: ['damageDone','pvp']
combatDamageToPlayersFighterBomberNumShots:
name: "Hits Dealt with Fighter Drones"
description: "The total number of hits made to other players using fighter bombers"
tags: ['damageDone','pvp']
combatDamageToPlayersBombAmount:
name: "Damage Dealt with Bombs"
description: "The total amount damage dealt to other players using bombs"
tags: ['damageDone','pvp']
combatDamageToPlayersBombNumShots:
name: "Hits Dealt with Bombs"
description: "The total number of hits made to other players using bombs"
tags: ['damageDone','pvp']
combatDamageToPlayersEnergyAmount:
name: "Damage Dealt with Lasers"
description: "The total amount damage dealt to other players using laser turrets"
tags: []
combatDamageToPlayersEnergyNumShots:
name: "Number of Laser Shots"
description: "The total number of shots made with laser turrets"
tags: []
combatDamageToPlayersHybridAmount:
name: "Damage Dealt with Hybrids"
description: "The total amount damage dealt to other players using hybrid turrets"
tags: []
combatDamageToPlayersHybridNumShots:
name: "Number of Hybrid Shots"
description: "The total number of shots made with hybrid turrets"
tags: []
combatDamageToPlayersMissileAmount:
name: "Damage Dealt with Missiles"
description: "The total amount damage dealt to other players using missile launchers"
tags: []
combatDamageToPlayersMissileNumShots:
name: "Number of Missile Shots"
description: "The total number of shots made with missile launchers"
tags: []
combatDamageToPlayersProjectileAmount:
name: "Damage Dealt with Projectiles"
description: "The total amount damage dealt to other players using projectile turrets"
tags: []
combatDamageToPlayersProjectileNumShots:
name: "Number of Projectile Shots"
description: "The total number of shots made with projectile turrets"
tags: []
combatDamageToPlayersSmartBombAmount:
name: "Damage Dealth with Smart Bombs"
description: "The total amount damage dealt to other players using smart bombs"
tags: []
combatDamageToPlayersSmartBombNumShots:
name: "Number of Smart Bomb Hits"
description: "The total number of hits made with smart bombs"
tags: []
combatDamageToPlayersStructureAmount:
description: "REMOVE: Always 0...#wellshit"
disabled: true
tags: []
combatDamageToPlayersStructureNumShots:
description: "REMOVE: Always 0...#wellshit"
disabled: true
tags: []
combatDamageToPlayersSuperAmount:
name: "Damage Dealth with Doomsdays"
description: "The total amount of damage dealt using doomsday devices"
tags: []
combatDamageToPlayersSuperNumShots:
name: "Number of Doomsday Shots"
description: "The total number of shots made with doomsday devices"
tags: []
combatDuelRequested:
names: "Duel Requests"
description: "The total number of times the character requested a duel against another player"
tags: []
combatNpcFlagSet:
names: "Aggressed against NPCs"
description: "The number of times aggression flag was set against NPCs"
tags: []
combatPvpFlagSet:
name: "Aggressed against Players"
description: "The number of times aggression flag was set against Players"
tags: []
combatRepairArmorByRemoteAmount:
name: "Armor Reps Received"
description: "The total amount received from remote armor repairers"
tags: []
combatRepairArmorRemoteAmount:
name: "Armor Reps Given"
description: "The total amount repaired using remote armor repairers"
tags: []
combatRepairArmorSelfAmount:
name: "Armor Self Repped"
description: "The total amount repaired using local armor repairers"
tags: []
combatRepairCapacitorByRemoteAmount:
name: "Energy Transfer Received"
description: "The total amount of energy received from energy transfers"
tags: []
combatRepairCapacitorRemoteAmount:
name: "Energy Transfer Given"
description: "The total amount of energy sent using energy tranfers"
tags: []
combatRepairHullByRemoteAmount:
name: "Hull Reps Received"
description: "The total amount received from remote hull repairers"
tags: []
combatRepairHullRemoteAmount:
name: "Hull Reps Given"
description: "The total amount repaired using remote hull repairers"
tags: []
combatRepairHullSelfAmount:
name: "Hull Self Repped"
description: "The total amount repaired using local hull repairers"
tags: []
combatRepairShieldByRemoteAmount:
name: "Shield Reps Receieved"
description: "The total amount received from remote shield transfers"
tags: []
combatRepairShieldRemoteAmount:
name: "Shield Reps Given"
description: "The total amount repaired using remote shield transfers"
tags: []
combatRepairShieldSelfAmount:
name: "Shield Self Repped"
description: "The total amount repaired using local shield transfers"
tags: []
combatSelfDestructs:
name: "Self Destructs"
description: "The number of successful self destructs"
tags: []
combatWarpScramblePC:
name: "Scrammed Player"
description: "The number of times warp scrambled other players"
tags: []
combatWarpScrambledbyNPC:
name: "Scrammed by NPC"
description: "The number of times warp scrambled by NPCs"
tags: []
combatWarpScrambledbyPC:
name: "Scrammed by Player"
description: "The number of times warp scrambled by other players"
tags: []
combatWebifiedbyNPC:
name: "Webbed Player"
description: "The number of times webbed other players"
tags: []
combatWebifiedbyPC:
name: "Webbed by NPCs"
description: "The number of times webbed by NPCs"
tags: []
combatWebifyingPC:
name: "Webbed by Player"
description: "The number of times webbed by other players"
tags: []
genericConeScans:
name: "Times Dscanned"
description: "The number of directional scans made"
tags: []
genericRequestScans:
name: "Probe Scans"
description: "The number of probe scans made"
tags: []
industryHackingSuccesses:
name: "Data Cans Hacked"
description: "The number of successful hacking attempts"
tags: []
industryJobsCompletedCopyBlueprint:
name: "Blueprints Copied"
description: "The number of copy jobs completed"
tags: []
industryJobsCompletedInvention:
name: "Invention Jobs"
description: "The number of invention jobs completed"
tags: []
industryJobsCompletedManufacture:
name: "Manufacturing Jobs"
description: "The total number of manufacturing jobs completed"
tags: []
industryJobsCompletedManufactureAsteroidQuantity:
name: "Mineral Compression Jobs"
description: "The total units of"
tags: []
industryJobsCompletedManufactureChargeQuantity:
name: "Charges Produced"
description: "The total units of charges produced"
tags: []
industryJobsCompletedManufactureCommodityQuantity:
name: "Commodities Produced"
description: "The total units of commodities produced"
tags: []
industryJobsCompletedManufactureDeployableQuantity:
name: "Deployables Produced"
description: "The total units of deployables produced"
tags: []
industryJobsCompletedManufactureDroneQuantity:
name: "Drones Produced"
description: "The total units of drones produced"
tags: []
industryJobsCompletedManufactureImplantQuantity:
name: "Implants Produced"
description: "The total units of implants produced"
tags: []
industryJobsCompletedManufactureModuleQuantity:
name: "Modules Produced"
description: "The total units of modules produced"
tags: []
industryJobsCompletedManufactureShipQuantity:
name: "Ships Produced"
description: "The total units of ships produced"
tags: []
industryJobsCompletedManufactureStructureQuantity:
name: "Structures Produced"
description: "The total units of structures produced"
tags: []
industryJobsCompletedManufactureSubsystemQuantity:
name: "Subsystems Produced"
description: "The total units of subsystems produced"
tags: []
industryJobsCompletedMaterialProductivity:
name: "ME Jobs"
description: "The number of material efficiency jobs completed"
tags: []
industryJobsCompletedReverseEngineering:
name: "Reverse Engineering Jobs"
description: "The number of reverse engineering jobs completed (merged into invention as of ?)"
tags: []
industryJobsCompletedTimeProductivity:
name: "TE Jobs"
description: "The number of production efficiency jobs completed"
tags: []
inventoryTrashItemQuantity:
# stack size or number of times used?
name: "Items Trashed"
description: "The number of items trashed"
tags: []
marketISKGained:
name: "ISK Received from Sell Orders"
description: "The amount of isk from sell-orders"
tags: []
marketISKSpent:
name: "ISK Spent on Buy Orders"
description: "The amount of isk from buy-orders"
tags: []
marketAcceptContractsCourier:
name: "Courier Contracts Accepted"
description: "The number of times accepted a courier contract"
tags: []
marketAcceptContractsItemExchange:
name: "Item Contracts Accepted"
description: "The number of times accepted an item exchange contract"
tags: []
marketBuyOrdersPlaced:
name: "Buy Orders Placed"
description: "The number of buy orders placed"
tags: []
marketSellOrdersPlaced:
name: "Sell Orders Placed"
description: "The number of sell orders placed"
tags: []
marketCancelMarketOrder:
name: "Orders Cancelled"
description: "The number of orders cancelled"
tags: []
marketCreateContractsTotal:
# personal only? corp contracts as well?
name: "Contracts Created"
description: "The number of contracts created"
tags: []
marketDeliverCourierContract:
name: "Courier Contracts Delivered"
description: "The number of courier contracts delivered"
tags: []
marketModifyMarketOrder:
name: "Orders Modified"
description: "The number of modifications made to market orders"
tags: []
miningOreArkonor:
name: "Arkanor Mined"
description: "The total amount of Arkonor mined (units)"
tags: []
miningOreBistot:
name: "Bistot Mined"
description: "The total amount of Bistot mined (units)"
tags: []
miningOreCrokite:
name: "Crokite Mined"
description: "The total amount of Crokite mined (units)"
tags: []
miningOreDarkOchre:
name: "Dark Ochre Mined"
description: "The total amount of DarkOchre mined (units)"
tags: []
miningOreGneiss:
name: "Gneiss Mined"
description: "The total amount of Gneiss mined (units)"
tags: []
miningOreHarvestableCloud:
name: "Gas Huffed"
description: "The total amount of HarvestableCloud mined (units)"
tags: []
miningOreHedbergite:
name: "Hedbergite Mined"
description: "The total amount of Hedbergite mined (units)"
tags: []
miningOreHemorphite:
name: "Hemorphite Mined"
description: "The total amount of Hemorphite mined (units)"
tags: []
miningOreIce:
name: "Ice Mined"
description: "The total amount of Ice mined (units)"
tags: []
miningOreJaspet:
name: "Jaspet Mined"
description: "The total amount of Jaspet mined (units)"
tags: []
miningOreKernite:
name: "Kernite Mined"
description: "The total amount of Kernite mined (units)"
tags: []
miningOreMercoxit:
name: "Mercoxit Mined"
description: "The total amount of Mercoxit mined (units)"
tags: []
miningOreOmber:
name: "Omber Mined"
description: "The total amount of Omber mined (units)"
tags: []
miningOrePlagioclase:
name: "Plagioclase Mined"
description: "The total amount of Plagioclase mined (units)"
tags: []
miningOrePyroxeres:
name: "Pyroxeres Mined"
description: "The total amount of Pyroxeres mined (units)"
tags: []
miningOreScordite:
name: "Scordite Mined"
description: "The total amount of Scordite mined (units)"
tags: []
miningOreSpodumain:
name: "Spodumain Mined"
description: "The total amount of Spodumain mined (units)"
tags: []
miningOreVeldspar:
name: "Veldspar Mined"
description: "The total amount of Veldspar mined (units)"
tags: []
moduleActivationsCloakingDevice:
name: "Times Cloaked"
description: "The total number of cloak activations"
tags: []
moduleActivationsCynosuralField:
name: "Cynos Activated"
description: "The total number of cyno activations"
tags: []
moduleActivationsRemoteSensorSamper:
name: "Sensor Damps Used"
description: "The total number of sensor dampener activations"
tags: []
moduleActivationsECM:
name: "ECM Activations"
description: "The total number of ECM activations"
tags: []
moduleActivationsTargetPainter:
name: "Target Painter Activations"
description: "The total number of target painter activations"
tags: []
moduleActivationsEnergyVampire:
name: "Energy Vampire Activations"
description: "The total number of energy vampire activations"
tags: []
moduleActivationsGangCoordinator:
name: "Links Activated"
description: "The total number of gang link module activations"
tags: []
moduleOverload:
name: "Modules Overloaded"
description: "The number of times a module was overloaded"
tags: []
socialAddContactBad:
name: "Added Contact with Bad Standing"
description: "The number of contacts added with bad standings"
tags: []
socialAddContactGood:
name: "Added Contact with Good Standing"
description: "The number of contacts added with good standings"
tags: []
socialAddContactHigh:
name: "Added Contact with High Standing"
description: "The number of contacts added with high standings"
tags: []
socialAddContactHorrible:
name: "Added Contact with Horrible Standing"
description: "The number of contacts added with horrible standings"
tags: []
socialAddContactNeutral:
name: "Added Contact with Neutral Standing"
description: "The number of contacts added with neutral standings"
tags: []
socialAddedAsContactBad:
name: "Added as Bad Contact by Another Player"
description: "The number of times added as a contact with bad standings"
tags: []
socialAddedAsContactGood:
name: "Added as Good Contact by Another Player"
description: "The number of times added as a contact with good standings"
tags: []
socialAddedAsContactHigh:
name: "Added as High Contact by Another Player"
description: "The number of times added as a contact with high standings"
tags: []
socialAddedAsContactHorrible:
name: "Added as Horrible Contact by Another Player"
description: "The number of times added as a contact with horrible standings"
tags: []
socialAddedAsContactNeutral:
name: "Added as Neutral Contact by Another Player"
description: "The number of times added as a contact with neutral standings"
tags: []
socialChatTotalMessageLength:
name: "Total Length of All Chat"
description: "The total length of all chat messages -NSA"
tags: []
socialDirectTrades:
name: "Direct Trades"
description: "The number of direct trades made"
tags: []
socialFleetJoins:
name: "Fleets Joined"
description: "The number of fleets joined"
tags: []
socialFleetBroadcasts:
name: "Fleet Broadcasts"
description: "The number of broadcasts made in fleet"
tags: []
socialMailsReceived:
name: "PI:NAME:<NAME>END_PI Received"
description: "The number of mails received -NSA"
tags: []
socialMailsSent:
name: "PI:NAME:<NAME>END_PI Sent"
description: "The number of mails sent -NSA"
tags: []
travelAccelerationGateActivations:
name: "Acceleration Gates Activated"
description: "The number of acceleration gates activated"
tags: []
travelAlignTo:
name: "Times Aligned"
description: "The number of times ship alignment was made"
tags: []
travelDistanceWarpedHighSec:
name: "AU Traveled in High Sec"
description: "The total distance(AU) traveled in warp while in high security space"
tags: []
travelDistanceWarpedLowSec:
name: "AU Traveled in Low Sec"
description: "The total distance(AU) traveled in warp while in low security space"
tags: []
travelDistanceWarpedNullSec:
name: "AU Traveled in Null Sec"
description: "The total distance(AU) traveled in warp while in null security space"
tags: []
travelDistanceWarpedWormhole:
name: "AU Traveled in Wormholes"
description: "The total distance(AU) traveled in warp while in wormhole space"
tags: []
travelWarpsHighSec:
name: "Initiated Warp in High Sec"
description: "The total number of warps initiated while in high security space"
tags: []
travelWarpsLowSec:
name: "Initiated Warp in Low Sec"
description: "The total number of warps initiated while in low security space"
tags: []
travelWarpsNullSec:
name: "Initiated Warp in Null Sec"
description: "The total number of warps initiated while in null security space"
tags: []
travelWarpsWormhole:
name: "Initiated Warp in Wormholes"
description: "The total number of warps initiated while in wormhole space"
tags: []
travelWarpsToBookmark:
name: "Initiated Warp to Bookmark"
description: "The total number of warps initiated to a bookmark"
tags: []
travelWarpsToCelestial:
name: "Initiated Warp to Celestial"
description: "The total number of warps initiated to a celestial"
tags: []
travelWarpsToFleetMember:
name: "Initiated Warp to Fleet Member"
description: "The total number of warps initiated to a fleet member"
tags: []
travelWarpsToScanResult:
name: "Initiated Warp to Scan Result"
description: "The total number of warps initiated to a scan result"
tags: []
# derived fields
combatKillsTotal:
name: 'Total Kills'
tags: ['pvp']
combatDeathsTotal:
name: 'Total Deaths'
tags: ['pvp']
iskSpentPercent:
name: 'Percent of Income Spent, Overall'
tags: ['general']
units: 'percent'
kdRatioTotal:
name: 'Kill/Death Ratio'
tags: ['pvp']
averageSessionLength:
name: 'Average Session Length'
tags: ['general']
units: 'minutes'
module.exports = CharacterStats
|
[
{
"context": "t.svg'\n url: 'https://github.com/hanzoai/hanzo.js'\n }\n {\n ",
"end": 2049,
"score": 0.9996381402015686,
"start": 2042,
"tag": "USERNAME",
"value": "hanzoai"
},
{
"context": "t.svg'\n url: 'https://gith... | data.coffee | hanzo-io/hanzo.ai | 1 | module.exports =
data: {
'@context': 'hanzo.ai/schema'
'@type': 'Website'
header: {
'@type': 'WebsiteHeader'
type: 'complex'
logos: [
{
'@type': 'WebsiteLogo'
image: '/img/logo.svg'
alt: 'Hanzo'
name: ''
url: '/'
}
]
menuCollections: [
{
'@type': 'WebsiteMenuCollection'
menus: [
{
'@type': 'WebsiteMenu'
name: 'Blockchain'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'The secure, transparent way to verify any type of transaction'
description: 'Whether you’re launching a decentralized app, secure asset exchange, or building a nation, Hanzo has you covered'
url: 'https://hanzo.ai/blockchain'
}
]
}
{
'@type': 'WebsiteMenu'
name: 'Developers'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'Introduction to Hanzo'
description: 'What is Hanzo?'
# image: '/img/test-rocket.svg'
url: 'https://docs.hanzo.ai/docs/introduction-10'
}
{
'@type': 'WebsiteMenuLink'
name: 'API Reference'
description: 'Request and Response Examples'
# image: '/img/test-rocket.svg'
url: 'https://docs.hanzo.ai/reference'
}
]
}
{
'@type': 'WebsiteMenu'
name: 'Open Source'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'Javascript SDK'
description: 'Start building your store with our Javascript & Node SDK.'
# image: '/img/test-rocket.svg'
url: 'https://github.com/hanzoai/hanzo.js'
}
{
'@type': 'WebsiteMenuLink'
name: 'Shop.js'
description: 'Checkout open source custom payment flow UI library.'
# image: '/img/test-rocket.svg'
url: 'https://getshopjs.com'
}
{
'@type': 'WebsiteMenuLink'
name: 'Other Projects'
description: "Look at other software we've worked on."
# image: '/img/test-rocket.svg'
url: 'https://github.com/hanzoai'
}
]
}
# {
# '@type': 'WebsiteMenu'
# name: 'Solutions'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Analytics'
# description: 'Real time actionable insights. Fully integrated from day one.'
# # image: '/img/test-rocket.svg'
# url: 'analytics'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Commerce'
# description: 'Checkout optimized for convertions. Proven mobile checkout experience.'
# # image: '/img/test-rocket.svg'
# url: 'commerce'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Marketing'
# description: 'AI optimized marketing. Meet your automated sales engine.'
# # image: '/img/test-rocket.svg'
# url: 'marketing'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Developers'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'API'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.io/reference'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Javascript SDK'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzo-io/hanzo.js'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Open Source'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzo-io/'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Company'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Team'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Press'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Partners'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Careers'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Contact'
# url: '#'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Pricing'
# url: '#'
# }
]
}
{
'@type': 'WebsiteMenuCollection'
menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Support'
# url: 'https://docs.hanzo.io/discuss'
# }
{
'@type': 'WebsiteMenu'
name: 'Sign In'
url: 'https://dash.hanzo.ai'
}
]
}
]
}
# main: [
# {
# '@type': 'WebsiteSection'
# content: [
# {
# '@type': 'WebsiteText'
# text: 'Put your business on autopilot'
# level: 'h1'
# }
# {
# '@type': 'WebsiteLink'
# class: 'button'
# text: 'JOIN THE BETA +'
# url: '#'
# }
# {
# '@type': 'WebsiteLink'
# class: 'button important'
# text: 'CHECK OUR DOCS >'
# url: '#'
# }
# {
# '@type': 'WebsiteImage'
# class: 'bg-stars'
# src: '/img/stars.svg'
# }
# ]
# }
# {
# '@type': 'WebsiteSection'
# class: 'scale-your-business'
# content: [
# {
# '@type': 'WebsiteImage'
# class: 'phone-bb'
# src: '/img/3diphone_bb_final.png'
# alt: 'Bellabeat'
# }
# {
# '@type': 'WebsiteImage'
# class: 'phone-kanoa'
# src: '/img/3diphone_kanoa_final.png'
# alt: 'KANOA'
# }
# {
# '@type': 'WebsiteImage'
# class: 'phone-kanoa'
# src: '/img/3diphone_stoned_final.png'
# alt: 'Stoned Audio'
# }
# ]
# }
# ]
footer: {
'@type': 'WebsiteFooter'
logos: [
{
'@type': 'WebsiteLogo'
image: '/img/logo-dark.svg'
alt: 'Hanzo'
name: 'Hanzo'
url: '/'
}
{
'@type': 'WebsiteLogo'
image: '/img/atechstars-dark.png'
alt: 'A Techstars Company'
url: 'http://www.techstars.com'
}
]
menuCollections: [
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Solutions'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Analytics'
# url: 'analytics'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Commerce'
# url: 'commerce'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Marketing'
# url: 'marketing'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Developers'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Introduction to Hanzo'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.ai/docs/introduction-10'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'API Reference'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.ai/reference'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Open Source'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Javascript SDK'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzoai/hanzo.js'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Shop.js'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://getshopjs.com'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Other Projects'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzoai'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Company'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Team'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Press'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Partners'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Careers'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Contact'
# url: '#'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Pricing'
# url: '#'
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Support'
# url: 'https://docs.hanzo.io/discuss'
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Sign In'
# url: 'https://dash.hanzo.io'
# }
# ]
# }
]
}
}
| 4328 | module.exports =
data: {
'@context': 'hanzo.ai/schema'
'@type': 'Website'
header: {
'@type': 'WebsiteHeader'
type: 'complex'
logos: [
{
'@type': 'WebsiteLogo'
image: '/img/logo.svg'
alt: 'Hanzo'
name: ''
url: '/'
}
]
menuCollections: [
{
'@type': 'WebsiteMenuCollection'
menus: [
{
'@type': 'WebsiteMenu'
name: 'Blockchain'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'The secure, transparent way to verify any type of transaction'
description: 'Whether you’re launching a decentralized app, secure asset exchange, or building a nation, Hanzo has you covered'
url: 'https://hanzo.ai/blockchain'
}
]
}
{
'@type': 'WebsiteMenu'
name: 'Developers'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'Introduction to Hanzo'
description: 'What is Hanzo?'
# image: '/img/test-rocket.svg'
url: 'https://docs.hanzo.ai/docs/introduction-10'
}
{
'@type': 'WebsiteMenuLink'
name: 'API Reference'
description: 'Request and Response Examples'
# image: '/img/test-rocket.svg'
url: 'https://docs.hanzo.ai/reference'
}
]
}
{
'@type': 'WebsiteMenu'
name: 'Open Source'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'Javascript SDK'
description: 'Start building your store with our Javascript & Node SDK.'
# image: '/img/test-rocket.svg'
url: 'https://github.com/hanzoai/hanzo.js'
}
{
'@type': 'WebsiteMenuLink'
name: 'Shop.js'
description: 'Checkout open source custom payment flow UI library.'
# image: '/img/test-rocket.svg'
url: 'https://getshopjs.com'
}
{
'@type': 'WebsiteMenuLink'
name: 'Other Projects'
description: "Look at other software we've worked on."
# image: '/img/test-rocket.svg'
url: 'https://github.com/hanzoai'
}
]
}
# {
# '@type': 'WebsiteMenu'
# name: 'Solutions'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Analytics'
# description: 'Real time actionable insights. Fully integrated from day one.'
# # image: '/img/test-rocket.svg'
# url: 'analytics'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Commerce'
# description: 'Checkout optimized for convertions. Proven mobile checkout experience.'
# # image: '/img/test-rocket.svg'
# url: 'commerce'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Marketing'
# description: 'AI optimized marketing. Meet your automated sales engine.'
# # image: '/img/test-rocket.svg'
# url: 'marketing'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Developers'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'API'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.io/reference'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Javascript SDK'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzo-io/hanzo.js'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Open Source'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzo-io/'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Company'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# url: '#'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Pricing'
# url: '#'
# }
]
}
{
'@type': 'WebsiteMenuCollection'
menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Support'
# url: 'https://docs.hanzo.io/discuss'
# }
{
'@type': 'WebsiteMenu'
name: 'Sign In'
url: 'https://dash.hanzo.ai'
}
]
}
]
}
# main: [
# {
# '@type': 'WebsiteSection'
# content: [
# {
# '@type': 'WebsiteText'
# text: 'Put your business on autopilot'
# level: 'h1'
# }
# {
# '@type': 'WebsiteLink'
# class: 'button'
# text: 'JOIN THE BETA +'
# url: '#'
# }
# {
# '@type': 'WebsiteLink'
# class: 'button important'
# text: 'CHECK OUR DOCS >'
# url: '#'
# }
# {
# '@type': 'WebsiteImage'
# class: 'bg-stars'
# src: '/img/stars.svg'
# }
# ]
# }
# {
# '@type': 'WebsiteSection'
# class: 'scale-your-business'
# content: [
# {
# '@type': 'WebsiteImage'
# class: 'phone-bb'
# src: '/img/3diphone_bb_final.png'
# alt: 'Bellabeat'
# }
# {
# '@type': 'WebsiteImage'
# class: 'phone-kanoa'
# src: '/img/3diphone_kanoa_final.png'
# alt: 'KANOA'
# }
# {
# '@type': 'WebsiteImage'
# class: 'phone-kanoa'
# src: '/img/3diphone_stoned_final.png'
# alt: 'Stoned Audio'
# }
# ]
# }
# ]
footer: {
'@type': 'WebsiteFooter'
logos: [
{
'@type': 'WebsiteLogo'
image: '/img/logo-dark.svg'
alt: 'Han<NAME>'
name: '<NAME>'
url: '/'
}
{
'@type': 'WebsiteLogo'
image: '/img/atechstars-dark.png'
alt: 'A Techstars Company'
url: 'http://www.techstars.com'
}
]
menuCollections: [
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Solutions'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Analytics'
# url: 'analytics'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Commerce'
# url: 'commerce'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Marketing'
# url: 'marketing'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Developers'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Introduction to Hanzo'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.ai/docs/introduction-10'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'API Reference'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.ai/reference'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Open Source'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Javascript SDK'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzoai/hanzo.js'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Shop.js'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://getshopjs.com'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Other Projects'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzoai'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Company'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Press'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>ers'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: '<NAME>'
# url: '#'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Pricing'
# url: '#'
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Support'
# url: 'https://docs.hanzo.io/discuss'
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Sign In'
# url: 'https://dash.hanzo.io'
# }
# ]
# }
]
}
}
| true | module.exports =
data: {
'@context': 'hanzo.ai/schema'
'@type': 'Website'
header: {
'@type': 'WebsiteHeader'
type: 'complex'
logos: [
{
'@type': 'WebsiteLogo'
image: '/img/logo.svg'
alt: 'Hanzo'
name: ''
url: '/'
}
]
menuCollections: [
{
'@type': 'WebsiteMenuCollection'
menus: [
{
'@type': 'WebsiteMenu'
name: 'Blockchain'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'The secure, transparent way to verify any type of transaction'
description: 'Whether you’re launching a decentralized app, secure asset exchange, or building a nation, Hanzo has you covered'
url: 'https://hanzo.ai/blockchain'
}
]
}
{
'@type': 'WebsiteMenu'
name: 'Developers'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'Introduction to Hanzo'
description: 'What is Hanzo?'
# image: '/img/test-rocket.svg'
url: 'https://docs.hanzo.ai/docs/introduction-10'
}
{
'@type': 'WebsiteMenuLink'
name: 'API Reference'
description: 'Request and Response Examples'
# image: '/img/test-rocket.svg'
url: 'https://docs.hanzo.ai/reference'
}
]
}
{
'@type': 'WebsiteMenu'
name: 'Open Source'
links: [
{
'@type': 'WebsiteMenuLink'
name: 'Javascript SDK'
description: 'Start building your store with our Javascript & Node SDK.'
# image: '/img/test-rocket.svg'
url: 'https://github.com/hanzoai/hanzo.js'
}
{
'@type': 'WebsiteMenuLink'
name: 'Shop.js'
description: 'Checkout open source custom payment flow UI library.'
# image: '/img/test-rocket.svg'
url: 'https://getshopjs.com'
}
{
'@type': 'WebsiteMenuLink'
name: 'Other Projects'
description: "Look at other software we've worked on."
# image: '/img/test-rocket.svg'
url: 'https://github.com/hanzoai'
}
]
}
# {
# '@type': 'WebsiteMenu'
# name: 'Solutions'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Analytics'
# description: 'Real time actionable insights. Fully integrated from day one.'
# # image: '/img/test-rocket.svg'
# url: 'analytics'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Commerce'
# description: 'Checkout optimized for convertions. Proven mobile checkout experience.'
# # image: '/img/test-rocket.svg'
# url: 'commerce'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Marketing'
# description: 'AI optimized marketing. Meet your automated sales engine.'
# # image: '/img/test-rocket.svg'
# url: 'marketing'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Developers'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'API'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.io/reference'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Javascript SDK'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzo-io/hanzo.js'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Open Source'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzo-io/'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Company'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# url: '#'
# }
# ]
# }
# {
# '@type': 'WebsiteMenu'
# name: 'Pricing'
# url: '#'
# }
]
}
{
'@type': 'WebsiteMenuCollection'
menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Support'
# url: 'https://docs.hanzo.io/discuss'
# }
{
'@type': 'WebsiteMenu'
name: 'Sign In'
url: 'https://dash.hanzo.ai'
}
]
}
]
}
# main: [
# {
# '@type': 'WebsiteSection'
# content: [
# {
# '@type': 'WebsiteText'
# text: 'Put your business on autopilot'
# level: 'h1'
# }
# {
# '@type': 'WebsiteLink'
# class: 'button'
# text: 'JOIN THE BETA +'
# url: '#'
# }
# {
# '@type': 'WebsiteLink'
# class: 'button important'
# text: 'CHECK OUR DOCS >'
# url: '#'
# }
# {
# '@type': 'WebsiteImage'
# class: 'bg-stars'
# src: '/img/stars.svg'
# }
# ]
# }
# {
# '@type': 'WebsiteSection'
# class: 'scale-your-business'
# content: [
# {
# '@type': 'WebsiteImage'
# class: 'phone-bb'
# src: '/img/3diphone_bb_final.png'
# alt: 'Bellabeat'
# }
# {
# '@type': 'WebsiteImage'
# class: 'phone-kanoa'
# src: '/img/3diphone_kanoa_final.png'
# alt: 'KANOA'
# }
# {
# '@type': 'WebsiteImage'
# class: 'phone-kanoa'
# src: '/img/3diphone_stoned_final.png'
# alt: 'Stoned Audio'
# }
# ]
# }
# ]
footer: {
'@type': 'WebsiteFooter'
logos: [
{
'@type': 'WebsiteLogo'
image: '/img/logo-dark.svg'
alt: 'HanPI:NAME:<NAME>END_PI'
name: 'PI:NAME:<NAME>END_PI'
url: '/'
}
{
'@type': 'WebsiteLogo'
image: '/img/atechstars-dark.png'
alt: 'A Techstars Company'
url: 'http://www.techstars.com'
}
]
menuCollections: [
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Solutions'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Analytics'
# url: 'analytics'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Commerce'
# url: 'commerce'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Marketing'
# url: 'marketing'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Developers'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Introduction to Hanzo'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.ai/docs/introduction-10'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'API Reference'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://docs.hanzo.ai/reference'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Open Source'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'Javascript SDK'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzoai/hanzo.js'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Shop.js'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://getshopjs.com'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Other Projects'
# # description: 'Lorem Descriptio'
# # image: '/img/test-rocket.svg'
# url: 'https://github.com/hanzoai'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Company'
# links: [
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'Press'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PIers'
# # image: '/img/test-rocket.svg'
# url: '#'
# }
# {
# '@type': 'WebsiteMenuLink'
# name: 'PI:NAME:<NAME>END_PI'
# url: '#'
# }
# ]
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Pricing'
# url: '#'
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Support'
# url: 'https://docs.hanzo.io/discuss'
# }
# ]
# }
# {
# '@type': 'WebsiteMenuCollection'
# menus: [
# {
# '@type': 'WebsiteMenu'
# name: 'Sign In'
# url: 'https://dash.hanzo.io'
# }
# ]
# }
]
}
}
|
[
{
"context": "est(\"$121.04\")\n\tsetModel(\"customer\", display_me: \"Cool Customer\")\n\texecuteTest(\"Cool Customer\")\n\tsetMode",
"end": 1024,
"score": 0.650256872177124,
"start": 1020,
"tag": "NAME",
"value": "Cool"
},
{
"context": "edit)\")\n\tsetModel(\"bank-account\",\n\t\tl... | tests/unit/views/detail-views/resource-summary-base-test.coffee | dk-dev/balanced-dashboard | 169 | `import { test, moduleFor } from "ember-qunit";`
moduleFor("view:detail-views/resource-summaries/resource-summary-base", "View - ResourceSummaryBase", {},
(container) ->
typeNames = ["dispute", "reversal", "refund", "credit", "debit", "hold", "order", "customer", "card", "bank-account"]
for typeName in typeNames
container.register("model:#{typeName}", Ember.Object.extend(), singleton: false, instantiate: true)
)
generateSetModel = (view) ->
setModel = (modelType, attributes) ->
Ember.run ->
model = view.get("container").lookup("model:#{modelType}")
model.setProperties attributes
view.set("model", model)
test "#value", ->
view = @subject()
setModel = generateSetModel(view)
executeTest = (expectation) ->
deepEqual(view.get("value"), expectation)
executeTest(null)
setModel("order", amount_escrowed: 1404)
executeTest("$14.04")
setModel("debit", amount: 1204)
executeTest("$12.04")
setModel("reversal", amount: 12104)
executeTest("$121.04")
setModel("customer", display_me: "Cool Customer")
executeTest("Cool Customer")
setModel("card",
last_four: "9999"
brand: "Visa"
)
executeTest("9999 Visa")
setModel("bank-account",
last_four: "9011"
formatted_bank_name: "First Bank of Banking"
)
executeTest("9011 First Bank of Banking")
test "#hoverValue", ->
view = @subject()
setModel = generateSetModel(view)
executeTest = (expectation) ->
deepEqual(view.get("hoverValue"), expectation)
executeTest null
setModel "dispute", created_at: "2014-12-18T19:12:24.373Z"
deepEqual(view.get("hoverValue").replace(/,.*$/, ""), "Created at 12/18/2014")
setModel "refund", created_at: "2012-12-10T19:00:24.373Z"
deepEqual(view.get("hoverValue").replace(/,.*$/, ""), "Created at 12/10/2012")
setModel "customer", display_me_with_email: "xxxxxxxxx"
executeTest "xxxxxxxxx"
setModel("card",
last_four: "9999"
brand: "Visa"
type_name: "Credit"
)
executeTest("9999 Visa (Credit)")
setModel("bank-account",
last_four: "9011"
formatted_bank_name: "First Bank of Banking"
type_name: "Checking"
)
executeTest("9011 First Bank of Banking (Checking)")
| 64843 | `import { test, moduleFor } from "ember-qunit";`
moduleFor("view:detail-views/resource-summaries/resource-summary-base", "View - ResourceSummaryBase", {},
(container) ->
typeNames = ["dispute", "reversal", "refund", "credit", "debit", "hold", "order", "customer", "card", "bank-account"]
for typeName in typeNames
container.register("model:#{typeName}", Ember.Object.extend(), singleton: false, instantiate: true)
)
generateSetModel = (view) ->
setModel = (modelType, attributes) ->
Ember.run ->
model = view.get("container").lookup("model:#{modelType}")
model.setProperties attributes
view.set("model", model)
test "#value", ->
view = @subject()
setModel = generateSetModel(view)
executeTest = (expectation) ->
deepEqual(view.get("value"), expectation)
executeTest(null)
setModel("order", amount_escrowed: 1404)
executeTest("$14.04")
setModel("debit", amount: 1204)
executeTest("$12.04")
setModel("reversal", amount: 12104)
executeTest("$121.04")
setModel("customer", display_me: "<NAME> Customer")
executeTest("Cool Customer")
setModel("card",
last_four: "9999"
brand: "Visa"
)
executeTest("9999 Visa")
setModel("bank-account",
last_four: "9011"
formatted_bank_name: "First Bank of Banking"
)
executeTest("9011 First Bank of Banking")
test "#hoverValue", ->
view = @subject()
setModel = generateSetModel(view)
executeTest = (expectation) ->
deepEqual(view.get("hoverValue"), expectation)
executeTest null
setModel "dispute", created_at: "2014-12-18T19:12:24.373Z"
deepEqual(view.get("hoverValue").replace(/,.*$/, ""), "Created at 12/18/2014")
setModel "refund", created_at: "2012-12-10T19:00:24.373Z"
deepEqual(view.get("hoverValue").replace(/,.*$/, ""), "Created at 12/10/2012")
setModel "customer", display_me_with_email: "xxxxxxxxx"
executeTest "xxxxxxxxx"
setModel("card",
last_four: "9999"
brand: "Visa"
type_name: "Credit"
)
executeTest("9999 Visa (Credit)")
setModel("bank-account",
last_four: "90<NAME>1"
formatted_bank_name: "First Bank of Banking"
type_name: "Checking"
)
executeTest("9011 First Bank of Banking (Checking)")
| true | `import { test, moduleFor } from "ember-qunit";`
moduleFor("view:detail-views/resource-summaries/resource-summary-base", "View - ResourceSummaryBase", {},
(container) ->
typeNames = ["dispute", "reversal", "refund", "credit", "debit", "hold", "order", "customer", "card", "bank-account"]
for typeName in typeNames
container.register("model:#{typeName}", Ember.Object.extend(), singleton: false, instantiate: true)
)
generateSetModel = (view) ->
setModel = (modelType, attributes) ->
Ember.run ->
model = view.get("container").lookup("model:#{modelType}")
model.setProperties attributes
view.set("model", model)
test "#value", ->
view = @subject()
setModel = generateSetModel(view)
executeTest = (expectation) ->
deepEqual(view.get("value"), expectation)
executeTest(null)
setModel("order", amount_escrowed: 1404)
executeTest("$14.04")
setModel("debit", amount: 1204)
executeTest("$12.04")
setModel("reversal", amount: 12104)
executeTest("$121.04")
setModel("customer", display_me: "PI:NAME:<NAME>END_PI Customer")
executeTest("Cool Customer")
setModel("card",
last_four: "9999"
brand: "Visa"
)
executeTest("9999 Visa")
setModel("bank-account",
last_four: "9011"
formatted_bank_name: "First Bank of Banking"
)
executeTest("9011 First Bank of Banking")
test "#hoverValue", ->
view = @subject()
setModel = generateSetModel(view)
executeTest = (expectation) ->
deepEqual(view.get("hoverValue"), expectation)
executeTest null
setModel "dispute", created_at: "2014-12-18T19:12:24.373Z"
deepEqual(view.get("hoverValue").replace(/,.*$/, ""), "Created at 12/18/2014")
setModel "refund", created_at: "2012-12-10T19:00:24.373Z"
deepEqual(view.get("hoverValue").replace(/,.*$/, ""), "Created at 12/10/2012")
setModel "customer", display_me_with_email: "xxxxxxxxx"
executeTest "xxxxxxxxx"
setModel("card",
last_four: "9999"
brand: "Visa"
type_name: "Credit"
)
executeTest("9999 Visa (Credit)")
setModel("bank-account",
last_four: "90PI:NAME:<NAME>END_PI1"
formatted_bank_name: "First Bank of Banking"
type_name: "Checking"
)
executeTest("9011 First Bank of Banking (Checking)")
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.999908447265625,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/_components/changelog-header-streams.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { a, div, p } from 'react-dom-factories'
el = React.createElement
export class ChangelogHeaderStreams extends React.PureComponent
render: =>
div className: osu.classWithModifiers('update-streams-v2', ['with-active' if @props.currentStreamId?]),
div className: 'update-streams-v2__container',
for stream in @props.updateStreams
@renderHeaderStream stream: stream
renderHeaderStream: ({stream}) =>
streamNameClass = _.kebabCase(stream.display_name)
mainClass = osu.classWithModifiers 'update-streams-v2__item', [
streamNameClass
'featured' if stream.is_featured
'active' if @props.currentStreamId == stream.id
]
mainClass += " t-changelog-stream--#{streamNameClass}"
a
href: _exported.OsuUrlHelper.changelogBuild stream.latest_build
key: stream.id
className: mainClass
div className: 'update-streams-v2__bar u-changelog-stream--bg'
p className: 'update-streams-v2__row update-streams-v2__row--name', stream.display_name
p className: 'update-streams-v2__row update-streams-v2__row--version', stream.latest_build.display_version
if stream.user_count > 0
p
className: 'update-streams-v2__row update-streams-v2__row--users'
osu.transChoice 'changelog.builds.users_online', stream.user_count
| 135200 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { a, div, p } from 'react-dom-factories'
el = React.createElement
export class ChangelogHeaderStreams extends React.PureComponent
render: =>
div className: osu.classWithModifiers('update-streams-v2', ['with-active' if @props.currentStreamId?]),
div className: 'update-streams-v2__container',
for stream in @props.updateStreams
@renderHeaderStream stream: stream
renderHeaderStream: ({stream}) =>
streamNameClass = _.kebabCase(stream.display_name)
mainClass = osu.classWithModifiers 'update-streams-v2__item', [
streamNameClass
'featured' if stream.is_featured
'active' if @props.currentStreamId == stream.id
]
mainClass += " t-changelog-stream--#{streamNameClass}"
a
href: _exported.OsuUrlHelper.changelogBuild stream.latest_build
key: stream.id
className: mainClass
div className: 'update-streams-v2__bar u-changelog-stream--bg'
p className: 'update-streams-v2__row update-streams-v2__row--name', stream.display_name
p className: 'update-streams-v2__row update-streams-v2__row--version', stream.latest_build.display_version
if stream.user_count > 0
p
className: 'update-streams-v2__row update-streams-v2__row--users'
osu.transChoice 'changelog.builds.users_online', stream.user_count
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { a, div, p } from 'react-dom-factories'
el = React.createElement
export class ChangelogHeaderStreams extends React.PureComponent
render: =>
div className: osu.classWithModifiers('update-streams-v2', ['with-active' if @props.currentStreamId?]),
div className: 'update-streams-v2__container',
for stream in @props.updateStreams
@renderHeaderStream stream: stream
renderHeaderStream: ({stream}) =>
streamNameClass = _.kebabCase(stream.display_name)
mainClass = osu.classWithModifiers 'update-streams-v2__item', [
streamNameClass
'featured' if stream.is_featured
'active' if @props.currentStreamId == stream.id
]
mainClass += " t-changelog-stream--#{streamNameClass}"
a
href: _exported.OsuUrlHelper.changelogBuild stream.latest_build
key: stream.id
className: mainClass
div className: 'update-streams-v2__bar u-changelog-stream--bg'
p className: 'update-streams-v2__row update-streams-v2__row--name', stream.display_name
p className: 'update-streams-v2__row update-streams-v2__row--version', stream.latest_build.display_version
if stream.user_count > 0
p
className: 'update-streams-v2__row update-streams-v2__row--users'
osu.transChoice 'changelog.builds.users_online', stream.user_count
|
[
{
"context": "t>\n <book asdf=\"asdf\">\n <author name=\"john\"></author>\n <author><name>will</name></aut",
"end": 385,
"score": 0.9990237951278687,
"start": 381,
"tag": "NAME",
"value": "john"
},
{
"context": "uthor name=\"john\"></author>\n <author><name>... | node_modules/bucket-list/node_modules/xml-object-stream/test.coffee | zeke/s3-bucket-lister | 2 | assert = require 'assert'
{Stream} = require 'stream'
{parse} = require './index'
streamData = (xml) ->
stream = new Stream()
process.nextTick ->
stream.emit 'data', xml
stream.emit 'end'
return stream
describe "xml streamer thing", ->
it "should parse", (done) ->
foundBook = false
xml = """
<root>
<book asdf="asdf">
<author name="john"></author>
<author><name>will</name></author>
<title>Title</title>
<description>stuff</description>
</book>
</root>
"""
stream = streamData xml
parser = parse stream
parser.each 'book', (book) ->
foundBook = true
assert.ok book
assert.equal book.$.asdf, "asdf"
assert.equal book.title.$text, "Title"
assert.equal book.description.$text, "stuff"
authors = book.$children.filter (node) -> node.$name is "author"
assert.equal authors.length, 2
assert.equal authors[0].$.name, "john"
assert.equal authors[1].name.$text, "will"
parser.on 'end', ->
assert.ok foundBook
done()
it 'should find all the nodes', (done) ->
found = []
xml = """
<root>
<items>
<item name="1"/>
<item name="2"/>
<item name="3"/>
<item name="4"/>
<item name="5"/>
<item name="6"/>
<item name="7"/>
<item name="8"/>
</items>
</root>
"""
stream = streamData xml
parser = parse stream
parser.each 'item', (item) ->
found.push item
parser.on 'end', ->
assert.equal found.length, 8
done()
describe 'namespaces', ->
it 'should strip namespaces by default', (done) ->
stream = streamData """
<root>
<me:item>one</me:item>
</root>
"""
found = []
parser = parse stream
parser.each 'item', (item) ->
found.push item
assert.equal item.$text, "one"
parser.on 'end', ->
assert.equal found.length, 1
done()
it 'should preserve them if you turn it off', (done) ->
stream = streamData """
<root>
<me:item>one</me:item>
</root>
"""
found = []
parser = parse stream, {stripNamespaces: false}
parser.each 'me:item', (item) ->
found.push item
assert.equal item.$text, "one"
parser.on 'end', ->
assert.equal found.length, 1
done()
| 79353 | assert = require 'assert'
{Stream} = require 'stream'
{parse} = require './index'
streamData = (xml) ->
stream = new Stream()
process.nextTick ->
stream.emit 'data', xml
stream.emit 'end'
return stream
describe "xml streamer thing", ->
it "should parse", (done) ->
foundBook = false
xml = """
<root>
<book asdf="asdf">
<author name="<NAME>"></author>
<author><name><NAME></name></author>
<title>Title</title>
<description>stuff</description>
</book>
</root>
"""
stream = streamData xml
parser = parse stream
parser.each 'book', (book) ->
foundBook = true
assert.ok book
assert.equal book.$.asdf, "asdf"
assert.equal book.title.$text, "Title"
assert.equal book.description.$text, "stuff"
authors = book.$children.filter (node) -> node.$name is "author"
assert.equal authors.length, 2
assert.equal authors[0].$.name, "<NAME>"
assert.equal authors[1].name.$text, "<NAME>"
parser.on 'end', ->
assert.ok foundBook
done()
it 'should find all the nodes', (done) ->
found = []
xml = """
<root>
<items>
<item name="1"/>
<item name="2"/>
<item name="3"/>
<item name="4"/>
<item name="5"/>
<item name="6"/>
<item name="7"/>
<item name="8"/>
</items>
</root>
"""
stream = streamData xml
parser = parse stream
parser.each 'item', (item) ->
found.push item
parser.on 'end', ->
assert.equal found.length, 8
done()
describe 'namespaces', ->
it 'should strip namespaces by default', (done) ->
stream = streamData """
<root>
<me:item>one</me:item>
</root>
"""
found = []
parser = parse stream
parser.each 'item', (item) ->
found.push item
assert.equal item.$text, "one"
parser.on 'end', ->
assert.equal found.length, 1
done()
it 'should preserve them if you turn it off', (done) ->
stream = streamData """
<root>
<me:item>one</me:item>
</root>
"""
found = []
parser = parse stream, {stripNamespaces: false}
parser.each 'me:item', (item) ->
found.push item
assert.equal item.$text, "one"
parser.on 'end', ->
assert.equal found.length, 1
done()
| true | assert = require 'assert'
{Stream} = require 'stream'
{parse} = require './index'
streamData = (xml) ->
stream = new Stream()
process.nextTick ->
stream.emit 'data', xml
stream.emit 'end'
return stream
describe "xml streamer thing", ->
it "should parse", (done) ->
foundBook = false
xml = """
<root>
<book asdf="asdf">
<author name="PI:NAME:<NAME>END_PI"></author>
<author><name>PI:NAME:<NAME>END_PI</name></author>
<title>Title</title>
<description>stuff</description>
</book>
</root>
"""
stream = streamData xml
parser = parse stream
parser.each 'book', (book) ->
foundBook = true
assert.ok book
assert.equal book.$.asdf, "asdf"
assert.equal book.title.$text, "Title"
assert.equal book.description.$text, "stuff"
authors = book.$children.filter (node) -> node.$name is "author"
assert.equal authors.length, 2
assert.equal authors[0].$.name, "PI:NAME:<NAME>END_PI"
assert.equal authors[1].name.$text, "PI:NAME:<NAME>END_PI"
parser.on 'end', ->
assert.ok foundBook
done()
it 'should find all the nodes', (done) ->
found = []
xml = """
<root>
<items>
<item name="1"/>
<item name="2"/>
<item name="3"/>
<item name="4"/>
<item name="5"/>
<item name="6"/>
<item name="7"/>
<item name="8"/>
</items>
</root>
"""
stream = streamData xml
parser = parse stream
parser.each 'item', (item) ->
found.push item
parser.on 'end', ->
assert.equal found.length, 8
done()
describe 'namespaces', ->
it 'should strip namespaces by default', (done) ->
stream = streamData """
<root>
<me:item>one</me:item>
</root>
"""
found = []
parser = parse stream
parser.each 'item', (item) ->
found.push item
assert.equal item.$text, "one"
parser.on 'end', ->
assert.equal found.length, 1
done()
it 'should preserve them if you turn it off', (done) ->
stream = streamData """
<root>
<me:item>one</me:item>
</root>
"""
found = []
parser = parse stream, {stripNamespaces: false}
parser.each 'me:item', (item) ->
found.push item
assert.equal item.$text, "one"
parser.on 'end', ->
assert.equal found.length, 1
done()
|
[
{
"context": "e to another object in the PDF object heirarchy\nBy Devon Govett\n###\n\nclass PDFReference\n constructor: (@id, @d",
"end": 103,
"score": 0.9997254610061646,
"start": 91,
"tag": "NAME",
"value": "Devon Govett"
}
] | lib/reference.coffee | stanfeldman/pdf.js | 1 | ###
PDFReference - represents a reference to another object in the PDF object heirarchy
By Devon Govett
###
class PDFReference
constructor: (@id, @data = {}) ->
@gen = 0
@stream = null
@finalizedStream = null
object: ->
@finalize() if not @finalizedStream
out = ["#{@id} #{@gen} obj"]
out.push PDFObject.convert(@data)
if @stream
out.push "stream"
out.push @finalizedStream
out.push "endstream"
out.push "endobj"
return out.join '\n'
add: (s) ->
@stream ?= []
@stream.push if Buffer.isBuffer(s) then s.toString('binary') else s
finalize: (compress = false) ->
# cache the finalized stream
if @stream
data = @stream.join '\n'
if compress
# create a byte array instead of passing a string to the Buffer
# fixes a weird unicode bug.
data = new Buffer(data.charCodeAt(i) for i in [0...data.length])
@finalizedStream = data.toString 'binary'
@data.Length ?= @finalizedStream.length
else
@finalizedStream = data
else
@finalizedStream = ''
toString: ->
"#{@id} #{@gen} R"
module.exports = PDFReference
PDFObject = require './object'
| 119977 | ###
PDFReference - represents a reference to another object in the PDF object heirarchy
By <NAME>
###
class PDFReference
constructor: (@id, @data = {}) ->
@gen = 0
@stream = null
@finalizedStream = null
object: ->
@finalize() if not @finalizedStream
out = ["#{@id} #{@gen} obj"]
out.push PDFObject.convert(@data)
if @stream
out.push "stream"
out.push @finalizedStream
out.push "endstream"
out.push "endobj"
return out.join '\n'
add: (s) ->
@stream ?= []
@stream.push if Buffer.isBuffer(s) then s.toString('binary') else s
finalize: (compress = false) ->
# cache the finalized stream
if @stream
data = @stream.join '\n'
if compress
# create a byte array instead of passing a string to the Buffer
# fixes a weird unicode bug.
data = new Buffer(data.charCodeAt(i) for i in [0...data.length])
@finalizedStream = data.toString 'binary'
@data.Length ?= @finalizedStream.length
else
@finalizedStream = data
else
@finalizedStream = ''
toString: ->
"#{@id} #{@gen} R"
module.exports = PDFReference
PDFObject = require './object'
| true | ###
PDFReference - represents a reference to another object in the PDF object heirarchy
By PI:NAME:<NAME>END_PI
###
class PDFReference
constructor: (@id, @data = {}) ->
@gen = 0
@stream = null
@finalizedStream = null
object: ->
@finalize() if not @finalizedStream
out = ["#{@id} #{@gen} obj"]
out.push PDFObject.convert(@data)
if @stream
out.push "stream"
out.push @finalizedStream
out.push "endstream"
out.push "endobj"
return out.join '\n'
add: (s) ->
@stream ?= []
@stream.push if Buffer.isBuffer(s) then s.toString('binary') else s
finalize: (compress = false) ->
# cache the finalized stream
if @stream
data = @stream.join '\n'
if compress
# create a byte array instead of passing a string to the Buffer
# fixes a weird unicode bug.
data = new Buffer(data.charCodeAt(i) for i in [0...data.length])
@finalizedStream = data.toString 'binary'
@data.Length ?= @finalizedStream.length
else
@finalizedStream = data
else
@finalizedStream = ''
toString: ->
"#{@id} #{@gen} R"
module.exports = PDFReference
PDFObject = require './object'
|
[
{
"context": ": 1\n Fail: 1\n \"Hello Kitty\": 1\n }\n ])\n\n @ajax.whenQuerying(",
"end": 16124,
"score": 0.6910604238510132,
"start": 16119,
"tag": "NAME",
"value": "Kitty"
},
{
"context": ": 1\n Fail: 1\n ... | test/spec/iterationsummary/IterationSummaryAppSpec.coffee | CustomAgile/app-catalog | 31 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.apps.iterationsummary.IterationSummaryApp'
]
describe 'Rally.apps.iterationsummary.IterationSummaryApp', ->
helpers
getContext: (initialValues) ->
globalContext = Rally.environment.getContext()
Ext.create 'Rally.app.Context',
initialValues:Ext.merge
project:globalContext.getProject()
workspace:globalContext.getWorkspace()
user:globalContext.getUser()
subscription:globalContext.getSubscription()
timebox: Ext.create 'Rally.app.TimeboxScope', record: @mom.getRecord 'iteration'
, initialValues
createApp: (initialValues) ->
@container = Ext.create('Ext.Container', {
renderTo:'testDiv'
})
app = Ext.create('Rally.apps.iterationsummary.IterationSummaryApp', {
context: @getContext(initialValues)
})
@container.add(app)
if app.getContext().getTimeboxScope().getRecord()
@waitForComponentReady(app)
else
@once condition: -> app.down '#unscheduledBlankSlate'
stubApp: (config) ->
@stubPromiseFunction(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getScheduleStates',
(config.scheduleStates || ["Defined", "In-Progress", "Completed", "Accepted"]))
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getStartDate').returns(config.startDate || new Date())
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getEndDate').returns(config.endDate || new Date())
@_stubIterationQuery(config.tzOffset || 0)
@stub(Rally.util.Timebox, 'getToday').returns(config.today || new Date())
stubTimeBoxInfo: (orientation) ->
timeOrientation: orientation
timeboxLength: 4
daysRemaining: 0
_stubIterationQuery: (tzOffset = 0) ->
@ajax.whenQuerying('iteration').respondWith([{
_refObjectName:"Iteration 3", Name:"Iteration 3", ObjectID:3,
StartDate:"2010-07-11T00:00:00.000Z", EndDate:"2010-07-15T23:59:59.000Z"
}
], {
schema:
properties:
EndDate:
format:
tzOffset: tzOffset * 60
})
prepareNoneAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([{
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 2
Open: 2
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0,
ScheduleState:"In-Progress",
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0,
ScheduleState:"In-Progress",
AcceptedDate:null
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareFiveDefectsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 2
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
},
{
Summary:
Defects:
State:
Closed: 2
Open: 0
}
])
prepareNoActiveDefectsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null,
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 0
Open: 0
},
{
Summary:
Defects:
State:
Closed: 2
Open: 0
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
}
])
prepareSomeAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareAllAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareSomeFailingTestsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"Hello Kitty": 1
}
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
{
Summary:
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"Hello Kitty": 1
}
])
@ajax.whenQuerying('testset').respondWith([
{
Summary:
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"Hello Kitty": 1
}
])
prepareTestSetData: (testSetSummaryVerdicts) ->
@ajax.whenQuerying('userstory').respondWith()
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith([
{
Summary:
TestCases:
LastVerdict: testSetSummaryVerdicts
}
])
beforeEach ->
@_stubIterationQuery()
afterEach ->
@container?.destroy()
it "does not call wsapidatastore if models are unavailable", ->
@stub(Rally.data.ModelFactory, 'getModels', (options) ->
results = {}
switch options.types[0]
when 'Iteration'
results.Iteration = Rally.test.mock.data.WsapiModelFactory.getModel('Iteration')
when 'UserStory'
results.UserStoRally.test.mock.data.WsapiModelFactoryctory.getModel('UserStory')
when 'AllowedAttributeValue'
results.AllowedAttribuRally.test.mock.data.WsapiModelFactorydelFactory.getModel('AllowedAttributeValue')
options.success.call(options.scope, results)
)
displayStatusRowsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_displayStatusRows')
@createApp({}).then (app) =>
expect(displayStatusRowsSpy).not.toHaveBeenCalled()
it "calls wsapidatastore if models are available", ->
displayStatusRowsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_displayStatusRows')
@createApp({}).then (app) =>
@waitForCallback(displayStatusRowsSpy)
it "getPostAcceptedState with no before or after state", ->
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBeNull()
it "getPostAcceptedState with only a before state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Idea", "Defined", "In-Progress", "Completed", "Accepted"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBeNull()
it "getPostAcceptedState with only an after state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Defined", "In-Progress", "Completed", "Accepted", "Released"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBe "Released"
it "getPostAcceptedState with a before and after state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Idea", "Defined", "In-Progress", "Completed", "Accepted", "Really Really Done"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBe "Really Really Done"
it "does not aggregate testset and defectsuite data for HS subscriptions", ->
@prepareFiveDefectsData()
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_isHsOrTeamEdition').returns true
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
# only the 2 defects from user story - should exclude the 3 from defect suite
expect(configDefects.title).toBe "2 Active Defects"
expect(configDefects.status).toBe "error"
expect(configDefects.message).toBe app.self.PAST_WITH_DEFECTS
expect(testsSpy).not.toHaveBeenCalled()
it "does aggregate testset data for UE or EE subscriptions", ->
@prepareTestSetData(Pass: 2, Fail: 1, Inconclusive: 1)
@createApp({}).then (app) =>
@waitForVisible(
css: ".#{Ext.baseCSSPrefix}component.header.testsPassing"
text: "50% Tests Passing"
)
it "sets timeBoxInfo every time iteraton scope is changed", ->
@prepareTestSetData(Pass: 2, Fail: 1, Inconclusive: 1)
timeBoxInfoStub = @stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_determineTimeBoxInfo')
timeBoxInfoStub.returns(@stubTimeBoxInfo('past'))
@createApp({}).then (app) =>
@waitForVisible(
css: '.timeboxStatusRow'
text: "50% Tests Passing"
).then =>
expect(timeBoxInfoStub.callCount).toBe 1
timeBoxInfoStub.returns(@stubTimeBoxInfo('future'))
app.onScopeChange()
@waitForComponentReady(app).then =>
@waitForNotVisible(
css: '.timeboxStatusRow'
text: "50% Tests Passing"
).then =>
expect(timeBoxInfoStub.callCount).toBe 2
it "refreshes app on objectUpdate of artifacts", ->
@createApp({}).then (app) =>
addStub = @stub(app, 'add')
messageBus = Rally.environment.getMessageBus()
for type in ['Defect', 'HierarchicalRequirement', 'DefectSuite', 'TestSet', 'TestCase']
messageBus.publish(Rally.Message.objectUpdate, @mom.getRecord(type))
expect(addStub.callCount).toBe 5
it "does not refresh app on objectUpdate of non-artifacts", ->
@createApp({}).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish(Rally.Message.objectUpdate, @mom.getRecord('Release'))
expect(addSpy).not.toHaveBeenCalled()
it "refreshes app on bulkUpdate of artifacts", ->
@createApp({}).then (app) =>
addStub = @stub(app, 'add')
messageBus = Rally.environment.getMessageBus()
messageBus.publish(Rally.Message.bulkUpdate, @mom.getRecord(type) for type in ['Defect', 'HierarchicalRequirement', 'DefectSuite', 'TestSet', 'TestCase'])
expect(addStub.callCount).toBe 1
it "does not refresh app on bulkUpdate of non-artifacts", ->
@createApp({}).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish(Rally.Message.bulkUpdate, @mom.getRecord(type) for type in ['ConversationPost', 'Release'])
expect(addSpy).not.toHaveBeenCalled()
it 'does not refresh app on objectUpdate if unscheduled', ->
@createApp(timebox: Ext.create 'Rally.app.TimeboxScope',
type: 'iteration',
record: null
).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish Rally.Message.objectUpdate, @mom.getRecord 'defect'
expect(addSpy).not.toHaveBeenCalled()
it "only fetches iteration schema once", ->
httpGetSpy = @spy(Rally.env.IoProvider.prototype, 'httpGet')
@createApp({}).then (app) =>
expect(httpGetSpy).toHaveBeenCalledOnce()
app.calculateTimeboxInfo().then ->
expect(httpGetSpy).toHaveBeenCalledOnce()
it "rounds estimates to two decimal places", ->
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith()
# the PEs in here add up to 14.829999999999998, which is needed for the rounding test above
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:2.23
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.13
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.43
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.04
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp({
startDate:new Date(2011, 4, 13),
endDate:new Date(2011, 4, 20, 23, 59, 59),
today:new Date(2011, 4, 14)
})
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
summedPlanEstimate = 0
Ext.Array.forEach(app.results.userstory, (s) ->
summedPlanEstimate += s.get('PlanEstimate')
)
expect(summedPlanEstimate.toString().length).toBeGreaterThan 5
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expectedSubtitle = Ext.String.format("(0 of {0} Points)", Math.round(summedPlanEstimate * 100) / 100)
expect(configAcceptance.subtitle).toBe expectedSubtitle
describe 'status row', ->
it "displays no stats for future timebox", ->
@prepareNoneAcceptedData()
@stubApp({
startDate:new Date(2051, 5, 15),
endDate:new Date(2051, 5, 16, 23, 59, 59)
})
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
testSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.then (configAcceptance) ->
expect(!!configAcceptance.title).toBeFalsy()
expect(!!configAcceptance.status).toBeFalsy()
expect(!!configAcceptance.message).toBeFalsy()
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
configTests = testSpy.firstCall.returnValue
expect(!!configTests.title).toBeFalsy()
expect(!!configTests.status).toBeFalsy()
expect(!!configTests.message).toBeFalsy()
it "displays no alarming acceptance stats when timebox has just started", ->
@prepareNoneAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "0% Accepted"
expect(configAcceptance.subtitle).toBe "(0 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_NO_ACCEPTED_WORK
it "does not display defect stats when no active defects for current timebox", ->
@prepareNoActiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
it "displays defect stats for current timebox", ->
@prepareFiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(configDefects.title).toBe "5 Active Defects"
expect(configDefects.status).toBe "warn"
expect(configDefects.message).toBe app.self.CURRENT_WITH_DEFECTS
it "displays acceptance warning 5 days into a long timebox", ->
@prepareNoneAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 1)
endDate:new Date(2011, 4, 28, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "0% Accepted"
expect(configAcceptance.subtitle).toBe "(0 of 27 Points)"
expect(configAcceptance.status).toBe "warn"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance pending 5 days into a long timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 1)
endDate:new Date(2011, 4, 28, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance pending halfway through a short timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 6, 23, 59, 59)
today:new Date(2011, 4, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance error when all work not accepted from past timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "error"
expect(configAcceptance.message).toBe app.self.PAST_WITH_SOME_UNACCEPTED_WORK
it "displays defect error when active defects remain from past timebox", ->
@prepareFiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(configDefects.title).toBe "5 Active Defects"
expect(configDefects.status).toBe "error"
expect(configDefects.message).toBe app.self.PAST_WITH_DEFECTS
it "does not display defect stats when no active defects for past timebox", ->
@prepareNoActiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
it "displays positive acceptance stats when all work accepted for past timebox", ->
@prepareAllAcceptedData()
@stubApp
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe ""
it "displays positive acceptance stats when all work accepted or released for past timebox", ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Released"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Released"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp
scheduleStates:["Defined", "In-Progress", "Completed", "Accepted", "Released"],
startDate:new Date(2011, 4, 2),
endDate:new Date(2011, 4, 20, 23, 59, 59),
today:new Date(2011, 5, 5)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe ""
it "displays success acceptance stats with work items without estimates but all accepted", ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 6, 23, 59, 59)
today:new Date(2011, 4, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(18 of 18 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe "3 work items have no estimate."
it "displays gently scolding for past timebox with work accepted late", ->
@prepareAllAcceptedData()
@stubApp(
startDate:new Date(2011, 3, 2)
endDate:new Date(2011, 3, 20, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe app.self.PAST_WITH_ACCEPTED_WORK_AFTER_END_DATE
it "does not display stats when there are no tests", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@ajax.whenQuerying('defectsuite').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(!!configTests.title).toBeFalsy()
expect(!!configTests.status).toBeFalsy()
expect(!!configTests.message).toBeFalsy()
it "displays pending when less than halfway or 5 days", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 8)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "pending"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays warning if all failing tests during current timebox", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "0% Tests Passing"
expect(configTests.subtitle).toBe "(0 of 9)"
expect(configTests.status).toBe "warn"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays pending if some failing tests during current timebox", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "pending"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays success if no failing tests during past, current, past timeboxes", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "100% Tests Passing"
expect(configTests.subtitle).toBe "(9 of 9)"
expect(configTests.status).toBe "success"
expect(configTests.message).toBe app.self.CURRENT_TESTS_PASSING
it "displays error if any failing tests during past timeboxes", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "error"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it 'cleans up app content when no timeboxes available', ->
@createApp({}).then (app) =>
expect(app.down('#dataContainer')).not.toBeNull()
app.onNoAvailableTimeboxes()
expect(app.down('#dataContainer')).toBeNull()
| 25127 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.apps.iterationsummary.IterationSummaryApp'
]
describe 'Rally.apps.iterationsummary.IterationSummaryApp', ->
helpers
getContext: (initialValues) ->
globalContext = Rally.environment.getContext()
Ext.create 'Rally.app.Context',
initialValues:Ext.merge
project:globalContext.getProject()
workspace:globalContext.getWorkspace()
user:globalContext.getUser()
subscription:globalContext.getSubscription()
timebox: Ext.create 'Rally.app.TimeboxScope', record: @mom.getRecord 'iteration'
, initialValues
createApp: (initialValues) ->
@container = Ext.create('Ext.Container', {
renderTo:'testDiv'
})
app = Ext.create('Rally.apps.iterationsummary.IterationSummaryApp', {
context: @getContext(initialValues)
})
@container.add(app)
if app.getContext().getTimeboxScope().getRecord()
@waitForComponentReady(app)
else
@once condition: -> app.down '#unscheduledBlankSlate'
stubApp: (config) ->
@stubPromiseFunction(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getScheduleStates',
(config.scheduleStates || ["Defined", "In-Progress", "Completed", "Accepted"]))
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getStartDate').returns(config.startDate || new Date())
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getEndDate').returns(config.endDate || new Date())
@_stubIterationQuery(config.tzOffset || 0)
@stub(Rally.util.Timebox, 'getToday').returns(config.today || new Date())
stubTimeBoxInfo: (orientation) ->
timeOrientation: orientation
timeboxLength: 4
daysRemaining: 0
_stubIterationQuery: (tzOffset = 0) ->
@ajax.whenQuerying('iteration').respondWith([{
_refObjectName:"Iteration 3", Name:"Iteration 3", ObjectID:3,
StartDate:"2010-07-11T00:00:00.000Z", EndDate:"2010-07-15T23:59:59.000Z"
}
], {
schema:
properties:
EndDate:
format:
tzOffset: tzOffset * 60
})
prepareNoneAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([{
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 2
Open: 2
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0,
ScheduleState:"In-Progress",
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0,
ScheduleState:"In-Progress",
AcceptedDate:null
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareFiveDefectsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 2
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
},
{
Summary:
Defects:
State:
Closed: 2
Open: 0
}
])
prepareNoActiveDefectsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null,
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 0
Open: 0
},
{
Summary:
Defects:
State:
Closed: 2
Open: 0
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
}
])
prepareSomeAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareAllAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareSomeFailingTestsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"Hello <NAME>": 1
}
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
{
Summary:
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"Hello <NAME>": 1
}
])
@ajax.whenQuerying('testset').respondWith([
{
Summary:
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"<NAME> <NAME>": 1
}
])
prepareTestSetData: (testSetSummaryVerdicts) ->
@ajax.whenQuerying('userstory').respondWith()
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith([
{
Summary:
TestCases:
LastVerdict: testSetSummaryVerdicts
}
])
beforeEach ->
@_stubIterationQuery()
afterEach ->
@container?.destroy()
it "does not call wsapidatastore if models are unavailable", ->
@stub(Rally.data.ModelFactory, 'getModels', (options) ->
results = {}
switch options.types[0]
when 'Iteration'
results.Iteration = Rally.test.mock.data.WsapiModelFactory.getModel('Iteration')
when 'UserStory'
results.UserStoRally.test.mock.data.WsapiModelFactoryctory.getModel('UserStory')
when 'AllowedAttributeValue'
results.AllowedAttribuRally.test.mock.data.WsapiModelFactorydelFactory.getModel('AllowedAttributeValue')
options.success.call(options.scope, results)
)
displayStatusRowsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_displayStatusRows')
@createApp({}).then (app) =>
expect(displayStatusRowsSpy).not.toHaveBeenCalled()
it "calls wsapidatastore if models are available", ->
displayStatusRowsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_displayStatusRows')
@createApp({}).then (app) =>
@waitForCallback(displayStatusRowsSpy)
it "getPostAcceptedState with no before or after state", ->
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBeNull()
it "getPostAcceptedState with only a before state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Idea", "Defined", "In-Progress", "Completed", "Accepted"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBeNull()
it "getPostAcceptedState with only an after state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Defined", "In-Progress", "Completed", "Accepted", "Released"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBe "Released"
it "getPostAcceptedState with a before and after state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Idea", "Defined", "In-Progress", "Completed", "Accepted", "Really Really Done"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBe "Really Really Done"
it "does not aggregate testset and defectsuite data for HS subscriptions", ->
@prepareFiveDefectsData()
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_isHsOrTeamEdition').returns true
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
# only the 2 defects from user story - should exclude the 3 from defect suite
expect(configDefects.title).toBe "2 Active Defects"
expect(configDefects.status).toBe "error"
expect(configDefects.message).toBe app.self.PAST_WITH_DEFECTS
expect(testsSpy).not.toHaveBeenCalled()
it "does aggregate testset data for UE or EE subscriptions", ->
@prepareTestSetData(Pass: 2, Fail: 1, Inconclusive: 1)
@createApp({}).then (app) =>
@waitForVisible(
css: ".#{Ext.baseCSSPrefix}component.header.testsPassing"
text: "50% Tests Passing"
)
it "sets timeBoxInfo every time iteraton scope is changed", ->
@prepareTestSetData(Pass: 2, Fail: 1, Inconclusive: 1)
timeBoxInfoStub = @stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_determineTimeBoxInfo')
timeBoxInfoStub.returns(@stubTimeBoxInfo('past'))
@createApp({}).then (app) =>
@waitForVisible(
css: '.timeboxStatusRow'
text: "50% Tests Passing"
).then =>
expect(timeBoxInfoStub.callCount).toBe 1
timeBoxInfoStub.returns(@stubTimeBoxInfo('future'))
app.onScopeChange()
@waitForComponentReady(app).then =>
@waitForNotVisible(
css: '.timeboxStatusRow'
text: "50% Tests Passing"
).then =>
expect(timeBoxInfoStub.callCount).toBe 2
it "refreshes app on objectUpdate of artifacts", ->
@createApp({}).then (app) =>
addStub = @stub(app, 'add')
messageBus = Rally.environment.getMessageBus()
for type in ['Defect', 'HierarchicalRequirement', 'DefectSuite', 'TestSet', 'TestCase']
messageBus.publish(Rally.Message.objectUpdate, @mom.getRecord(type))
expect(addStub.callCount).toBe 5
it "does not refresh app on objectUpdate of non-artifacts", ->
@createApp({}).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish(Rally.Message.objectUpdate, @mom.getRecord('Release'))
expect(addSpy).not.toHaveBeenCalled()
it "refreshes app on bulkUpdate of artifacts", ->
@createApp({}).then (app) =>
addStub = @stub(app, 'add')
messageBus = Rally.environment.getMessageBus()
messageBus.publish(Rally.Message.bulkUpdate, @mom.getRecord(type) for type in ['Defect', 'HierarchicalRequirement', 'DefectSuite', 'TestSet', 'TestCase'])
expect(addStub.callCount).toBe 1
it "does not refresh app on bulkUpdate of non-artifacts", ->
@createApp({}).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish(Rally.Message.bulkUpdate, @mom.getRecord(type) for type in ['ConversationPost', 'Release'])
expect(addSpy).not.toHaveBeenCalled()
it 'does not refresh app on objectUpdate if unscheduled', ->
@createApp(timebox: Ext.create 'Rally.app.TimeboxScope',
type: 'iteration',
record: null
).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish Rally.Message.objectUpdate, @mom.getRecord 'defect'
expect(addSpy).not.toHaveBeenCalled()
it "only fetches iteration schema once", ->
httpGetSpy = @spy(Rally.env.IoProvider.prototype, 'httpGet')
@createApp({}).then (app) =>
expect(httpGetSpy).toHaveBeenCalledOnce()
app.calculateTimeboxInfo().then ->
expect(httpGetSpy).toHaveBeenCalledOnce()
it "rounds estimates to two decimal places", ->
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith()
# the PEs in here add up to 14.829999999999998, which is needed for the rounding test above
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:2.23
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.13
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.43
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.04
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp({
startDate:new Date(2011, 4, 13),
endDate:new Date(2011, 4, 20, 23, 59, 59),
today:new Date(2011, 4, 14)
})
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
summedPlanEstimate = 0
Ext.Array.forEach(app.results.userstory, (s) ->
summedPlanEstimate += s.get('PlanEstimate')
)
expect(summedPlanEstimate.toString().length).toBeGreaterThan 5
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expectedSubtitle = Ext.String.format("(0 of {0} Points)", Math.round(summedPlanEstimate * 100) / 100)
expect(configAcceptance.subtitle).toBe expectedSubtitle
describe 'status row', ->
it "displays no stats for future timebox", ->
@prepareNoneAcceptedData()
@stubApp({
startDate:new Date(2051, 5, 15),
endDate:new Date(2051, 5, 16, 23, 59, 59)
})
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
testSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.then (configAcceptance) ->
expect(!!configAcceptance.title).toBeFalsy()
expect(!!configAcceptance.status).toBeFalsy()
expect(!!configAcceptance.message).toBeFalsy()
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
configTests = testSpy.firstCall.returnValue
expect(!!configTests.title).toBeFalsy()
expect(!!configTests.status).toBeFalsy()
expect(!!configTests.message).toBeFalsy()
it "displays no alarming acceptance stats when timebox has just started", ->
@prepareNoneAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "0% Accepted"
expect(configAcceptance.subtitle).toBe "(0 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_NO_ACCEPTED_WORK
it "does not display defect stats when no active defects for current timebox", ->
@prepareNoActiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
it "displays defect stats for current timebox", ->
@prepareFiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(configDefects.title).toBe "5 Active Defects"
expect(configDefects.status).toBe "warn"
expect(configDefects.message).toBe app.self.CURRENT_WITH_DEFECTS
it "displays acceptance warning 5 days into a long timebox", ->
@prepareNoneAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 1)
endDate:new Date(2011, 4, 28, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "0% Accepted"
expect(configAcceptance.subtitle).toBe "(0 of 27 Points)"
expect(configAcceptance.status).toBe "warn"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance pending 5 days into a long timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 1)
endDate:new Date(2011, 4, 28, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance pending halfway through a short timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 6, 23, 59, 59)
today:new Date(2011, 4, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance error when all work not accepted from past timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "error"
expect(configAcceptance.message).toBe app.self.PAST_WITH_SOME_UNACCEPTED_WORK
it "displays defect error when active defects remain from past timebox", ->
@prepareFiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(configDefects.title).toBe "5 Active Defects"
expect(configDefects.status).toBe "error"
expect(configDefects.message).toBe app.self.PAST_WITH_DEFECTS
it "does not display defect stats when no active defects for past timebox", ->
@prepareNoActiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
it "displays positive acceptance stats when all work accepted for past timebox", ->
@prepareAllAcceptedData()
@stubApp
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe ""
it "displays positive acceptance stats when all work accepted or released for past timebox", ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Released"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Released"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp
scheduleStates:["Defined", "In-Progress", "Completed", "Accepted", "Released"],
startDate:new Date(2011, 4, 2),
endDate:new Date(2011, 4, 20, 23, 59, 59),
today:new Date(2011, 5, 5)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe ""
it "displays success acceptance stats with work items without estimates but all accepted", ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 6, 23, 59, 59)
today:new Date(2011, 4, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(18 of 18 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe "3 work items have no estimate."
it "displays gently scolding for past timebox with work accepted late", ->
@prepareAllAcceptedData()
@stubApp(
startDate:new Date(2011, 3, 2)
endDate:new Date(2011, 3, 20, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe app.self.PAST_WITH_ACCEPTED_WORK_AFTER_END_DATE
it "does not display stats when there are no tests", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@ajax.whenQuerying('defectsuite').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(!!configTests.title).toBeFalsy()
expect(!!configTests.status).toBeFalsy()
expect(!!configTests.message).toBeFalsy()
it "displays pending when less than halfway or 5 days", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 8)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "pending"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays warning if all failing tests during current timebox", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "0% Tests Passing"
expect(configTests.subtitle).toBe "(0 of 9)"
expect(configTests.status).toBe "warn"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays pending if some failing tests during current timebox", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "pending"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays success if no failing tests during past, current, past timeboxes", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "100% Tests Passing"
expect(configTests.subtitle).toBe "(9 of 9)"
expect(configTests.status).toBe "success"
expect(configTests.message).toBe app.self.CURRENT_TESTS_PASSING
it "displays error if any failing tests during past timeboxes", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "error"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it 'cleans up app content when no timeboxes available', ->
@createApp({}).then (app) =>
expect(app.down('#dataContainer')).not.toBeNull()
app.onNoAvailableTimeboxes()
expect(app.down('#dataContainer')).toBeNull()
| true | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.apps.iterationsummary.IterationSummaryApp'
]
describe 'Rally.apps.iterationsummary.IterationSummaryApp', ->
helpers
getContext: (initialValues) ->
globalContext = Rally.environment.getContext()
Ext.create 'Rally.app.Context',
initialValues:Ext.merge
project:globalContext.getProject()
workspace:globalContext.getWorkspace()
user:globalContext.getUser()
subscription:globalContext.getSubscription()
timebox: Ext.create 'Rally.app.TimeboxScope', record: @mom.getRecord 'iteration'
, initialValues
createApp: (initialValues) ->
@container = Ext.create('Ext.Container', {
renderTo:'testDiv'
})
app = Ext.create('Rally.apps.iterationsummary.IterationSummaryApp', {
context: @getContext(initialValues)
})
@container.add(app)
if app.getContext().getTimeboxScope().getRecord()
@waitForComponentReady(app)
else
@once condition: -> app.down '#unscheduledBlankSlate'
stubApp: (config) ->
@stubPromiseFunction(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getScheduleStates',
(config.scheduleStates || ["Defined", "In-Progress", "Completed", "Accepted"]))
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getStartDate').returns(config.startDate || new Date())
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, 'getEndDate').returns(config.endDate || new Date())
@_stubIterationQuery(config.tzOffset || 0)
@stub(Rally.util.Timebox, 'getToday').returns(config.today || new Date())
stubTimeBoxInfo: (orientation) ->
timeOrientation: orientation
timeboxLength: 4
daysRemaining: 0
_stubIterationQuery: (tzOffset = 0) ->
@ajax.whenQuerying('iteration').respondWith([{
_refObjectName:"Iteration 3", Name:"Iteration 3", ObjectID:3,
StartDate:"2010-07-11T00:00:00.000Z", EndDate:"2010-07-15T23:59:59.000Z"
}
], {
schema:
properties:
EndDate:
format:
tzOffset: tzOffset * 60
})
prepareNoneAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([{
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 2
Open: 2
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0,
ScheduleState:"In-Progress",
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0,
ScheduleState:"In-Progress",
AcceptedDate:null
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareFiveDefectsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 2
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
},
{
Summary:
Defects:
State:
Closed: 2
Open: 0
}
])
prepareNoActiveDefectsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Backlog"
AcceptedDate:null,
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 1
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 0
Open: 0
},
{
Summary:
Defects:
State:
Closed: 2
Open: 0
},
{
Summary:
Defects:
State:
Closed: 1
Open: 0
}
])
prepareSomeAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareAllAcceptedData: ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
prepareSomeFailingTestsData: ->
@ajax.whenQuerying('userstory').respondWith([
{
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"Hello PI:NAME:<NAME>END_PI": 1
}
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
{
Summary:
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"Hello PI:NAME:<NAME>END_PI": 1
}
])
@ajax.whenQuerying('testset').respondWith([
{
Summary:
TestCases:
LastVerdict:
Pass: 1
Fail: 1
"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI": 1
}
])
prepareTestSetData: (testSetSummaryVerdicts) ->
@ajax.whenQuerying('userstory').respondWith()
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith([
{
Summary:
TestCases:
LastVerdict: testSetSummaryVerdicts
}
])
beforeEach ->
@_stubIterationQuery()
afterEach ->
@container?.destroy()
it "does not call wsapidatastore if models are unavailable", ->
@stub(Rally.data.ModelFactory, 'getModels', (options) ->
results = {}
switch options.types[0]
when 'Iteration'
results.Iteration = Rally.test.mock.data.WsapiModelFactory.getModel('Iteration')
when 'UserStory'
results.UserStoRally.test.mock.data.WsapiModelFactoryctory.getModel('UserStory')
when 'AllowedAttributeValue'
results.AllowedAttribuRally.test.mock.data.WsapiModelFactorydelFactory.getModel('AllowedAttributeValue')
options.success.call(options.scope, results)
)
displayStatusRowsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_displayStatusRows')
@createApp({}).then (app) =>
expect(displayStatusRowsSpy).not.toHaveBeenCalled()
it "calls wsapidatastore if models are available", ->
displayStatusRowsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_displayStatusRows')
@createApp({}).then (app) =>
@waitForCallback(displayStatusRowsSpy)
it "getPostAcceptedState with no before or after state", ->
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBeNull()
it "getPostAcceptedState with only a before state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Idea", "Defined", "In-Progress", "Completed", "Accepted"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBeNull()
it "getPostAcceptedState with only an after state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Defined", "In-Progress", "Completed", "Accepted", "Released"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBe "Released"
it "getPostAcceptedState with a before and after state", ->
@stub Rally.test.mock.data.WsapiModelFactory.getUserStoryModel().getField('ScheduleState'), 'getAllowedStringValues', -> ["Idea", "Defined", "In-Progress", "Completed", "Accepted", "Really Really Done"]
@createApp({}).then (app) =>
app._getPostAcceptedState().always (postAcceptedState) ->
expect(postAcceptedState).toBe "Really Really Done"
it "does not aggregate testset and defectsuite data for HS subscriptions", ->
@prepareFiveDefectsData()
@stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_isHsOrTeamEdition').returns true
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
# only the 2 defects from user story - should exclude the 3 from defect suite
expect(configDefects.title).toBe "2 Active Defects"
expect(configDefects.status).toBe "error"
expect(configDefects.message).toBe app.self.PAST_WITH_DEFECTS
expect(testsSpy).not.toHaveBeenCalled()
it "does aggregate testset data for UE or EE subscriptions", ->
@prepareTestSetData(Pass: 2, Fail: 1, Inconclusive: 1)
@createApp({}).then (app) =>
@waitForVisible(
css: ".#{Ext.baseCSSPrefix}component.header.testsPassing"
text: "50% Tests Passing"
)
it "sets timeBoxInfo every time iteraton scope is changed", ->
@prepareTestSetData(Pass: 2, Fail: 1, Inconclusive: 1)
timeBoxInfoStub = @stub(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_determineTimeBoxInfo')
timeBoxInfoStub.returns(@stubTimeBoxInfo('past'))
@createApp({}).then (app) =>
@waitForVisible(
css: '.timeboxStatusRow'
text: "50% Tests Passing"
).then =>
expect(timeBoxInfoStub.callCount).toBe 1
timeBoxInfoStub.returns(@stubTimeBoxInfo('future'))
app.onScopeChange()
@waitForComponentReady(app).then =>
@waitForNotVisible(
css: '.timeboxStatusRow'
text: "50% Tests Passing"
).then =>
expect(timeBoxInfoStub.callCount).toBe 2
it "refreshes app on objectUpdate of artifacts", ->
@createApp({}).then (app) =>
addStub = @stub(app, 'add')
messageBus = Rally.environment.getMessageBus()
for type in ['Defect', 'HierarchicalRequirement', 'DefectSuite', 'TestSet', 'TestCase']
messageBus.publish(Rally.Message.objectUpdate, @mom.getRecord(type))
expect(addStub.callCount).toBe 5
it "does not refresh app on objectUpdate of non-artifacts", ->
@createApp({}).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish(Rally.Message.objectUpdate, @mom.getRecord('Release'))
expect(addSpy).not.toHaveBeenCalled()
it "refreshes app on bulkUpdate of artifacts", ->
@createApp({}).then (app) =>
addStub = @stub(app, 'add')
messageBus = Rally.environment.getMessageBus()
messageBus.publish(Rally.Message.bulkUpdate, @mom.getRecord(type) for type in ['Defect', 'HierarchicalRequirement', 'DefectSuite', 'TestSet', 'TestCase'])
expect(addStub.callCount).toBe 1
it "does not refresh app on bulkUpdate of non-artifacts", ->
@createApp({}).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish(Rally.Message.bulkUpdate, @mom.getRecord(type) for type in ['ConversationPost', 'Release'])
expect(addSpy).not.toHaveBeenCalled()
it 'does not refresh app on objectUpdate if unscheduled', ->
@createApp(timebox: Ext.create 'Rally.app.TimeboxScope',
type: 'iteration',
record: null
).then (app) =>
addSpy = @spy(app, 'add')
Rally.environment.getMessageBus().publish Rally.Message.objectUpdate, @mom.getRecord 'defect'
expect(addSpy).not.toHaveBeenCalled()
it "only fetches iteration schema once", ->
httpGetSpy = @spy(Rally.env.IoProvider.prototype, 'httpGet')
@createApp({}).then (app) =>
expect(httpGetSpy).toHaveBeenCalledOnce()
app.calculateTimeboxInfo().then ->
expect(httpGetSpy).toHaveBeenCalledOnce()
it "rounds estimates to two decimal places", ->
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith()
# the PEs in here add up to 14.829999999999998, which is needed for the rounding test above
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:2.23
ScheduleState:"Completed"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.13
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.43
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.04
ScheduleState:"In-Progress"
AcceptedDate:null
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp({
startDate:new Date(2011, 4, 13),
endDate:new Date(2011, 4, 20, 23, 59, 59),
today:new Date(2011, 4, 14)
})
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
summedPlanEstimate = 0
Ext.Array.forEach(app.results.userstory, (s) ->
summedPlanEstimate += s.get('PlanEstimate')
)
expect(summedPlanEstimate.toString().length).toBeGreaterThan 5
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expectedSubtitle = Ext.String.format("(0 of {0} Points)", Math.round(summedPlanEstimate * 100) / 100)
expect(configAcceptance.subtitle).toBe expectedSubtitle
describe 'status row', ->
it "displays no stats for future timebox", ->
@prepareNoneAcceptedData()
@stubApp({
startDate:new Date(2051, 5, 15),
endDate:new Date(2051, 5, 16, 23, 59, 59)
})
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
testSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.then (configAcceptance) ->
expect(!!configAcceptance.title).toBeFalsy()
expect(!!configAcceptance.status).toBeFalsy()
expect(!!configAcceptance.message).toBeFalsy()
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
configTests = testSpy.firstCall.returnValue
expect(!!configTests.title).toBeFalsy()
expect(!!configTests.status).toBeFalsy()
expect(!!configTests.message).toBeFalsy()
it "displays no alarming acceptance stats when timebox has just started", ->
@prepareNoneAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "0% Accepted"
expect(configAcceptance.subtitle).toBe "(0 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_NO_ACCEPTED_WORK
it "does not display defect stats when no active defects for current timebox", ->
@prepareNoActiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
it "displays defect stats for current timebox", ->
@prepareFiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(configDefects.title).toBe "5 Active Defects"
expect(configDefects.status).toBe "warn"
expect(configDefects.message).toBe app.self.CURRENT_WITH_DEFECTS
it "displays acceptance warning 5 days into a long timebox", ->
@prepareNoneAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 1)
endDate:new Date(2011, 4, 28, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "0% Accepted"
expect(configAcceptance.subtitle).toBe "(0 of 27 Points)"
expect(configAcceptance.status).toBe "warn"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance pending 5 days into a long timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 1)
endDate:new Date(2011, 4, 28, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance pending halfway through a short timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 6, 23, 59, 59)
today:new Date(2011, 4, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe app.self.CURRENT_WITH_SOME_UNACCEPTED_WORK
it "displays acceptance error when all work not accepted from past timebox", ->
@prepareSomeAcceptedData()
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "48% Accepted"
expect(configAcceptance.subtitle).toBe "(13 of 27 Points)"
expect(configAcceptance.status).toBe "error"
expect(configAcceptance.message).toBe app.self.PAST_WITH_SOME_UNACCEPTED_WORK
it "displays defect error when active defects remain from past timebox", ->
@prepareFiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(configDefects.title).toBe "5 Active Defects"
expect(configDefects.status).toBe "error"
expect(configDefects.message).toBe app.self.PAST_WITH_DEFECTS
it "does not display defect stats when no active defects for past timebox", ->
@prepareNoActiveDefectsData()
@stubApp(
startDate:new Date(2011, 4, 13)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 14)
)
defectSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getDefectsConfigObject')
@createApp({}).then (app) =>
configDefects = defectSpy.firstCall.returnValue
expect(!!configDefects.title).toBeFalsy()
expect(!!configDefects.status).toBeFalsy()
expect(!!configDefects.message).toBeFalsy()
it "displays positive acceptance stats when all work accepted for past timebox", ->
@prepareAllAcceptedData()
@stubApp
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe ""
it "displays positive acceptance stats when all work accepted or released for past timebox", ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:1.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Released"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Released"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Released"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp
scheduleStates:["Defined", "In-Progress", "Completed", "Accepted", "Released"],
startDate:new Date(2011, 4, 2),
endDate:new Date(2011, 4, 20, 23, 59, 59),
today:new Date(2011, 5, 5)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe ""
it "displays success acceptance stats with work items without estimates but all accepted", ->
@ajax.whenQuerying('userstory').respondWith([
{
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-14T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-13T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:3.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-12T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:4.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:5.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-10T16:45:05Z"
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('defectsuite').respondWith([
{
Summary:
Defects:
State:
Closed: 2
Open: 1
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
},
{
Summary:
Defects:
State:
Closed: 2
Open: 2
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
}
])
@ajax.whenQuerying('defect').respondWith([
{
PlanEstimate:null
ScheduleState:"In-Progress"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@ajax.whenQuerying('testset').respondWith([
{
PlanEstimate:null
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
},
{
PlanEstimate:2.0
ScheduleState:"Accepted"
AcceptedDate:"2011-05-11T16:45:05Z"
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
}
])
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 6, 23, 59, 59)
today:new Date(2011, 4, 5)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(18 of 18 Points)"
expect(configAcceptance.status).toBe "pending"
expect(configAcceptance.message).toBe "3 work items have no estimate."
it "displays gently scolding for past timebox with work accepted late", ->
@prepareAllAcceptedData()
@stubApp(
startDate:new Date(2011, 3, 2)
endDate:new Date(2011, 3, 20, 23, 59, 59)
today:new Date(2011, 4, 20)
)
acceptanceSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getAcceptanceConfigObject')
@createApp({}).then (app) =>
acceptanceSpy.firstCall.returnValue.always (configAcceptance) ->
expect(configAcceptance.title).toBe "100% Accepted"
expect(configAcceptance.subtitle).toBe "(27 of 27 Points)"
expect(configAcceptance.status).toBe "success"
expect(configAcceptance.message).toBe app.self.PAST_WITH_ACCEPTED_WORK_AFTER_END_DATE
it "does not display stats when there are no tests", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@ajax.whenQuerying('defectsuite').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@ajax.whenQuerying('defect').respondWith()
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 0
])
@stubApp(
startDate:new Date(2011, 4, 2)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 5)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(!!configTests.title).toBeFalsy()
expect(!!configTests.status).toBeFalsy()
expect(!!configTests.message).toBeFalsy()
it "displays pending when less than halfway or 5 days", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 8)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "pending"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays warning if all failing tests during current timebox", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 0
Fail: 3
])
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "0% Tests Passing"
expect(configTests.subtitle).toBe "(0 of 9)"
expect(configTests.status).toBe "warn"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays pending if some failing tests during current timebox", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "pending"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it "displays success if no failing tests during past, current, past timeboxes", ->
@ajax.whenQuerying('userstory').respondWith([
Summary:
Defects:
State:
Closed: 0
Open: 0
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@ajax.whenQuerying('defectsuite').respondWith()
@ajax.whenQuerying('defect').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@ajax.whenQuerying('testset').respondWith([
Summary:
TestCases:
LastVerdict:
Pass: 3
Fail: 0
])
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 4, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "100% Tests Passing"
expect(configTests.subtitle).toBe "(9 of 9)"
expect(configTests.status).toBe "success"
expect(configTests.message).toBe app.self.CURRENT_TESTS_PASSING
it "displays error if any failing tests during past timeboxes", ->
@prepareSomeFailingTestsData()
@stubApp(
startDate:new Date(2011, 4, 6)
endDate:new Date(2011, 4, 20, 23, 59, 59)
today:new Date(2011, 5, 16)
)
testsSpy = @spy(Rally.apps.iterationsummary.IterationSummaryApp.prototype, '_getTestsConfigObject')
@createApp({}).then (app) =>
configTests = testsSpy.firstCall.returnValue
expect(configTests.title).toBe "33% Tests Passing"
expect(configTests.subtitle).toBe "(3 of 9)"
expect(configTests.status).toBe "error"
expect(configTests.message).toBe app.self.CURRENT_TESTS_FAILING_MESSAGE
it 'cleans up app content when no timeboxes available', ->
@createApp({}).then (app) =>
expect(app.down('#dataContainer')).not.toBeNull()
app.onNoAvailableTimeboxes()
expect(app.down('#dataContainer')).toBeNull()
|
[
{
"context": "ules.bookmark(comments, {\n csrfToken: \"foobar\",\n target: \"/foo/\"\n })\n ",
"end": 736,
"score": 0.7269014716148376,
"start": 730,
"tag": "PASSWORD",
"value": "foobar"
}
] | game/static/spirit/scripts/test/suites/bookmark-spec.coffee | Yoann-Vie/esgi-hearthstone | 3 | describe "bookmark plugin tests", ->
comments = null
bookmarks = null
mark = null
Bookmark = null
Mark = null
post = null
beforeEach ->
fixtures = jasmine.getFixtures()
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures('bookmark.html')
# Promise is async, so must callFake a sync thing
post = spyOn(window, 'fetch')
post.and.callFake( -> {
then: (func) ->
func({ok: true})
return {
catch: -> {then: (func) -> func()}
}
})
comments = document.querySelectorAll('.comment')
bookmarks = stModules.bookmark(comments, {
csrfToken: "foobar",
target: "/foo/"
})
mark = bookmarks[0].mark
Bookmark = stModules.Bookmark
Mark = stModules.Mark
# Trigger all waypoints
bookmarks.forEach((bm) ->
bm.onWaypoint()
)
it "sends the first comment number", ->
expect(post.calls.any()).toEqual(true)
expect(post.calls.argsFor(0)[0]).toEqual('/foo/')
expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar")
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
it "stores the last comment number", ->
expect(mark.commentNumber).toEqual(2)
it "stores the same mark in every comment", ->
bookmark_1 = bookmarks[0]
bookmark_2 = bookmarks[bookmarks.length - 1]
expect(bookmark_1.mark).toEqual(bookmark_2.mark)
it "does not post on scroll up", ->
post.calls.reset()
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(mark.commentNumber).toEqual(2)
expect(post.calls.any()).toEqual(false)
it "does post on scroll down", ->
post.calls.reset()
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.number = 999
bookmark_2.onWaypoint()
expect(mark.commentNumber).toEqual(999)
expect(post.calls.any()).toEqual(true)
it "gets the comment number from the address bar", ->
org_location_hash = window.location.hash
window.location.hash = ""
try
window.location.hash = "http://example.com/foo/#c5"
newMark = new Mark()
# it substract 1 from the real comment number
expect(newMark.commentNumber).toEqual 4
window.location.hash = "http://example.com/foo/"
newMark = new Mark()
expect(newMark.commentNumber).toEqual 0
window.location.hash = "http://example.com/foo/#foobar5"
newMark = new Mark()
expect(newMark.commentNumber).toEqual 0
finally
window.location.hash = org_location_hash
it "sends only one comment number in a given time", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
# won't post if already sending
mark.commentNumber = 0
bookmark_2 = bookmarks[bookmarks.length - 1]
mark.isSending = true
bookmark_2.onWaypoint()
expect(post.calls.any()).toEqual(false)
mark.commentNumber = 0
post.calls.reset()
mark.isSending = false
bookmark_2.onWaypoint()
expect(post.calls.any()).toEqual(true)
expect(mark.isSending).toEqual(false)
it "sends current comment number after sending previous when current > previous", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
post.and.callFake( -> {
then: (func) ->
# isSending == true, so this should just put it in queue
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.onWaypoint()
func({ok: true})
return {
catch: -> {then: (func) -> func()}
}
})
mark.commentNumber = -1
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(post.calls.count()).toEqual(2)
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
expect(post.calls.argsFor(1)[1].body.get('comment_number')).toEqual('2')
# Should do nothing
post.calls.reset()
bookmark_1.onWaypoint()
expect(post.calls.any()).toEqual(false)
it "sends next after server error", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
post.and.callFake( -> {
then: ->
# isSending == true, so this should just put it in queue
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.onWaypoint()
return {
catch: (func) ->
func({message: 'connection error'})
return {then: (func) -> func()}
}
})
log = spyOn(console, 'log')
log.and.callFake( -> )
mark.commentNumber = -1
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(post.calls.count()).toEqual(2)
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
expect(post.calls.argsFor(1)[1].body.get('comment_number')).toEqual('2')
expect(log.calls.count()).toEqual(2)
expect(log.calls.argsFor(0)[0]).toEqual('connection error')
expect(log.calls.argsFor(1)[0]).toEqual('connection error')
| 199622 | describe "bookmark plugin tests", ->
comments = null
bookmarks = null
mark = null
Bookmark = null
Mark = null
post = null
beforeEach ->
fixtures = jasmine.getFixtures()
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures('bookmark.html')
# Promise is async, so must callFake a sync thing
post = spyOn(window, 'fetch')
post.and.callFake( -> {
then: (func) ->
func({ok: true})
return {
catch: -> {then: (func) -> func()}
}
})
comments = document.querySelectorAll('.comment')
bookmarks = stModules.bookmark(comments, {
csrfToken: "<PASSWORD>",
target: "/foo/"
})
mark = bookmarks[0].mark
Bookmark = stModules.Bookmark
Mark = stModules.Mark
# Trigger all waypoints
bookmarks.forEach((bm) ->
bm.onWaypoint()
)
it "sends the first comment number", ->
expect(post.calls.any()).toEqual(true)
expect(post.calls.argsFor(0)[0]).toEqual('/foo/')
expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar")
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
it "stores the last comment number", ->
expect(mark.commentNumber).toEqual(2)
it "stores the same mark in every comment", ->
bookmark_1 = bookmarks[0]
bookmark_2 = bookmarks[bookmarks.length - 1]
expect(bookmark_1.mark).toEqual(bookmark_2.mark)
it "does not post on scroll up", ->
post.calls.reset()
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(mark.commentNumber).toEqual(2)
expect(post.calls.any()).toEqual(false)
it "does post on scroll down", ->
post.calls.reset()
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.number = 999
bookmark_2.onWaypoint()
expect(mark.commentNumber).toEqual(999)
expect(post.calls.any()).toEqual(true)
it "gets the comment number from the address bar", ->
org_location_hash = window.location.hash
window.location.hash = ""
try
window.location.hash = "http://example.com/foo/#c5"
newMark = new Mark()
# it substract 1 from the real comment number
expect(newMark.commentNumber).toEqual 4
window.location.hash = "http://example.com/foo/"
newMark = new Mark()
expect(newMark.commentNumber).toEqual 0
window.location.hash = "http://example.com/foo/#foobar5"
newMark = new Mark()
expect(newMark.commentNumber).toEqual 0
finally
window.location.hash = org_location_hash
it "sends only one comment number in a given time", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
# won't post if already sending
mark.commentNumber = 0
bookmark_2 = bookmarks[bookmarks.length - 1]
mark.isSending = true
bookmark_2.onWaypoint()
expect(post.calls.any()).toEqual(false)
mark.commentNumber = 0
post.calls.reset()
mark.isSending = false
bookmark_2.onWaypoint()
expect(post.calls.any()).toEqual(true)
expect(mark.isSending).toEqual(false)
it "sends current comment number after sending previous when current > previous", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
post.and.callFake( -> {
then: (func) ->
# isSending == true, so this should just put it in queue
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.onWaypoint()
func({ok: true})
return {
catch: -> {then: (func) -> func()}
}
})
mark.commentNumber = -1
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(post.calls.count()).toEqual(2)
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
expect(post.calls.argsFor(1)[1].body.get('comment_number')).toEqual('2')
# Should do nothing
post.calls.reset()
bookmark_1.onWaypoint()
expect(post.calls.any()).toEqual(false)
it "sends next after server error", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
post.and.callFake( -> {
then: ->
# isSending == true, so this should just put it in queue
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.onWaypoint()
return {
catch: (func) ->
func({message: 'connection error'})
return {then: (func) -> func()}
}
})
log = spyOn(console, 'log')
log.and.callFake( -> )
mark.commentNumber = -1
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(post.calls.count()).toEqual(2)
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
expect(post.calls.argsFor(1)[1].body.get('comment_number')).toEqual('2')
expect(log.calls.count()).toEqual(2)
expect(log.calls.argsFor(0)[0]).toEqual('connection error')
expect(log.calls.argsFor(1)[0]).toEqual('connection error')
| true | describe "bookmark plugin tests", ->
comments = null
bookmarks = null
mark = null
Bookmark = null
Mark = null
post = null
beforeEach ->
fixtures = jasmine.getFixtures()
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures('bookmark.html')
# Promise is async, so must callFake a sync thing
post = spyOn(window, 'fetch')
post.and.callFake( -> {
then: (func) ->
func({ok: true})
return {
catch: -> {then: (func) -> func()}
}
})
comments = document.querySelectorAll('.comment')
bookmarks = stModules.bookmark(comments, {
csrfToken: "PI:PASSWORD:<PASSWORD>END_PI",
target: "/foo/"
})
mark = bookmarks[0].mark
Bookmark = stModules.Bookmark
Mark = stModules.Mark
# Trigger all waypoints
bookmarks.forEach((bm) ->
bm.onWaypoint()
)
it "sends the first comment number", ->
expect(post.calls.any()).toEqual(true)
expect(post.calls.argsFor(0)[0]).toEqual('/foo/')
expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar")
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
it "stores the last comment number", ->
expect(mark.commentNumber).toEqual(2)
it "stores the same mark in every comment", ->
bookmark_1 = bookmarks[0]
bookmark_2 = bookmarks[bookmarks.length - 1]
expect(bookmark_1.mark).toEqual(bookmark_2.mark)
it "does not post on scroll up", ->
post.calls.reset()
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(mark.commentNumber).toEqual(2)
expect(post.calls.any()).toEqual(false)
it "does post on scroll down", ->
post.calls.reset()
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.number = 999
bookmark_2.onWaypoint()
expect(mark.commentNumber).toEqual(999)
expect(post.calls.any()).toEqual(true)
it "gets the comment number from the address bar", ->
org_location_hash = window.location.hash
window.location.hash = ""
try
window.location.hash = "http://example.com/foo/#c5"
newMark = new Mark()
# it substract 1 from the real comment number
expect(newMark.commentNumber).toEqual 4
window.location.hash = "http://example.com/foo/"
newMark = new Mark()
expect(newMark.commentNumber).toEqual 0
window.location.hash = "http://example.com/foo/#foobar5"
newMark = new Mark()
expect(newMark.commentNumber).toEqual 0
finally
window.location.hash = org_location_hash
it "sends only one comment number in a given time", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
# won't post if already sending
mark.commentNumber = 0
bookmark_2 = bookmarks[bookmarks.length - 1]
mark.isSending = true
bookmark_2.onWaypoint()
expect(post.calls.any()).toEqual(false)
mark.commentNumber = 0
post.calls.reset()
mark.isSending = false
bookmark_2.onWaypoint()
expect(post.calls.any()).toEqual(true)
expect(mark.isSending).toEqual(false)
it "sends current comment number after sending previous when current > previous", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
post.and.callFake( -> {
then: (func) ->
# isSending == true, so this should just put it in queue
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.onWaypoint()
func({ok: true})
return {
catch: -> {then: (func) -> func()}
}
})
mark.commentNumber = -1
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(post.calls.count()).toEqual(2)
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
expect(post.calls.argsFor(1)[1].body.get('comment_number')).toEqual('2')
# Should do nothing
post.calls.reset()
bookmark_1.onWaypoint()
expect(post.calls.any()).toEqual(false)
it "sends next after server error", ->
post.calls.reset()
expect(post.calls.any()).toEqual(false)
post.and.callFake( -> {
then: ->
# isSending == true, so this should just put it in queue
bookmark_2 = bookmarks[bookmarks.length - 1]
bookmark_2.onWaypoint()
return {
catch: (func) ->
func({message: 'connection error'})
return {then: (func) -> func()}
}
})
log = spyOn(console, 'log')
log.and.callFake( -> )
mark.commentNumber = -1
bookmark_1 = bookmarks[0]
bookmark_1.onWaypoint()
expect(post.calls.count()).toEqual(2)
expect(post.calls.argsFor(0)[1].body.get('comment_number')).toEqual('1')
expect(post.calls.argsFor(1)[1].body.get('comment_number')).toEqual('2')
expect(log.calls.count()).toEqual(2)
expect(log.calls.argsFor(0)[0]).toEqual('connection error')
expect(log.calls.argsFor(1)[0]).toEqual('connection error')
|
[
{
"context": "rg/TR/websockets).\n#\n# * Copyright (C) 2010-2012 [Jeff Mesnil](http://jmesnil.net/)\n# * Copyright (C) 2012 [Fus",
"end": 166,
"score": 0.9998621344566345,
"start": 155,
"tag": "NAME",
"value": "Jeff Mesnil"
},
{
"context": ".](http://fusesource.com)\n# * Copyright (C... | src/stomp.coffee | pawanaraballi/stomp-websocket | 0 |
# **STOMP Over Web Socket** is a JavaScript STOMP Client using
# [HTML5 Web Sockets API](http://www.w3.org/TR/websockets).
#
# * Copyright (C) 2010-2012 [Jeff Mesnil](http://jmesnil.net/)
# * Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
# * Copyright (C) 2017 [Deepak Kumar](https://www.kreatio.com)
#
# This library supports:
#
# * [STOMP 1.0](http://stomp.github.com/stomp-specification-1.0.html)
# * [STOMP 1.1](http://stomp.github.com/stomp-specification-1.1.html)
# * [STOMP 1.2](http://stomp.github.com/stomp-specification-1.2.html)
#
# The library is accessed through the `Stomp` object that is set on the `window`
# when running in a Web browser.
###
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2010-2013 [Jeff Mesnil](http://jmesnil.net/)
Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
Copyright (C) 2017 [Deepak Kumar](https://www.kreatio.com)
###
# @mixin
#
# @private
Byte =
# LINEFEED byte (octet 10)
LF: '\x0A'
# NULL byte (octet 0)
NULL: '\x00'
# @see http://stomp.github.com/stomp-specification-1.2.html#STOMP_Frames STOMP Frame
#
# Frame class represents a STOMP frame
#
class Frame
# Frame constructor. `command`, `headers` and `body` are available as properties.
#
# Many of the Client methods pass instance of received Frame to the callback.
#
# @param command [String]
# @param headers [Object]
# @param body [String]
# @param escapeHeaderValues [Boolean]
constructor: (@command, @headers={}, @body='', @escapeHeaderValues = false) ->
# Provides a textual representation of the frame
# suitable to be sent to the server
#
# @private
toString: ->
lines = [@command]
skipContentLength = if (@headers['content-length'] == false) then true else false
delete @headers['content-length'] if skipContentLength
for own name, value of @headers
if @escapeHeaderValues && @command != 'CONNECT' && @command != 'CONNECTED'
lines.push("#{name}:#{Frame.frEscape(value)}")
else
lines.push("#{name}:#{value}")
if @body && !skipContentLength
lines.push("content-length:#{Frame.sizeOfUTF8(@body)}")
lines.push(Byte.LF + @body)
return lines.join(Byte.LF)
# Compute the size of a UTF-8 string by counting its number of bytes
# (and not the number of characters composing the string)
#
# @private
@sizeOfUTF8: (s)->
if s
encodeURI(s).match(/%..|./g).length
else
0
# Unmarshall a single STOMP frame from a `data` string
#
# @private
unmarshallSingle= (data, escapeHeaderValues=false) ->
# search for 2 consecutives LF byte to split the command
# and headers from the body
divider = data.search(///#{Byte.LF}#{Byte.LF}///)
headerLines = data.substring(0, divider).split(Byte.LF)
command = headerLines.shift()
headers = {}
# utility function to trim any whitespace before and after a string
trim= (str) ->
str.replace(/^\s+|\s+$/g,'')
# Parse headers in reverse order so that for repeated headers, the 1st
# value is used
for line in headerLines.reverse()
idx = line.indexOf(':')
if escapeHeaderValues && command != 'CONNECT' && command != 'CONNECTED'
headers[trim(line.substring(0, idx))] = Frame.frUnEscape(trim(line.substring(idx + 1)))
else
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1))
# Parse body
# check for content-length or topping at the first NULL byte found.
body = ''
# skip the 2 LF bytes that divides the headers from the body
start = divider + 2
if headers['content-length']
len = parseInt headers['content-length']
body = ('' + data).substring(start, start + len)
else
chr = null
for i in [start...data.length]
chr = data.charAt(i)
break if chr is Byte.NULL
body += chr
return new Frame(command, headers, body, escapeHeaderValues)
# Split the data before unmarshalling every single STOMP frame.
# Web socket servers can send multiple frames in a single websocket message.
# If the message size exceeds the websocket message size, then a single
# frame can be fragmented across multiple messages.
#
# `datas` is a string.
#
# returns an *array* of Frame objects
#
# @private
@unmarshall: (datas, escapeHeaderValues=false) ->
# Ugly list comprehension to split and unmarshall *multiple STOMP frames*
# contained in a *single WebSocket frame*.
# The data is split when a NULL byte (followed by zero or many LF bytes) is
# found
frames = datas.split(///#{Byte.NULL}#{Byte.LF}*///)
r =
frames: []
partial: ''
r.frames = (unmarshallSingle(frame, escapeHeaderValues) for frame in frames[0..-2])
# If this contains a final full message or just a acknowledgement of a PING
# without any other content, process this frame, otherwise return the
# contents of the buffer to the caller.
last_frame = frames[-1..][0]
if last_frame is Byte.LF or (last_frame.search ///#{Byte.NULL}#{Byte.LF}*$///) isnt -1
r.frames.push(unmarshallSingle(last_frame, escapeHeaderValues))
else
r.partial = last_frame
return r
# Marshall a Stomp frame
#
# @private
@marshall: (command, headers, body, escapeHeaderValues) ->
frame = new Frame(command, headers, body, escapeHeaderValues)
return frame.toString() + Byte.NULL
# Escape header values
#
# @private
@frEscape: (str) ->
("" + str).replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/:/g, "\\c")
# Escape header values
#
# @private
@frUnEscape: (str) ->
("" + str).replace(/\\r/g, "\r").replace(/\\n/g, "\n").replace(/\\c/g, ":").replace(/\\\\/g, "\\")
# STOMP Client Class
#
# All STOMP protocol is exposed as methods of this class (`connect()`,
# `send()`, etc.)
class Client
# Please do not create instance of this class directly, use one of the methods {Stomp~client}, {Stomp~over}
# or {overTCP}
# in Stomp.
#
# @private
#
# @see Stomp
constructor: (ws_fn) ->
@ws_fn = ->
ws= ws_fn()
ws.binaryType = "arraybuffer"
ws
# @property reconnect_delay [Number] automatically reconnect with delay in milliseconds, set to 0 to disable
@reconnect_delay= 0
# used to index subscribers
@counter = 0
# @property [Boolean] current connection state
@connected = false
# @property [{outgoing: Number, incoming: Number}] outgoing and incoming
# heartbeat in milliseconds, set to 0 to disable
@heartbeat = {
# send heartbeat every 10s by default (value is in ms)
outgoing: 10000
# expect to receive server heartbeat at least every 10s by default
# (value in ms)
incoming: 10000
}
# maximum *WebSocket* frame size sent by the client. If the STOMP frame
# is bigger than this value, the STOMP frame will be sent using multiple
# WebSocket frames (default is 16KiB)
@maxWebSocketFrameSize = 16*1024
# subscription callbacks indexed by subscriber's ID
@subscriptions = {}
@partialData = ''
# By default, debug messages are logged in the window's console if it is defined.
# This method is called for every actual transmission of the STOMP frames over the
# WebSocket.
#
# It is possible to set a `debug(message)` method
# on a client instance to handle differently the debug messages:
#
# @example
# client.debug = function(str) {
# // append the debug log to a #debug div
# $("#debug").append(str + "\n");
# };
#
# @example disable logging
# client.debug = function(str) {};
#
# @note the default can generate lot of log on the console. Set it to empty function to disable
#
# @param message [String]
debug: (message) ->
window?.console?.log message
# Utility method to get the current timestamp (Date.now is not defined in IE8)
#
# @private
now= ->
if Date.now then Date.now() else new Date().valueOf
# Base method to transmit any stomp frame
#
# @private
_transmit: (command, headers, body) ->
out = Frame.marshall(command, headers, body, @escapeHeaderValues)
@debug? ">>> " + out
# if necessary, split the *STOMP* frame to send it on many smaller
# *WebSocket* frames
while(true)
if out.length > @maxWebSocketFrameSize
@ws.send(out.substring(0, @maxWebSocketFrameSize))
out = out.substring(@maxWebSocketFrameSize)
@debug? "remaining = " + out.length
else
return @ws.send(out)
# Heart-beat negotiation
#
# @private
_setupHeartbeat: (headers) ->
return unless headers.version in [Stomp.VERSIONS.V1_1, Stomp.VERSIONS.V1_2]
# heart-beat header received from the server looks like:
#
# heart-beat: sx, sy
[serverOutgoing, serverIncoming] = (parseInt(v) for v in headers['heart-beat'].split(","))
unless @heartbeat.outgoing == 0 or serverIncoming == 0
ttl = Math.max(@heartbeat.outgoing, serverIncoming)
@debug? "send PING every #{ttl}ms"
# The `Stomp.setInterval` is a wrapper to handle regular callback
# that depends on the runtime environment (Web browser or node.js app)
@pinger = Stomp.setInterval ttl, =>
@ws.send Byte.LF
@debug? ">>> PING"
unless @heartbeat.incoming == 0 or serverOutgoing == 0
ttl = Math.max(@heartbeat.incoming, serverOutgoing)
@debug? "check PONG every #{ttl}ms"
@ponger = Stomp.setInterval ttl, =>
delta = now() - @serverActivity
# We wait twice the TTL to be flexible on window's setInterval calls
if delta > ttl * 2
@debug? "did not receive server activity for the last #{delta}ms"
@ws.close()
# parse the arguments number and type to find the headers, connectCallback and
# (eventually undefined) errorCallback
#
# @private
_parseConnect: (args...) ->
headers = {}
if args.length < 2
throw("Connect requires at least 2 arguments")
if args[1] instanceof Function
[headers, connectCallback, errorCallback, closeEventCallback] = args
else
switch args.length
when 6
[headers.login, headers.passcode, connectCallback, errorCallback, closeEventCallback, headers.host] = args
else
[headers.login, headers.passcode, connectCallback, errorCallback, closeEventCallback] = args
[headers, connectCallback, errorCallback, closeEventCallback]
# @see http://stomp.github.com/stomp-specification-1.2.html#CONNECT_or_STOMP_Frame CONNECT Frame
#
# The `connect` method accepts different number of arguments and types. See the Overloads list. Use the
# version with headers to pass your broker specific options.
#
# @overload connect(headers, connectCallback)
#
# @overload connect(headers, connectCallback, errorCallback)
#
# @overload connect(login, passcode, connectCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback, closeEventCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback, closeEventCallback, host)
#
# @param headers [Object]
# @option headers [String] login
# @option headers [String] passcode
# @option headers [String] host virtual host to connect to. STOMP 1.2 makes it mandatory, however the broker may not mandate it
# @param connectCallback [function(Frame)] Called upon a successful connect or reconnect
# @param errorCallback [function(any)] Optional, called upon an error. The passed paramer may be a {Frame} or a message
# @param closeEventCallback [function(CloseEvent)] Optional, called when the websocket is closed.
#
# @param login [String]
# @param passcode [String]
# @param host [String] Optional, virtual host to connect to. STOMP 1.2 makes it mandatory, however the broker may not mandate it
#
# @example
# client.connect('guest, 'guest', function(frame) {
# client.debug("connected to Stomp");
# client.subscribe(destination, function(message) {
# $("#messages").append("<p>" + message.body + "</p>\n");
# });
# });
#
# @note When auto reconnect is active, `connectCallback` and `errorCallback` will be called on each connect or error
connect: (args...) ->
@escapeHeaderValues = false
out = @_parseConnect(args...)
[@headers, @connectCallback, @errorCallback, @closeEventCallback] = out
# Indicate that this connection is active (it will keep trying to connect)
@_active = true
@_connect()
# Refactored to make it callable multiple times, useful for reconnecting
#
# @private
_connect: ->
headers = @headers
errorCallback = @errorCallback
closeEventCallback = @closeEventCallback
@debug? "Opening Web Socket..."
# Get the actual Websocket (or a similar object)
@ws= @ws_fn()
@ws.onmessage = (evt) =>
data = if typeof(ArrayBuffer) != 'undefined' and evt.data instanceof ArrayBuffer
# the data is stored inside an ArrayBuffer, we decode it to get the
# data as a String
arr = new Uint8Array(evt.data)
@debug? "--- got data length: #{arr.length}"
# Return a string formed by all the char codes stored in the Uint8array
(String.fromCharCode(c) for c in arr).join('')
else
# take the data directly from the WebSocket `data` field
evt.data
@serverActivity = now()
if data == Byte.LF # heartbeat
@debug? "<<< PONG"
return
@debug? "<<< #{data}"
# Handle STOMP frames received from the server
# The unmarshall function returns the frames parsed and any remaining
# data from partial frames.
unmarshalledData = Frame.unmarshall(@partialData + data, @escapeHeaderValues)
@partialData = unmarshalledData.partial
for frame in unmarshalledData.frames
switch frame.command
# [CONNECTED Frame](http://stomp.github.com/stomp-specification-1.2.html#CONNECTED_Frame)
when "CONNECTED"
@debug? "connected to server #{frame.headers.server}"
@connected = true
@version = frame.headers.version;
# STOMP version 1.2 needs header values to be escaped
if @version == Stomp.VERSIONS.V1_2
@escapeHeaderValues = true
# If a disconnect was requested while I was connecting, issue a disconnect
unless @_active
@disconnect()
return
@_setupHeartbeat(frame.headers)
@connectCallback? frame
# [MESSAGE Frame](http://stomp.github.com/stomp-specification-1.2.html#MESSAGE)
when "MESSAGE"
# the `onreceive` callback is registered when the client calls
# `subscribe()`.
# If there is registered subscription for the received message,
# we used the default `onreceive` method that the client can set.
# This is useful for subscriptions that are automatically created
# on the browser side (e.g. [RabbitMQ's temporary
# queues](http://www.rabbitmq.com/stomp.html)).
subscription = frame.headers.subscription
onreceive = @subscriptions[subscription] or @onreceive
if onreceive
client = this
if (@version == Stomp.VERSIONS.V1_2)
messageID = frame.headers["ack"]
else
messageID = frame.headers["message-id"]
# add `ack()` and `nack()` methods directly to the returned frame
# so that a simple call to `message.ack()` can acknowledge the message.
frame.ack = (headers = {}) =>
client .ack messageID , subscription, headers
frame.nack = (headers = {}) =>
client .nack messageID, subscription, headers
onreceive frame
else
@debug? "Unhandled received MESSAGE: #{frame}"
# [RECEIPT Frame](http://stomp.github.com/stomp-specification-1.2.html#RECEIPT)
#
# The client instance can set its `onreceipt` field to a function taking
# a frame argument that will be called when a receipt is received from
# the server:
#
# client.onreceipt = function(frame) {
# receiptID = frame.headers['receipt-id'];
# ...
# }
when "RECEIPT"
# if this is the receipt for a DISCONNECT, close the websocket
if (frame.headers["receipt-id"] == @closeReceipt)
# Discard the onclose callback to avoid calling the errorCallback when
# the client is properly disconnected.
@ws.onclose = null
@ws.close()
@_cleanUp()
@_disconnectCallback?()
else
@onreceipt?(frame)
# [ERROR Frame](http://stomp.github.com/stomp-specification-1.2.html#ERROR)
when "ERROR"
errorCallback?(frame)
else
@debug? "Unhandled frame: #{frame}"
@ws.onclose = (closeEvent) =>
msg = "Whoops! Lost connection to #{@ws.url}"
@debug?(msg)
closeEventCallback?(closeEvent)
@_cleanUp()
errorCallback?(msg)
@_schedule_reconnect()
@ws.onopen = =>
@debug?('Web Socket Opened...')
headers["accept-version"] = Stomp.VERSIONS.supportedVersions()
headers["heart-beat"] = [@heartbeat.outgoing, @heartbeat.incoming].join(',')
@_transmit "CONNECT", headers
#
# @private
_schedule_reconnect: ->
if @reconnect_delay > 0
@debug?("STOMP: scheduling reconnection in #{@reconnect_delay}ms")
# setTimeout is available in both Browser and Node.js environments
@_reconnector = setTimeout(=>
if @connected
@debug?('STOMP: already connected')
else
@debug?('STOMP: attempting to reconnect')
@_connect()
, @reconnect_delay)
# @see http://stomp.github.com/stomp-specification-1.2.html#DISCONNECT DISCONNECT Frame
#
# Disconnect from the STOMP broker. To ensure graceful shutdown it sends a DISCONNECT Frame
# and wait till the broker acknowledges.
#
# disconnectCallback will be called only if the broker was actually connected.
#
# @param disconnectCallback [function()]
# @param headers [Object] optional
disconnect: (disconnectCallback, headers={}) ->
@_disconnectCallback = disconnectCallback
# indicate that auto reconnect loop should terminate
@_active = false
if @connected
unless headers.receipt
headers.receipt = "close-" + @counter++
@closeReceipt = headers.receipt
try
@_transmit "DISCONNECT", headers
catch error
@debug?('Ignoring error during disconnect', error)
# Clean up client resources when it is disconnected or the server did not
# send heart beats in a timely fashion
#
# @private
_cleanUp: () ->
# Clear if a reconnection was scheduled
clearTimeout @_reconnector if @_reconnector
@connected = false
@subscriptions = {}
@partial = ''
Stomp.clearInterval @pinger if @pinger
Stomp.clearInterval @ponger if @ponger
# @see http://stomp.github.com/stomp-specification-1.2.html#SEND SEND Frame
#
# Send a message to a named destination. Refer to your STOMP broker documentation for types
# and naming of destinations. The headers will, typically, be available to the subscriber.
# However, there may be special purpose headers corresponding to your STOMP broker.
#
# @param destination [String] mandatory
# @param headers [Object] Optional
# @param body [String] Optional
#
# @example
# client.send("/queue/test", {priority: 9}, "Hello, STOMP");
#
# @example payload without headers
# # If you want to send a message with a body, you must also pass the headers argument.
# client.send("/queue/test", {}, "Hello, STOMP");
#
# @note Body must be String. You will need to covert the payload to string in case it is not string (e.g. JSON)
send: (destination, headers={}, body='') ->
headers.destination = destination
@_transmit "SEND", headers, body
# @see http://stomp.github.com/stomp-specification-1.2.html#SUBSCRIBE SUBSCRIBE Frame
#
# Subscribe to a STOMP Broker location. The return value is an Object with unsubscribe method.
#
# @example
# callback = function(message) {
# // called when the client receives a STOMP message from the server
# if (message.body) {
# alert("got message with body " + message.body)
# } else
# {
# alert("got empty message");
# }
# });
#
# var subscription = client.subscribe("/queue/test", callback);
#
# @example Explicit subscription id
# var mysubid = 'my-subscription-id-001';
# var subscription = client.subscribe(destination, callback, { id: mysubid });
#
# @param destination [String]
# @param callback [function(message)]
# @param headers [Object] optional
# @return [Object] this object has a method to `unsubscribe`
#
# @note The library will generate an unique ID if there is none provided in the headers. To use your own ID, pass it using the headers argument
subscribe: (destination, callback, headers={}) ->
# for convenience if the `id` header is not set, we create a new one for this client
# that will be returned to be able to unsubscribe this subscription
unless headers.id
headers.id = "sub-" + @counter++
headers.destination = destination
@subscriptions[headers.id] = callback
@_transmit "SUBSCRIBE", headers
client = this
return {
id: headers.id
unsubscribe: (hdrs) ->
client.unsubscribe headers.id, hdrs
}
# @see http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
#
# It is preferable to unsubscribe from a subscription by calling
# `unsubscribe()` directly on the object returned by `client.subscribe()`:
#
# @example
# var subscription = client.subscribe(destination, onmessage);
# ...
# subscription.unsubscribe();
#
# @param id [String]
# @param headers [Object] optional
unsubscribe: (id, headers={}) ->
delete @subscriptions[id]
headers.id = id
@_transmit "UNSUBSCRIBE", headers
# @see http://stomp.github.com/stomp-specification-1.2.html#BEGIN BEGIN Frame
#
# Start a transaction, the returned Object has methods - `commit` and `abort`
#
# @param transaction_id [String] optional
# @return [Object] member, `id` - transaction id, methods `commit` and `abort`
#
# @note If no transaction ID is passed, one will be created automatically
begin: (transaction_id) ->
txid = transaction_id || "tx-" + @counter++
@_transmit "BEGIN", {
transaction: txid
}
client = this
return {
id: txid
commit: ->
client.commit txid
abort: ->
client.abort txid
}
# @see http://stomp.github.com/stomp-specification-1.2.html#COMMIT COMMIT Frame
#
# Commit a transaction.
# It is preferable to commit a transaction by calling `commit()` directly on
# the object returned by `client.begin()`:
#
# @param transaction_id [String]
#
# @example
# var tx = client.begin(txid);
# ...
# tx.commit();
commit: (transaction_id) ->
@_transmit "COMMIT", {
transaction: transaction_id
}
# @see http://stomp.github.com/stomp-specification-1.2.html#ABORT ABORT Frame
#
# Abort a transaction.
# It is preferable to abort a transaction by calling `abort()` directly on
# the object returned by `client.begin()`:
#
# @param transaction_id [String]
#
# @example
# var tx = client.begin(txid);
# ...
# tx.abort();
abort: (transaction_id) ->
@_transmit "ABORT", {
transaction: transaction_id
}
# @see http://stomp.github.com/stomp-specification-1.2.html#ACK ACK Frame
#
# ACK a message. It is preferable to acknowledge a message by calling `ack()` directly
# on the message handled by a subscription callback:
#
# @example
# client.subscribe(destination,
# function(message) {
# // process the message
# // acknowledge it
# message.ack();
# },
# {'ack': 'client'}
# );
#
# @param messageID [String]
# @param subscription [String]
# @param headers [Object] optional
ack: (messageID, subscription, headers = {}) ->
if (@version == Stomp.VERSIONS.V1_2)
headers["id"] = messageID
else
headers["message-id"] = messageID
headers.subscription = subscription
@_transmit "ACK", headers
# @see http://stomp.github.com/stomp-specification-1.2.html#NACK NACK Frame
#
# NACK a message. It is preferable to nack a message by calling `nack()` directly on the
# message handled by a subscription callback:
#
# @example
# client.subscribe(destination,
# function(message) {
# // process the message
# // an error occurs, nack it
# message.nack();
# },
# {'ack': 'client'}
# );
#
# @param messageID [String]
# @param subscription [String]
# @param headers [Object] optional
nack: (messageID, subscription, headers = {}) ->
if (@version == Stomp.VERSIONS.V1_2)
headers["id"] = messageID
else
headers["message-id"] = messageID
headers.subscription = subscription
@_transmit "NACK", headers
# Stomp exposes methods to instantiate Client.
#
# @mixin
Stomp =
# @private
VERSIONS:
V1_0: '1.0'
V1_1: '1.1'
V1_2: '1.2'
# Versions of STOMP specifications supported
supportedVersions: ->
'1.2,1.1,1.0'
# This method creates a WebSocket client that is connected to
# the STOMP server located at the url.
#
# @example
# var url = "ws://localhost:61614/stomp";
# var client = Stomp.client(url);
#
# @param url [String]
client: (url, protocols = ['v10.stomp', 'v11.stomp', 'v12.stomp']) ->
# This is a hack to allow another implementation than the standard
# HTML5 WebSocket class.
#
# It is possible to use another class by calling
#
# Stomp.WebSocketClass = MozWebSocket
#
# *prior* to call `Stomp.client()`.
#
# This hack is deprecated and `Stomp.over()` method should be used
# instead.
# See remarks on the function Stomp.over
ws_fn= ->
klass = Stomp.WebSocketClass || WebSocket
new klass(url, protocols)
new Client ws_fn
# This method is an alternative to `Stomp.client()` to let the user
# specify the WebSocket to use (either a standard HTML5 WebSocket or
# a similar object).
#
# In order to support reconnection, the function Client._connect should be callable more than once. While reconnecting
# a new instance of underlying transport (TCP Socket, WebSocket or SockJS) will be needed. So, this function
# alternatively allows passing a function that should return a new instance of the underlying socket.
#
# @example
# var client = Stomp.over(function(){
# return new WebSocket('ws://localhost:15674/ws')
# });
#
# @param ws [WebSocket|function()] a WebSocket like Object or a function returning a WebObject or similar Object
#
# @note If you need auto reconnect feature you must pass a function that returns a WebSocket or similar Object
over: (ws) ->
ws_fn = if typeof(ws) == "function" then ws else -> ws
new Client ws_fn
# For testing purpose, expose the Frame class inside Stomp to be able to
# marshall/unmarshall frames
Frame: Frame
# Timer function
#
# @private
Stomp.setInterval= (interval, f) ->
setInterval f, interval
# @private
Stomp.clearInterval= (id) ->
clearInterval id
# # `Stomp` object exportation
# export as CommonJS module
if exports?
exports.Stomp = Stomp
# export in the Web Browser
if window?
window.Stomp = Stomp
# or in the current object (e.g. a WebWorker)
else if !exports
self.Stomp = Stomp
| 20958 |
# **STOMP Over Web Socket** is a JavaScript STOMP Client using
# [HTML5 Web Sockets API](http://www.w3.org/TR/websockets).
#
# * Copyright (C) 2010-2012 [<NAME>](http://jmesnil.net/)
# * Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
# * Copyright (C) 2017 [<NAME>](https://www.kreatio.com)
#
# This library supports:
#
# * [STOMP 1.0](http://stomp.github.com/stomp-specification-1.0.html)
# * [STOMP 1.1](http://stomp.github.com/stomp-specification-1.1.html)
# * [STOMP 1.2](http://stomp.github.com/stomp-specification-1.2.html)
#
# The library is accessed through the `Stomp` object that is set on the `window`
# when running in a Web browser.
###
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2010-2013 [<NAME>](http://jmesnil.net/)
Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
Copyright (C) 2017 [<NAME>](https://www.kreatio.com)
###
# @mixin
#
# @private
Byte =
# LINEFEED byte (octet 10)
LF: '\x0A'
# NULL byte (octet 0)
NULL: '\x00'
# @see http://stomp.github.com/stomp-specification-1.2.html#STOMP_Frames STOMP Frame
#
# Frame class represents a STOMP frame
#
class Frame
# Frame constructor. `command`, `headers` and `body` are available as properties.
#
# Many of the Client methods pass instance of received Frame to the callback.
#
# @param command [String]
# @param headers [Object]
# @param body [String]
# @param escapeHeaderValues [Boolean]
constructor: (@command, @headers={}, @body='', @escapeHeaderValues = false) ->
# Provides a textual representation of the frame
# suitable to be sent to the server
#
# @private
toString: ->
lines = [@command]
skipContentLength = if (@headers['content-length'] == false) then true else false
delete @headers['content-length'] if skipContentLength
for own name, value of @headers
if @escapeHeaderValues && @command != 'CONNECT' && @command != 'CONNECTED'
lines.push("#{name}:#{Frame.frEscape(value)}")
else
lines.push("#{name}:#{value}")
if @body && !skipContentLength
lines.push("content-length:#{Frame.sizeOfUTF8(@body)}")
lines.push(Byte.LF + @body)
return lines.join(Byte.LF)
# Compute the size of a UTF-8 string by counting its number of bytes
# (and not the number of characters composing the string)
#
# @private
@sizeOfUTF8: (s)->
if s
encodeURI(s).match(/%..|./g).length
else
0
# Unmarshall a single STOMP frame from a `data` string
#
# @private
unmarshallSingle= (data, escapeHeaderValues=false) ->
# search for 2 consecutives LF byte to split the command
# and headers from the body
divider = data.search(///#{Byte.LF}#{Byte.LF}///)
headerLines = data.substring(0, divider).split(Byte.LF)
command = headerLines.shift()
headers = {}
# utility function to trim any whitespace before and after a string
trim= (str) ->
str.replace(/^\s+|\s+$/g,'')
# Parse headers in reverse order so that for repeated headers, the 1st
# value is used
for line in headerLines.reverse()
idx = line.indexOf(':')
if escapeHeaderValues && command != 'CONNECT' && command != 'CONNECTED'
headers[trim(line.substring(0, idx))] = Frame.frUnEscape(trim(line.substring(idx + 1)))
else
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1))
# Parse body
# check for content-length or topping at the first NULL byte found.
body = ''
# skip the 2 LF bytes that divides the headers from the body
start = divider + 2
if headers['content-length']
len = parseInt headers['content-length']
body = ('' + data).substring(start, start + len)
else
chr = null
for i in [start...data.length]
chr = data.charAt(i)
break if chr is Byte.NULL
body += chr
return new Frame(command, headers, body, escapeHeaderValues)
# Split the data before unmarshalling every single STOMP frame.
# Web socket servers can send multiple frames in a single websocket message.
# If the message size exceeds the websocket message size, then a single
# frame can be fragmented across multiple messages.
#
# `datas` is a string.
#
# returns an *array* of Frame objects
#
# @private
@unmarshall: (datas, escapeHeaderValues=false) ->
# Ugly list comprehension to split and unmarshall *multiple STOMP frames*
# contained in a *single WebSocket frame*.
# The data is split when a NULL byte (followed by zero or many LF bytes) is
# found
frames = datas.split(///#{Byte.NULL}#{Byte.LF}*///)
r =
frames: []
partial: ''
r.frames = (unmarshallSingle(frame, escapeHeaderValues) for frame in frames[0..-2])
# If this contains a final full message or just a acknowledgement of a PING
# without any other content, process this frame, otherwise return the
# contents of the buffer to the caller.
last_frame = frames[-1..][0]
if last_frame is Byte.LF or (last_frame.search ///#{Byte.NULL}#{Byte.LF}*$///) isnt -1
r.frames.push(unmarshallSingle(last_frame, escapeHeaderValues))
else
r.partial = last_frame
return r
# Marshall a Stomp frame
#
# @private
@marshall: (command, headers, body, escapeHeaderValues) ->
frame = new Frame(command, headers, body, escapeHeaderValues)
return frame.toString() + Byte.NULL
# Escape header values
#
# @private
@frEscape: (str) ->
("" + str).replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/:/g, "\\c")
# Escape header values
#
# @private
@frUnEscape: (str) ->
("" + str).replace(/\\r/g, "\r").replace(/\\n/g, "\n").replace(/\\c/g, ":").replace(/\\\\/g, "\\")
# STOMP Client Class
#
# All STOMP protocol is exposed as methods of this class (`connect()`,
# `send()`, etc.)
class Client
# Please do not create instance of this class directly, use one of the methods {Stomp~client}, {Stomp~over}
# or {overTCP}
# in Stomp.
#
# @private
#
# @see Stomp
constructor: (ws_fn) ->
@ws_fn = ->
ws= ws_fn()
ws.binaryType = "arraybuffer"
ws
# @property reconnect_delay [Number] automatically reconnect with delay in milliseconds, set to 0 to disable
@reconnect_delay= 0
# used to index subscribers
@counter = 0
# @property [Boolean] current connection state
@connected = false
# @property [{outgoing: Number, incoming: Number}] outgoing and incoming
# heartbeat in milliseconds, set to 0 to disable
@heartbeat = {
# send heartbeat every 10s by default (value is in ms)
outgoing: 10000
# expect to receive server heartbeat at least every 10s by default
# (value in ms)
incoming: 10000
}
# maximum *WebSocket* frame size sent by the client. If the STOMP frame
# is bigger than this value, the STOMP frame will be sent using multiple
# WebSocket frames (default is 16KiB)
@maxWebSocketFrameSize = 16*1024
# subscription callbacks indexed by subscriber's ID
@subscriptions = {}
@partialData = ''
# By default, debug messages are logged in the window's console if it is defined.
# This method is called for every actual transmission of the STOMP frames over the
# WebSocket.
#
# It is possible to set a `debug(message)` method
# on a client instance to handle differently the debug messages:
#
# @example
# client.debug = function(str) {
# // append the debug log to a #debug div
# $("#debug").append(str + "\n");
# };
#
# @example disable logging
# client.debug = function(str) {};
#
# @note the default can generate lot of log on the console. Set it to empty function to disable
#
# @param message [String]
debug: (message) ->
window?.console?.log message
# Utility method to get the current timestamp (Date.now is not defined in IE8)
#
# @private
now= ->
if Date.now then Date.now() else new Date().valueOf
# Base method to transmit any stomp frame
#
# @private
_transmit: (command, headers, body) ->
out = Frame.marshall(command, headers, body, @escapeHeaderValues)
@debug? ">>> " + out
# if necessary, split the *STOMP* frame to send it on many smaller
# *WebSocket* frames
while(true)
if out.length > @maxWebSocketFrameSize
@ws.send(out.substring(0, @maxWebSocketFrameSize))
out = out.substring(@maxWebSocketFrameSize)
@debug? "remaining = " + out.length
else
return @ws.send(out)
# Heart-beat negotiation
#
# @private
_setupHeartbeat: (headers) ->
return unless headers.version in [Stomp.VERSIONS.V1_1, Stomp.VERSIONS.V1_2]
# heart-beat header received from the server looks like:
#
# heart-beat: sx, sy
[serverOutgoing, serverIncoming] = (parseInt(v) for v in headers['heart-beat'].split(","))
unless @heartbeat.outgoing == 0 or serverIncoming == 0
ttl = Math.max(@heartbeat.outgoing, serverIncoming)
@debug? "send PING every #{ttl}ms"
# The `Stomp.setInterval` is a wrapper to handle regular callback
# that depends on the runtime environment (Web browser or node.js app)
@pinger = Stomp.setInterval ttl, =>
@ws.send Byte.LF
@debug? ">>> PING"
unless @heartbeat.incoming == 0 or serverOutgoing == 0
ttl = Math.max(@heartbeat.incoming, serverOutgoing)
@debug? "check PONG every #{ttl}ms"
@ponger = Stomp.setInterval ttl, =>
delta = now() - @serverActivity
# We wait twice the TTL to be flexible on window's setInterval calls
if delta > ttl * 2
@debug? "did not receive server activity for the last #{delta}ms"
@ws.close()
# parse the arguments number and type to find the headers, connectCallback and
# (eventually undefined) errorCallback
#
# @private
_parseConnect: (args...) ->
headers = {}
if args.length < 2
throw("Connect requires at least 2 arguments")
if args[1] instanceof Function
[headers, connectCallback, errorCallback, closeEventCallback] = args
else
switch args.length
when 6
[headers.login, headers.passcode, connectCallback, errorCallback, closeEventCallback, headers.host] = args
else
[headers.login, headers.passcode, connectCallback, errorCallback, closeEventCallback] = args
[headers, connectCallback, errorCallback, closeEventCallback]
# @see http://stomp.github.com/stomp-specification-1.2.html#CONNECT_or_STOMP_Frame CONNECT Frame
#
# The `connect` method accepts different number of arguments and types. See the Overloads list. Use the
# version with headers to pass your broker specific options.
#
# @overload connect(headers, connectCallback)
#
# @overload connect(headers, connectCallback, errorCallback)
#
# @overload connect(login, passcode, connectCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback, closeEventCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback, closeEventCallback, host)
#
# @param headers [Object]
# @option headers [String] login
# @option headers [String] passcode
# @option headers [String] host virtual host to connect to. STOMP 1.2 makes it mandatory, however the broker may not mandate it
# @param connectCallback [function(Frame)] Called upon a successful connect or reconnect
# @param errorCallback [function(any)] Optional, called upon an error. The passed paramer may be a {Frame} or a message
# @param closeEventCallback [function(CloseEvent)] Optional, called when the websocket is closed.
#
# @param login [String]
# @param passcode [String]
# @param host [String] Optional, virtual host to connect to. STOMP 1.2 makes it mandatory, however the broker may not mandate it
#
# @example
# client.connect('guest, 'guest', function(frame) {
# client.debug("connected to Stomp");
# client.subscribe(destination, function(message) {
# $("#messages").append("<p>" + message.body + "</p>\n");
# });
# });
#
# @note When auto reconnect is active, `connectCallback` and `errorCallback` will be called on each connect or error
connect: (args...) ->
@escapeHeaderValues = false
out = @_parseConnect(args...)
[@headers, @connectCallback, @errorCallback, @closeEventCallback] = out
# Indicate that this connection is active (it will keep trying to connect)
@_active = true
@_connect()
# Refactored to make it callable multiple times, useful for reconnecting
#
# @private
_connect: ->
headers = @headers
errorCallback = @errorCallback
closeEventCallback = @closeEventCallback
@debug? "Opening Web Socket..."
# Get the actual Websocket (or a similar object)
@ws= @ws_fn()
@ws.onmessage = (evt) =>
data = if typeof(ArrayBuffer) != 'undefined' and evt.data instanceof ArrayBuffer
# the data is stored inside an ArrayBuffer, we decode it to get the
# data as a String
arr = new Uint8Array(evt.data)
@debug? "--- got data length: #{arr.length}"
# Return a string formed by all the char codes stored in the Uint8array
(String.fromCharCode(c) for c in arr).join('')
else
# take the data directly from the WebSocket `data` field
evt.data
@serverActivity = now()
if data == Byte.LF # heartbeat
@debug? "<<< PONG"
return
@debug? "<<< #{data}"
# Handle STOMP frames received from the server
# The unmarshall function returns the frames parsed and any remaining
# data from partial frames.
unmarshalledData = Frame.unmarshall(@partialData + data, @escapeHeaderValues)
@partialData = unmarshalledData.partial
for frame in unmarshalledData.frames
switch frame.command
# [CONNECTED Frame](http://stomp.github.com/stomp-specification-1.2.html#CONNECTED_Frame)
when "CONNECTED"
@debug? "connected to server #{frame.headers.server}"
@connected = true
@version = frame.headers.version;
# STOMP version 1.2 needs header values to be escaped
if @version == Stomp.VERSIONS.V1_2
@escapeHeaderValues = true
# If a disconnect was requested while I was connecting, issue a disconnect
unless @_active
@disconnect()
return
@_setupHeartbeat(frame.headers)
@connectCallback? frame
# [MESSAGE Frame](http://stomp.github.com/stomp-specification-1.2.html#MESSAGE)
when "MESSAGE"
# the `onreceive` callback is registered when the client calls
# `subscribe()`.
# If there is registered subscription for the received message,
# we used the default `onreceive` method that the client can set.
# This is useful for subscriptions that are automatically created
# on the browser side (e.g. [RabbitMQ's temporary
# queues](http://www.rabbitmq.com/stomp.html)).
subscription = frame.headers.subscription
onreceive = @subscriptions[subscription] or @onreceive
if onreceive
client = this
if (@version == Stomp.VERSIONS.V1_2)
messageID = frame.headers["ack"]
else
messageID = frame.headers["message-id"]
# add `ack()` and `nack()` methods directly to the returned frame
# so that a simple call to `message.ack()` can acknowledge the message.
frame.ack = (headers = {}) =>
client .ack messageID , subscription, headers
frame.nack = (headers = {}) =>
client .nack messageID, subscription, headers
onreceive frame
else
@debug? "Unhandled received MESSAGE: #{frame}"
# [RECEIPT Frame](http://stomp.github.com/stomp-specification-1.2.html#RECEIPT)
#
# The client instance can set its `onreceipt` field to a function taking
# a frame argument that will be called when a receipt is received from
# the server:
#
# client.onreceipt = function(frame) {
# receiptID = frame.headers['receipt-id'];
# ...
# }
when "RECEIPT"
# if this is the receipt for a DISCONNECT, close the websocket
if (frame.headers["receipt-id"] == @closeReceipt)
# Discard the onclose callback to avoid calling the errorCallback when
# the client is properly disconnected.
@ws.onclose = null
@ws.close()
@_cleanUp()
@_disconnectCallback?()
else
@onreceipt?(frame)
# [ERROR Frame](http://stomp.github.com/stomp-specification-1.2.html#ERROR)
when "ERROR"
errorCallback?(frame)
else
@debug? "Unhandled frame: #{frame}"
@ws.onclose = (closeEvent) =>
msg = "Whoops! Lost connection to #{@ws.url}"
@debug?(msg)
closeEventCallback?(closeEvent)
@_cleanUp()
errorCallback?(msg)
@_schedule_reconnect()
@ws.onopen = =>
@debug?('Web Socket Opened...')
headers["accept-version"] = Stomp.VERSIONS.supportedVersions()
headers["heart-beat"] = [@heartbeat.outgoing, @heartbeat.incoming].join(',')
@_transmit "CONNECT", headers
#
# @private
_schedule_reconnect: ->
if @reconnect_delay > 0
@debug?("STOMP: scheduling reconnection in #{@reconnect_delay}ms")
# setTimeout is available in both Browser and Node.js environments
@_reconnector = setTimeout(=>
if @connected
@debug?('STOMP: already connected')
else
@debug?('STOMP: attempting to reconnect')
@_connect()
, @reconnect_delay)
# @see http://stomp.github.com/stomp-specification-1.2.html#DISCONNECT DISCONNECT Frame
#
# Disconnect from the STOMP broker. To ensure graceful shutdown it sends a DISCONNECT Frame
# and wait till the broker acknowledges.
#
# disconnectCallback will be called only if the broker was actually connected.
#
# @param disconnectCallback [function()]
# @param headers [Object] optional
disconnect: (disconnectCallback, headers={}) ->
@_disconnectCallback = disconnectCallback
# indicate that auto reconnect loop should terminate
@_active = false
if @connected
unless headers.receipt
headers.receipt = "close-" + @counter++
@closeReceipt = headers.receipt
try
@_transmit "DISCONNECT", headers
catch error
@debug?('Ignoring error during disconnect', error)
# Clean up client resources when it is disconnected or the server did not
# send heart beats in a timely fashion
#
# @private
_cleanUp: () ->
# Clear if a reconnection was scheduled
clearTimeout @_reconnector if @_reconnector
@connected = false
@subscriptions = {}
@partial = ''
Stomp.clearInterval @pinger if @pinger
Stomp.clearInterval @ponger if @ponger
# @see http://stomp.github.com/stomp-specification-1.2.html#SEND SEND Frame
#
# Send a message to a named destination. Refer to your STOMP broker documentation for types
# and naming of destinations. The headers will, typically, be available to the subscriber.
# However, there may be special purpose headers corresponding to your STOMP broker.
#
# @param destination [String] mandatory
# @param headers [Object] Optional
# @param body [String] Optional
#
# @example
# client.send("/queue/test", {priority: 9}, "Hello, STOMP");
#
# @example payload without headers
# # If you want to send a message with a body, you must also pass the headers argument.
# client.send("/queue/test", {}, "Hello, STOMP");
#
# @note Body must be String. You will need to covert the payload to string in case it is not string (e.g. JSON)
send: (destination, headers={}, body='') ->
headers.destination = destination
@_transmit "SEND", headers, body
# @see http://stomp.github.com/stomp-specification-1.2.html#SUBSCRIBE SUBSCRIBE Frame
#
# Subscribe to a STOMP Broker location. The return value is an Object with unsubscribe method.
#
# @example
# callback = function(message) {
# // called when the client receives a STOMP message from the server
# if (message.body) {
# alert("got message with body " + message.body)
# } else
# {
# alert("got empty message");
# }
# });
#
# var subscription = client.subscribe("/queue/test", callback);
#
# @example Explicit subscription id
# var mysubid = 'my-subscription-id-001';
# var subscription = client.subscribe(destination, callback, { id: mysubid });
#
# @param destination [String]
# @param callback [function(message)]
# @param headers [Object] optional
# @return [Object] this object has a method to `unsubscribe`
#
# @note The library will generate an unique ID if there is none provided in the headers. To use your own ID, pass it using the headers argument
subscribe: (destination, callback, headers={}) ->
# for convenience if the `id` header is not set, we create a new one for this client
# that will be returned to be able to unsubscribe this subscription
unless headers.id
headers.id = "sub-" + @counter++
headers.destination = destination
@subscriptions[headers.id] = callback
@_transmit "SUBSCRIBE", headers
client = this
return {
id: headers.id
unsubscribe: (hdrs) ->
client.unsubscribe headers.id, hdrs
}
# @see http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
#
# It is preferable to unsubscribe from a subscription by calling
# `unsubscribe()` directly on the object returned by `client.subscribe()`:
#
# @example
# var subscription = client.subscribe(destination, onmessage);
# ...
# subscription.unsubscribe();
#
# @param id [String]
# @param headers [Object] optional
unsubscribe: (id, headers={}) ->
delete @subscriptions[id]
headers.id = id
@_transmit "UNSUBSCRIBE", headers
# @see http://stomp.github.com/stomp-specification-1.2.html#BEGIN BEGIN Frame
#
# Start a transaction, the returned Object has methods - `commit` and `abort`
#
# @param transaction_id [String] optional
# @return [Object] member, `id` - transaction id, methods `commit` and `abort`
#
# @note If no transaction ID is passed, one will be created automatically
begin: (transaction_id) ->
txid = transaction_id || "tx-" + @counter++
@_transmit "BEGIN", {
transaction: txid
}
client = this
return {
id: txid
commit: ->
client.commit txid
abort: ->
client.abort txid
}
# @see http://stomp.github.com/stomp-specification-1.2.html#COMMIT COMMIT Frame
#
# Commit a transaction.
# It is preferable to commit a transaction by calling `commit()` directly on
# the object returned by `client.begin()`:
#
# @param transaction_id [String]
#
# @example
# var tx = client.begin(txid);
# ...
# tx.commit();
commit: (transaction_id) ->
@_transmit "COMMIT", {
transaction: transaction_id
}
# @see http://stomp.github.com/stomp-specification-1.2.html#ABORT ABORT Frame
#
# Abort a transaction.
# It is preferable to abort a transaction by calling `abort()` directly on
# the object returned by `client.begin()`:
#
# @param transaction_id [String]
#
# @example
# var tx = client.begin(txid);
# ...
# tx.abort();
abort: (transaction_id) ->
@_transmit "ABORT", {
transaction: transaction_id
}
# @see http://stomp.github.com/stomp-specification-1.2.html#ACK ACK Frame
#
# ACK a message. It is preferable to acknowledge a message by calling `ack()` directly
# on the message handled by a subscription callback:
#
# @example
# client.subscribe(destination,
# function(message) {
# // process the message
# // acknowledge it
# message.ack();
# },
# {'ack': 'client'}
# );
#
# @param messageID [String]
# @param subscription [String]
# @param headers [Object] optional
ack: (messageID, subscription, headers = {}) ->
if (@version == Stomp.VERSIONS.V1_2)
headers["id"] = messageID
else
headers["message-id"] = messageID
headers.subscription = subscription
@_transmit "ACK", headers
# @see http://stomp.github.com/stomp-specification-1.2.html#NACK NACK Frame
#
# NACK a message. It is preferable to nack a message by calling `nack()` directly on the
# message handled by a subscription callback:
#
# @example
# client.subscribe(destination,
# function(message) {
# // process the message
# // an error occurs, nack it
# message.nack();
# },
# {'ack': 'client'}
# );
#
# @param messageID [String]
# @param subscription [String]
# @param headers [Object] optional
nack: (messageID, subscription, headers = {}) ->
if (@version == Stomp.VERSIONS.V1_2)
headers["id"] = messageID
else
headers["message-id"] = messageID
headers.subscription = subscription
@_transmit "NACK", headers
# Stomp exposes methods to instantiate Client.
#
# @mixin
Stomp =
# @private
VERSIONS:
V1_0: '1.0'
V1_1: '1.1'
V1_2: '1.2'
# Versions of STOMP specifications supported
supportedVersions: ->
'1.2,1.1,1.0'
# This method creates a WebSocket client that is connected to
# the STOMP server located at the url.
#
# @example
# var url = "ws://localhost:61614/stomp";
# var client = Stomp.client(url);
#
# @param url [String]
client: (url, protocols = ['v10.stomp', 'v11.stomp', 'v12.stomp']) ->
# This is a hack to allow another implementation than the standard
# HTML5 WebSocket class.
#
# It is possible to use another class by calling
#
# Stomp.WebSocketClass = MozWebSocket
#
# *prior* to call `Stomp.client()`.
#
# This hack is deprecated and `Stomp.over()` method should be used
# instead.
# See remarks on the function Stomp.over
ws_fn= ->
klass = Stomp.WebSocketClass || WebSocket
new klass(url, protocols)
new Client ws_fn
# This method is an alternative to `Stomp.client()` to let the user
# specify the WebSocket to use (either a standard HTML5 WebSocket or
# a similar object).
#
# In order to support reconnection, the function Client._connect should be callable more than once. While reconnecting
# a new instance of underlying transport (TCP Socket, WebSocket or SockJS) will be needed. So, this function
# alternatively allows passing a function that should return a new instance of the underlying socket.
#
# @example
# var client = Stomp.over(function(){
# return new WebSocket('ws://localhost:15674/ws')
# });
#
# @param ws [WebSocket|function()] a WebSocket like Object or a function returning a WebObject or similar Object
#
# @note If you need auto reconnect feature you must pass a function that returns a WebSocket or similar Object
over: (ws) ->
ws_fn = if typeof(ws) == "function" then ws else -> ws
new Client ws_fn
# For testing purpose, expose the Frame class inside Stomp to be able to
# marshall/unmarshall frames
Frame: Frame
# Timer function
#
# @private
Stomp.setInterval= (interval, f) ->
setInterval f, interval
# @private
Stomp.clearInterval= (id) ->
clearInterval id
# # `Stomp` object exportation
# export as CommonJS module
if exports?
exports.Stomp = Stomp
# export in the Web Browser
if window?
window.Stomp = Stomp
# or in the current object (e.g. a WebWorker)
else if !exports
self.Stomp = Stomp
| true |
# **STOMP Over Web Socket** is a JavaScript STOMP Client using
# [HTML5 Web Sockets API](http://www.w3.org/TR/websockets).
#
# * Copyright (C) 2010-2012 [PI:NAME:<NAME>END_PI](http://jmesnil.net/)
# * Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
# * Copyright (C) 2017 [PI:NAME:<NAME>END_PI](https://www.kreatio.com)
#
# This library supports:
#
# * [STOMP 1.0](http://stomp.github.com/stomp-specification-1.0.html)
# * [STOMP 1.1](http://stomp.github.com/stomp-specification-1.1.html)
# * [STOMP 1.2](http://stomp.github.com/stomp-specification-1.2.html)
#
# The library is accessed through the `Stomp` object that is set on the `window`
# when running in a Web browser.
###
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2010-2013 [PI:NAME:<NAME>END_PI](http://jmesnil.net/)
Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
Copyright (C) 2017 [PI:NAME:<NAME>END_PI](https://www.kreatio.com)
###
# @mixin
#
# @private
Byte =
# LINEFEED byte (octet 10)
LF: '\x0A'
# NULL byte (octet 0)
NULL: '\x00'
# @see http://stomp.github.com/stomp-specification-1.2.html#STOMP_Frames STOMP Frame
#
# Frame class represents a STOMP frame
#
class Frame
# Frame constructor. `command`, `headers` and `body` are available as properties.
#
# Many of the Client methods pass instance of received Frame to the callback.
#
# @param command [String]
# @param headers [Object]
# @param body [String]
# @param escapeHeaderValues [Boolean]
constructor: (@command, @headers={}, @body='', @escapeHeaderValues = false) ->
# Provides a textual representation of the frame
# suitable to be sent to the server
#
# @private
toString: ->
lines = [@command]
skipContentLength = if (@headers['content-length'] == false) then true else false
delete @headers['content-length'] if skipContentLength
for own name, value of @headers
if @escapeHeaderValues && @command != 'CONNECT' && @command != 'CONNECTED'
lines.push("#{name}:#{Frame.frEscape(value)}")
else
lines.push("#{name}:#{value}")
if @body && !skipContentLength
lines.push("content-length:#{Frame.sizeOfUTF8(@body)}")
lines.push(Byte.LF + @body)
return lines.join(Byte.LF)
# Compute the size of a UTF-8 string by counting its number of bytes
# (and not the number of characters composing the string)
#
# @private
@sizeOfUTF8: (s)->
if s
encodeURI(s).match(/%..|./g).length
else
0
# Unmarshall a single STOMP frame from a `data` string
#
# @private
unmarshallSingle= (data, escapeHeaderValues=false) ->
# search for 2 consecutives LF byte to split the command
# and headers from the body
divider = data.search(///#{Byte.LF}#{Byte.LF}///)
headerLines = data.substring(0, divider).split(Byte.LF)
command = headerLines.shift()
headers = {}
# utility function to trim any whitespace before and after a string
trim= (str) ->
str.replace(/^\s+|\s+$/g,'')
# Parse headers in reverse order so that for repeated headers, the 1st
# value is used
for line in headerLines.reverse()
idx = line.indexOf(':')
if escapeHeaderValues && command != 'CONNECT' && command != 'CONNECTED'
headers[trim(line.substring(0, idx))] = Frame.frUnEscape(trim(line.substring(idx + 1)))
else
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1))
# Parse body
# check for content-length or topping at the first NULL byte found.
body = ''
# skip the 2 LF bytes that divides the headers from the body
start = divider + 2
if headers['content-length']
len = parseInt headers['content-length']
body = ('' + data).substring(start, start + len)
else
chr = null
for i in [start...data.length]
chr = data.charAt(i)
break if chr is Byte.NULL
body += chr
return new Frame(command, headers, body, escapeHeaderValues)
# Split the data before unmarshalling every single STOMP frame.
# Web socket servers can send multiple frames in a single websocket message.
# If the message size exceeds the websocket message size, then a single
# frame can be fragmented across multiple messages.
#
# `datas` is a string.
#
# returns an *array* of Frame objects
#
# @private
@unmarshall: (datas, escapeHeaderValues=false) ->
# Ugly list comprehension to split and unmarshall *multiple STOMP frames*
# contained in a *single WebSocket frame*.
# The data is split when a NULL byte (followed by zero or many LF bytes) is
# found
frames = datas.split(///#{Byte.NULL}#{Byte.LF}*///)
r =
frames: []
partial: ''
r.frames = (unmarshallSingle(frame, escapeHeaderValues) for frame in frames[0..-2])
# If this contains a final full message or just a acknowledgement of a PING
# without any other content, process this frame, otherwise return the
# contents of the buffer to the caller.
last_frame = frames[-1..][0]
if last_frame is Byte.LF or (last_frame.search ///#{Byte.NULL}#{Byte.LF}*$///) isnt -1
r.frames.push(unmarshallSingle(last_frame, escapeHeaderValues))
else
r.partial = last_frame
return r
# Marshall a Stomp frame
#
# @private
@marshall: (command, headers, body, escapeHeaderValues) ->
frame = new Frame(command, headers, body, escapeHeaderValues)
return frame.toString() + Byte.NULL
# Escape header values
#
# @private
@frEscape: (str) ->
("" + str).replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/:/g, "\\c")
# Escape header values
#
# @private
@frUnEscape: (str) ->
("" + str).replace(/\\r/g, "\r").replace(/\\n/g, "\n").replace(/\\c/g, ":").replace(/\\\\/g, "\\")
# STOMP Client Class
#
# All STOMP protocol is exposed as methods of this class (`connect()`,
# `send()`, etc.)
class Client
# Please do not create instance of this class directly, use one of the methods {Stomp~client}, {Stomp~over}
# or {overTCP}
# in Stomp.
#
# @private
#
# @see Stomp
constructor: (ws_fn) ->
@ws_fn = ->
ws= ws_fn()
ws.binaryType = "arraybuffer"
ws
# @property reconnect_delay [Number] automatically reconnect with delay in milliseconds, set to 0 to disable
@reconnect_delay= 0
# used to index subscribers
@counter = 0
# @property [Boolean] current connection state
@connected = false
# @property [{outgoing: Number, incoming: Number}] outgoing and incoming
# heartbeat in milliseconds, set to 0 to disable
@heartbeat = {
# send heartbeat every 10s by default (value is in ms)
outgoing: 10000
# expect to receive server heartbeat at least every 10s by default
# (value in ms)
incoming: 10000
}
# maximum *WebSocket* frame size sent by the client. If the STOMP frame
# is bigger than this value, the STOMP frame will be sent using multiple
# WebSocket frames (default is 16KiB)
@maxWebSocketFrameSize = 16*1024
# subscription callbacks indexed by subscriber's ID
@subscriptions = {}
@partialData = ''
# By default, debug messages are logged in the window's console if it is defined.
# This method is called for every actual transmission of the STOMP frames over the
# WebSocket.
#
# It is possible to set a `debug(message)` method
# on a client instance to handle differently the debug messages:
#
# @example
# client.debug = function(str) {
# // append the debug log to a #debug div
# $("#debug").append(str + "\n");
# };
#
# @example disable logging
# client.debug = function(str) {};
#
# @note the default can generate lot of log on the console. Set it to empty function to disable
#
# @param message [String]
debug: (message) ->
window?.console?.log message
# Utility method to get the current timestamp (Date.now is not defined in IE8)
#
# @private
now= ->
if Date.now then Date.now() else new Date().valueOf
# Base method to transmit any stomp frame
#
# @private
_transmit: (command, headers, body) ->
out = Frame.marshall(command, headers, body, @escapeHeaderValues)
@debug? ">>> " + out
# if necessary, split the *STOMP* frame to send it on many smaller
# *WebSocket* frames
while(true)
if out.length > @maxWebSocketFrameSize
@ws.send(out.substring(0, @maxWebSocketFrameSize))
out = out.substring(@maxWebSocketFrameSize)
@debug? "remaining = " + out.length
else
return @ws.send(out)
# Heart-beat negotiation
#
# @private
_setupHeartbeat: (headers) ->
return unless headers.version in [Stomp.VERSIONS.V1_1, Stomp.VERSIONS.V1_2]
# heart-beat header received from the server looks like:
#
# heart-beat: sx, sy
[serverOutgoing, serverIncoming] = (parseInt(v) for v in headers['heart-beat'].split(","))
unless @heartbeat.outgoing == 0 or serverIncoming == 0
ttl = Math.max(@heartbeat.outgoing, serverIncoming)
@debug? "send PING every #{ttl}ms"
# The `Stomp.setInterval` is a wrapper to handle regular callback
# that depends on the runtime environment (Web browser or node.js app)
@pinger = Stomp.setInterval ttl, =>
@ws.send Byte.LF
@debug? ">>> PING"
unless @heartbeat.incoming == 0 or serverOutgoing == 0
ttl = Math.max(@heartbeat.incoming, serverOutgoing)
@debug? "check PONG every #{ttl}ms"
@ponger = Stomp.setInterval ttl, =>
delta = now() - @serverActivity
# We wait twice the TTL to be flexible on window's setInterval calls
if delta > ttl * 2
@debug? "did not receive server activity for the last #{delta}ms"
@ws.close()
# parse the arguments number and type to find the headers, connectCallback and
# (eventually undefined) errorCallback
#
# @private
_parseConnect: (args...) ->
headers = {}
if args.length < 2
throw("Connect requires at least 2 arguments")
if args[1] instanceof Function
[headers, connectCallback, errorCallback, closeEventCallback] = args
else
switch args.length
when 6
[headers.login, headers.passcode, connectCallback, errorCallback, closeEventCallback, headers.host] = args
else
[headers.login, headers.passcode, connectCallback, errorCallback, closeEventCallback] = args
[headers, connectCallback, errorCallback, closeEventCallback]
# @see http://stomp.github.com/stomp-specification-1.2.html#CONNECT_or_STOMP_Frame CONNECT Frame
#
# The `connect` method accepts different number of arguments and types. See the Overloads list. Use the
# version with headers to pass your broker specific options.
#
# @overload connect(headers, connectCallback)
#
# @overload connect(headers, connectCallback, errorCallback)
#
# @overload connect(login, passcode, connectCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback, closeEventCallback)
#
# @overload connect(login, passcode, connectCallback, errorCallback, closeEventCallback, host)
#
# @param headers [Object]
# @option headers [String] login
# @option headers [String] passcode
# @option headers [String] host virtual host to connect to. STOMP 1.2 makes it mandatory, however the broker may not mandate it
# @param connectCallback [function(Frame)] Called upon a successful connect or reconnect
# @param errorCallback [function(any)] Optional, called upon an error. The passed paramer may be a {Frame} or a message
# @param closeEventCallback [function(CloseEvent)] Optional, called when the websocket is closed.
#
# @param login [String]
# @param passcode [String]
# @param host [String] Optional, virtual host to connect to. STOMP 1.2 makes it mandatory, however the broker may not mandate it
#
# @example
# client.connect('guest, 'guest', function(frame) {
# client.debug("connected to Stomp");
# client.subscribe(destination, function(message) {
# $("#messages").append("<p>" + message.body + "</p>\n");
# });
# });
#
# @note When auto reconnect is active, `connectCallback` and `errorCallback` will be called on each connect or error
connect: (args...) ->
@escapeHeaderValues = false
out = @_parseConnect(args...)
[@headers, @connectCallback, @errorCallback, @closeEventCallback] = out
# Indicate that this connection is active (it will keep trying to connect)
@_active = true
@_connect()
# Refactored to make it callable multiple times, useful for reconnecting
#
# @private
_connect: ->
headers = @headers
errorCallback = @errorCallback
closeEventCallback = @closeEventCallback
@debug? "Opening Web Socket..."
# Get the actual Websocket (or a similar object)
@ws= @ws_fn()
@ws.onmessage = (evt) =>
data = if typeof(ArrayBuffer) != 'undefined' and evt.data instanceof ArrayBuffer
# the data is stored inside an ArrayBuffer, we decode it to get the
# data as a String
arr = new Uint8Array(evt.data)
@debug? "--- got data length: #{arr.length}"
# Return a string formed by all the char codes stored in the Uint8array
(String.fromCharCode(c) for c in arr).join('')
else
# take the data directly from the WebSocket `data` field
evt.data
@serverActivity = now()
if data == Byte.LF # heartbeat
@debug? "<<< PONG"
return
@debug? "<<< #{data}"
# Handle STOMP frames received from the server
# The unmarshall function returns the frames parsed and any remaining
# data from partial frames.
unmarshalledData = Frame.unmarshall(@partialData + data, @escapeHeaderValues)
@partialData = unmarshalledData.partial
for frame in unmarshalledData.frames
switch frame.command
# [CONNECTED Frame](http://stomp.github.com/stomp-specification-1.2.html#CONNECTED_Frame)
when "CONNECTED"
@debug? "connected to server #{frame.headers.server}"
@connected = true
@version = frame.headers.version;
# STOMP version 1.2 needs header values to be escaped
if @version == Stomp.VERSIONS.V1_2
@escapeHeaderValues = true
# If a disconnect was requested while I was connecting, issue a disconnect
unless @_active
@disconnect()
return
@_setupHeartbeat(frame.headers)
@connectCallback? frame
# [MESSAGE Frame](http://stomp.github.com/stomp-specification-1.2.html#MESSAGE)
when "MESSAGE"
# the `onreceive` callback is registered when the client calls
# `subscribe()`.
# If there is registered subscription for the received message,
# we used the default `onreceive` method that the client can set.
# This is useful for subscriptions that are automatically created
# on the browser side (e.g. [RabbitMQ's temporary
# queues](http://www.rabbitmq.com/stomp.html)).
subscription = frame.headers.subscription
onreceive = @subscriptions[subscription] or @onreceive
if onreceive
client = this
if (@version == Stomp.VERSIONS.V1_2)
messageID = frame.headers["ack"]
else
messageID = frame.headers["message-id"]
# add `ack()` and `nack()` methods directly to the returned frame
# so that a simple call to `message.ack()` can acknowledge the message.
frame.ack = (headers = {}) =>
client .ack messageID , subscription, headers
frame.nack = (headers = {}) =>
client .nack messageID, subscription, headers
onreceive frame
else
@debug? "Unhandled received MESSAGE: #{frame}"
# [RECEIPT Frame](http://stomp.github.com/stomp-specification-1.2.html#RECEIPT)
#
# The client instance can set its `onreceipt` field to a function taking
# a frame argument that will be called when a receipt is received from
# the server:
#
# client.onreceipt = function(frame) {
# receiptID = frame.headers['receipt-id'];
# ...
# }
when "RECEIPT"
# if this is the receipt for a DISCONNECT, close the websocket
if (frame.headers["receipt-id"] == @closeReceipt)
# Discard the onclose callback to avoid calling the errorCallback when
# the client is properly disconnected.
@ws.onclose = null
@ws.close()
@_cleanUp()
@_disconnectCallback?()
else
@onreceipt?(frame)
# [ERROR Frame](http://stomp.github.com/stomp-specification-1.2.html#ERROR)
when "ERROR"
errorCallback?(frame)
else
@debug? "Unhandled frame: #{frame}"
@ws.onclose = (closeEvent) =>
msg = "Whoops! Lost connection to #{@ws.url}"
@debug?(msg)
closeEventCallback?(closeEvent)
@_cleanUp()
errorCallback?(msg)
@_schedule_reconnect()
@ws.onopen = =>
@debug?('Web Socket Opened...')
headers["accept-version"] = Stomp.VERSIONS.supportedVersions()
headers["heart-beat"] = [@heartbeat.outgoing, @heartbeat.incoming].join(',')
@_transmit "CONNECT", headers
#
# @private
_schedule_reconnect: ->
if @reconnect_delay > 0
@debug?("STOMP: scheduling reconnection in #{@reconnect_delay}ms")
# setTimeout is available in both Browser and Node.js environments
@_reconnector = setTimeout(=>
if @connected
@debug?('STOMP: already connected')
else
@debug?('STOMP: attempting to reconnect')
@_connect()
, @reconnect_delay)
# @see http://stomp.github.com/stomp-specification-1.2.html#DISCONNECT DISCONNECT Frame
#
# Disconnect from the STOMP broker. To ensure graceful shutdown it sends a DISCONNECT Frame
# and wait till the broker acknowledges.
#
# disconnectCallback will be called only if the broker was actually connected.
#
# @param disconnectCallback [function()]
# @param headers [Object] optional
disconnect: (disconnectCallback, headers={}) ->
@_disconnectCallback = disconnectCallback
# indicate that auto reconnect loop should terminate
@_active = false
if @connected
unless headers.receipt
headers.receipt = "close-" + @counter++
@closeReceipt = headers.receipt
try
@_transmit "DISCONNECT", headers
catch error
@debug?('Ignoring error during disconnect', error)
# Clean up client resources when it is disconnected or the server did not
# send heart beats in a timely fashion
#
# @private
_cleanUp: () ->
# Clear if a reconnection was scheduled
clearTimeout @_reconnector if @_reconnector
@connected = false
@subscriptions = {}
@partial = ''
Stomp.clearInterval @pinger if @pinger
Stomp.clearInterval @ponger if @ponger
# @see http://stomp.github.com/stomp-specification-1.2.html#SEND SEND Frame
#
# Send a message to a named destination. Refer to your STOMP broker documentation for types
# and naming of destinations. The headers will, typically, be available to the subscriber.
# However, there may be special purpose headers corresponding to your STOMP broker.
#
# @param destination [String] mandatory
# @param headers [Object] Optional
# @param body [String] Optional
#
# @example
# client.send("/queue/test", {priority: 9}, "Hello, STOMP");
#
# @example payload without headers
# # If you want to send a message with a body, you must also pass the headers argument.
# client.send("/queue/test", {}, "Hello, STOMP");
#
# @note Body must be String. You will need to covert the payload to string in case it is not string (e.g. JSON)
send: (destination, headers={}, body='') ->
headers.destination = destination
@_transmit "SEND", headers, body
# @see http://stomp.github.com/stomp-specification-1.2.html#SUBSCRIBE SUBSCRIBE Frame
#
# Subscribe to a STOMP Broker location. The return value is an Object with unsubscribe method.
#
# @example
# callback = function(message) {
# // called when the client receives a STOMP message from the server
# if (message.body) {
# alert("got message with body " + message.body)
# } else
# {
# alert("got empty message");
# }
# });
#
# var subscription = client.subscribe("/queue/test", callback);
#
# @example Explicit subscription id
# var mysubid = 'my-subscription-id-001';
# var subscription = client.subscribe(destination, callback, { id: mysubid });
#
# @param destination [String]
# @param callback [function(message)]
# @param headers [Object] optional
# @return [Object] this object has a method to `unsubscribe`
#
# @note The library will generate an unique ID if there is none provided in the headers. To use your own ID, pass it using the headers argument
subscribe: (destination, callback, headers={}) ->
# for convenience if the `id` header is not set, we create a new one for this client
# that will be returned to be able to unsubscribe this subscription
unless headers.id
headers.id = "sub-" + @counter++
headers.destination = destination
@subscriptions[headers.id] = callback
@_transmit "SUBSCRIBE", headers
client = this
return {
id: headers.id
unsubscribe: (hdrs) ->
client.unsubscribe headers.id, hdrs
}
# @see http://stomp.github.com/stomp-specification-1.2.html#UNSUBSCRIBE UNSUBSCRIBE Frame
#
# It is preferable to unsubscribe from a subscription by calling
# `unsubscribe()` directly on the object returned by `client.subscribe()`:
#
# @example
# var subscription = client.subscribe(destination, onmessage);
# ...
# subscription.unsubscribe();
#
# @param id [String]
# @param headers [Object] optional
unsubscribe: (id, headers={}) ->
delete @subscriptions[id]
headers.id = id
@_transmit "UNSUBSCRIBE", headers
# @see http://stomp.github.com/stomp-specification-1.2.html#BEGIN BEGIN Frame
#
# Start a transaction, the returned Object has methods - `commit` and `abort`
#
# @param transaction_id [String] optional
# @return [Object] member, `id` - transaction id, methods `commit` and `abort`
#
# @note If no transaction ID is passed, one will be created automatically
begin: (transaction_id) ->
txid = transaction_id || "tx-" + @counter++
@_transmit "BEGIN", {
transaction: txid
}
client = this
return {
id: txid
commit: ->
client.commit txid
abort: ->
client.abort txid
}
# @see http://stomp.github.com/stomp-specification-1.2.html#COMMIT COMMIT Frame
#
# Commit a transaction.
# It is preferable to commit a transaction by calling `commit()` directly on
# the object returned by `client.begin()`:
#
# @param transaction_id [String]
#
# @example
# var tx = client.begin(txid);
# ...
# tx.commit();
commit: (transaction_id) ->
@_transmit "COMMIT", {
transaction: transaction_id
}
# @see http://stomp.github.com/stomp-specification-1.2.html#ABORT ABORT Frame
#
# Abort a transaction.
# It is preferable to abort a transaction by calling `abort()` directly on
# the object returned by `client.begin()`:
#
# @param transaction_id [String]
#
# @example
# var tx = client.begin(txid);
# ...
# tx.abort();
abort: (transaction_id) ->
@_transmit "ABORT", {
transaction: transaction_id
}
# @see http://stomp.github.com/stomp-specification-1.2.html#ACK ACK Frame
#
# ACK a message. It is preferable to acknowledge a message by calling `ack()` directly
# on the message handled by a subscription callback:
#
# @example
# client.subscribe(destination,
# function(message) {
# // process the message
# // acknowledge it
# message.ack();
# },
# {'ack': 'client'}
# );
#
# @param messageID [String]
# @param subscription [String]
# @param headers [Object] optional
ack: (messageID, subscription, headers = {}) ->
if (@version == Stomp.VERSIONS.V1_2)
headers["id"] = messageID
else
headers["message-id"] = messageID
headers.subscription = subscription
@_transmit "ACK", headers
# @see http://stomp.github.com/stomp-specification-1.2.html#NACK NACK Frame
#
# NACK a message. It is preferable to nack a message by calling `nack()` directly on the
# message handled by a subscription callback:
#
# @example
# client.subscribe(destination,
# function(message) {
# // process the message
# // an error occurs, nack it
# message.nack();
# },
# {'ack': 'client'}
# );
#
# @param messageID [String]
# @param subscription [String]
# @param headers [Object] optional
nack: (messageID, subscription, headers = {}) ->
if (@version == Stomp.VERSIONS.V1_2)
headers["id"] = messageID
else
headers["message-id"] = messageID
headers.subscription = subscription
@_transmit "NACK", headers
# Stomp exposes methods to instantiate Client.
#
# @mixin
Stomp =
# @private
VERSIONS:
V1_0: '1.0'
V1_1: '1.1'
V1_2: '1.2'
# Versions of STOMP specifications supported
supportedVersions: ->
'1.2,1.1,1.0'
# This method creates a WebSocket client that is connected to
# the STOMP server located at the url.
#
# @example
# var url = "ws://localhost:61614/stomp";
# var client = Stomp.client(url);
#
# @param url [String]
client: (url, protocols = ['v10.stomp', 'v11.stomp', 'v12.stomp']) ->
# This is a hack to allow another implementation than the standard
# HTML5 WebSocket class.
#
# It is possible to use another class by calling
#
# Stomp.WebSocketClass = MozWebSocket
#
# *prior* to call `Stomp.client()`.
#
# This hack is deprecated and `Stomp.over()` method should be used
# instead.
# See remarks on the function Stomp.over
ws_fn= ->
klass = Stomp.WebSocketClass || WebSocket
new klass(url, protocols)
new Client ws_fn
# This method is an alternative to `Stomp.client()` to let the user
# specify the WebSocket to use (either a standard HTML5 WebSocket or
# a similar object).
#
# In order to support reconnection, the function Client._connect should be callable more than once. While reconnecting
# a new instance of underlying transport (TCP Socket, WebSocket or SockJS) will be needed. So, this function
# alternatively allows passing a function that should return a new instance of the underlying socket.
#
# @example
# var client = Stomp.over(function(){
# return new WebSocket('ws://localhost:15674/ws')
# });
#
# @param ws [WebSocket|function()] a WebSocket like Object or a function returning a WebObject or similar Object
#
# @note If you need auto reconnect feature you must pass a function that returns a WebSocket or similar Object
over: (ws) ->
ws_fn = if typeof(ws) == "function" then ws else -> ws
new Client ws_fn
# For testing purpose, expose the Frame class inside Stomp to be able to
# marshall/unmarshall frames
Frame: Frame
# Timer function
#
# @private
Stomp.setInterval= (interval, f) ->
setInterval f, interval
# @private
Stomp.clearInterval= (id) ->
clearInterval id
# # `Stomp` object exportation
# export as CommonJS module
if exports?
exports.Stomp = Stomp
# export in the Web Browser
if window?
window.Stomp = Stomp
# or in the current object (e.g. a WebWorker)
else if !exports
self.Stomp = Stomp
|
[
{
"context": "esult = null\n\n model =\n name: Observable \"Foobert\"\n click: ->\n result = @name()\n\n bu",
"end": 203,
"score": 0.9998226165771484,
"start": 196,
"tag": "NAME",
"value": "Foobert"
},
{
"context": "null\n button.click()\n assert.equal re... | test/events.coffee | STRd6/jadelet | 18 | describe "Events", ->
it "should bind click to the object context", ->
template = makeTemplate """
button(click=@click)
"""
result = null
model =
name: Observable "Foobert"
click: ->
result = @name()
button = template(model)
assert.equal result, null
button.click()
assert.equal result, "Foobert"
it "should bind on- events the same way", ->
template = makeTemplate """
button(onclick=@click)
"""
result = null
model =
name: Observable "Foobert"
click: ->
result = @name()
button = template(model)
assert.equal result, null
button.click()
assert.equal result, "Foobert"
it "should skip non-functions when binding events", ->
template = makeTemplate """
button(@mouseenter @mouseleave)
"""
model =
mouseenter: "wut"
mouseleave: "lol"
button = template(model)
dispatchEvent button, "mouseenter"
dispatchEvent button, "mouseleave"
it "should bind mouseenter and mouseleave events", ->
template = makeTemplate """
button(@mouseenter @mouseleave)
"""
result = null
model =
mouseenter: ->
result = 1
mouseleave: ->
result = 2
button = template(model)
assert.equal result, null
dispatchEvent button, "mouseenter"
assert.equal result, 1
dispatchEvent button, "mouseleave"
assert.equal result, 2
it "shoud handle all touch events", ->
template = makeTemplate """
canvas(@touchstart @touchmove @touchend @touchcancel)
"""
called = 0
eventFn = ->
called += 1
model =
touchcancel: eventFn
touchstart: eventFn
touchmove: eventFn
touchend: eventFn
canvas = template(model)
assert.equal called, 0
dispatchEvent canvas, "touchstart"
assert.equal called, 1
dispatchEvent canvas, "touchmove"
assert.equal called, 2
dispatchEvent canvas, "touchend"
assert.equal called, 3
dispatchEvent canvas, "touchcancel"
assert.equal called, 4
it "shoud handle all animation events", ->
template = makeTemplate """
div(@animationstart @animationiteration @animationend @transitionend)
"""
called = 0
eventFn = ->
called += 1
model =
animationstart: eventFn
animationend: eventFn
animationiteration: eventFn
transitionend: eventFn
canvas = template(model)
assert.equal called, 0
dispatchEvent canvas, "animationstart"
assert.equal called, 1
dispatchEvent canvas, "animationiteration"
assert.equal called, 2
dispatchEvent canvas, "animationend"
assert.equal called, 3
dispatchEvent canvas, "transitionend"
assert.equal called, 4
| 39493 | describe "Events", ->
it "should bind click to the object context", ->
template = makeTemplate """
button(click=@click)
"""
result = null
model =
name: Observable "<NAME>"
click: ->
result = @name()
button = template(model)
assert.equal result, null
button.click()
assert.equal result, "<NAME>"
it "should bind on- events the same way", ->
template = makeTemplate """
button(onclick=@click)
"""
result = null
model =
name: Observable "<NAME>"
click: ->
result = @name()
button = template(model)
assert.equal result, null
button.click()
assert.equal result, "<NAME>"
it "should skip non-functions when binding events", ->
template = makeTemplate """
button(@mouseenter @mouseleave)
"""
model =
mouseenter: "wut"
mouseleave: "lol"
button = template(model)
dispatchEvent button, "mouseenter"
dispatchEvent button, "mouseleave"
it "should bind mouseenter and mouseleave events", ->
template = makeTemplate """
button(@mouseenter @mouseleave)
"""
result = null
model =
mouseenter: ->
result = 1
mouseleave: ->
result = 2
button = template(model)
assert.equal result, null
dispatchEvent button, "mouseenter"
assert.equal result, 1
dispatchEvent button, "mouseleave"
assert.equal result, 2
it "shoud handle all touch events", ->
template = makeTemplate """
canvas(@touchstart @touchmove @touchend @touchcancel)
"""
called = 0
eventFn = ->
called += 1
model =
touchcancel: eventFn
touchstart: eventFn
touchmove: eventFn
touchend: eventFn
canvas = template(model)
assert.equal called, 0
dispatchEvent canvas, "touchstart"
assert.equal called, 1
dispatchEvent canvas, "touchmove"
assert.equal called, 2
dispatchEvent canvas, "touchend"
assert.equal called, 3
dispatchEvent canvas, "touchcancel"
assert.equal called, 4
it "shoud handle all animation events", ->
template = makeTemplate """
div(@animationstart @animationiteration @animationend @transitionend)
"""
called = 0
eventFn = ->
called += 1
model =
animationstart: eventFn
animationend: eventFn
animationiteration: eventFn
transitionend: eventFn
canvas = template(model)
assert.equal called, 0
dispatchEvent canvas, "animationstart"
assert.equal called, 1
dispatchEvent canvas, "animationiteration"
assert.equal called, 2
dispatchEvent canvas, "animationend"
assert.equal called, 3
dispatchEvent canvas, "transitionend"
assert.equal called, 4
| true | describe "Events", ->
it "should bind click to the object context", ->
template = makeTemplate """
button(click=@click)
"""
result = null
model =
name: Observable "PI:NAME:<NAME>END_PI"
click: ->
result = @name()
button = template(model)
assert.equal result, null
button.click()
assert.equal result, "PI:NAME:<NAME>END_PI"
it "should bind on- events the same way", ->
template = makeTemplate """
button(onclick=@click)
"""
result = null
model =
name: Observable "PI:NAME:<NAME>END_PI"
click: ->
result = @name()
button = template(model)
assert.equal result, null
button.click()
assert.equal result, "PI:NAME:<NAME>END_PI"
it "should skip non-functions when binding events", ->
template = makeTemplate """
button(@mouseenter @mouseleave)
"""
model =
mouseenter: "wut"
mouseleave: "lol"
button = template(model)
dispatchEvent button, "mouseenter"
dispatchEvent button, "mouseleave"
it "should bind mouseenter and mouseleave events", ->
template = makeTemplate """
button(@mouseenter @mouseleave)
"""
result = null
model =
mouseenter: ->
result = 1
mouseleave: ->
result = 2
button = template(model)
assert.equal result, null
dispatchEvent button, "mouseenter"
assert.equal result, 1
dispatchEvent button, "mouseleave"
assert.equal result, 2
it "shoud handle all touch events", ->
template = makeTemplate """
canvas(@touchstart @touchmove @touchend @touchcancel)
"""
called = 0
eventFn = ->
called += 1
model =
touchcancel: eventFn
touchstart: eventFn
touchmove: eventFn
touchend: eventFn
canvas = template(model)
assert.equal called, 0
dispatchEvent canvas, "touchstart"
assert.equal called, 1
dispatchEvent canvas, "touchmove"
assert.equal called, 2
dispatchEvent canvas, "touchend"
assert.equal called, 3
dispatchEvent canvas, "touchcancel"
assert.equal called, 4
it "shoud handle all animation events", ->
template = makeTemplate """
div(@animationstart @animationiteration @animationend @transitionend)
"""
called = 0
eventFn = ->
called += 1
model =
animationstart: eventFn
animationend: eventFn
animationiteration: eventFn
transitionend: eventFn
canvas = template(model)
assert.equal called, 0
dispatchEvent canvas, "animationstart"
assert.equal called, 1
dispatchEvent canvas, "animationiteration"
assert.equal called, 2
dispatchEvent canvas, "animationend"
assert.equal called, 3
dispatchEvent canvas, "transitionend"
assert.equal called, 4
|
[
{
"context": "S: \"Tags\"\nPAGES: \"Pages\"\nPOSTS: \"Posts\"\nAUTHORS: \"Autoren\"\nSEARCH: \"Suche\"\nSOCIAL_NETWORKS: \"Soziale Netzwe",
"end": 401,
"score": 0.9968264698982239,
"start": 394,
"tag": "NAME",
"value": "Autoren"
},
{
"context": "}}\"\n\"sharing\":\n \"shared\": \"... | src/i18n/de.cson | Intraktio/hybrid | 2 | PULL_TO_REFRESH: "Ziehen zum Aktualisieren!"
RETRY: "Wiederholen"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Zurück"
ERROR: "Etwas ging schief. Bitte erneut versuchen."
ATTEMPT_TO_CONNECT: "Verbinden: Versuch(e) {{attempt}} von {{attemptMax}}."
OK: "Ok"
YES: "Ja"
NO: "Nein"
EMPTY_LIST: "Keine Inhalte bisher!"
MENU: "Menü"
HOME: "Startseite"
TAGS: "Tags"
PAGES: "Pages"
POSTS: "Posts"
AUTHORS: "Autoren"
SEARCH: "Suche"
SOCIAL_NETWORKS: "Soziale Netzwerke"
CATEGORIES: "Kategorien"
SETTINGS: "Einstellungen"
CUSTOM_POSTS: "Custom posts"
CUSTOM_TAXO: "Custom Taxonomy"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push notifications"
PUSH_NOTIF_TITLE: "Neue Inhalte!"
PUSH_NOTIF_TEXT: "Neu! Seite/Beitrag: '{{postTitle}}' wurde in {{appTitle}} veröffentlich, willst du es dir jetzt ansehen?"
BOOKMARKS: "Lesenzeichen"
BOOKMARKS_EMPTY: "Bisher noch nichts gespeichert!"
BOOKMARK_ADDED : "Lesezeichen gespeichert!"
BOOKMARK_REMOVED: "Lesezeichen gelöscht!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Tags"
"tag":
"title": "Tag: {{name}}"
"categories":
"title": "Kategorien"
"category":
"title": "Kategorie: {{name}}"
"home":
"title": "Startseite"
"search":
"inputPlaceholder": "Suche"
"title": "Suche"
"titleQuery": "Suche: {{query}}"
"sharing":
"shared": "Geteilt!"
AUTHORS: "Autoren"
AUTHOR: "Autor"
AUTHOR_TITLE: "Autor: {{name}}"
"pages":
"title": "Pages"
"posts":
"title": "Posts"
"featured": "Hervorgehoben"
"post":
"comments": "Kommentare"
"openInBrowser": "Im Browser öffnen"
"about":
"title": "Über"
"languages":
"de": "Deutsch"
"en": "English"
"fr": "Französisch"
"zh": "Chinesich"
"es": "Spanisch"
"pl": "Polnisch"
"pt": "Portugiesisch"
"it": "Italienisch"
"nl": "Holländisch"
"ru": "Russisch"
| 177370 | PULL_TO_REFRESH: "Ziehen zum Aktualisieren!"
RETRY: "Wiederholen"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Zurück"
ERROR: "Etwas ging schief. Bitte erneut versuchen."
ATTEMPT_TO_CONNECT: "Verbinden: Versuch(e) {{attempt}} von {{attemptMax}}."
OK: "Ok"
YES: "Ja"
NO: "Nein"
EMPTY_LIST: "Keine Inhalte bisher!"
MENU: "Menü"
HOME: "Startseite"
TAGS: "Tags"
PAGES: "Pages"
POSTS: "Posts"
AUTHORS: "<NAME>"
SEARCH: "Suche"
SOCIAL_NETWORKS: "Soziale Netzwerke"
CATEGORIES: "Kategorien"
SETTINGS: "Einstellungen"
CUSTOM_POSTS: "Custom posts"
CUSTOM_TAXO: "Custom Taxonomy"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push notifications"
PUSH_NOTIF_TITLE: "Neue Inhalte!"
PUSH_NOTIF_TEXT: "Neu! Seite/Beitrag: '{{postTitle}}' wurde in {{appTitle}} veröffentlich, willst du es dir jetzt ansehen?"
BOOKMARKS: "Lesenzeichen"
BOOKMARKS_EMPTY: "Bisher noch nichts gespeichert!"
BOOKMARK_ADDED : "Lesezeichen gespeichert!"
BOOKMARK_REMOVED: "Lesezeichen gelöscht!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Tags"
"tag":
"title": "Tag: {{name}}"
"categories":
"title": "Kategorien"
"category":
"title": "Kategorie: {{name}}"
"home":
"title": "Startseite"
"search":
"inputPlaceholder": "Suche"
"title": "Suche"
"titleQuery": "Suche: {{query}}"
"sharing":
"shared": "Geteilt!"
AUTHORS: "<NAME>"
AUTHOR: "Autor"
AUTHOR_TITLE: "Autor: {{name}}"
"pages":
"title": "Pages"
"posts":
"title": "Posts"
"featured": "Hervorgehoben"
"post":
"comments": "Kommentare"
"openInBrowser": "Im Browser öffnen"
"about":
"title": "Über"
"languages":
"de": "Deutsch"
"en": "English"
"fr": "Französisch"
"zh": "Chinesich"
"es": "Spanisch"
"pl": "Polnisch"
"pt": "Portugiesisch"
"it": "Italienisch"
"nl": "Holländisch"
"ru": "Russisch"
| true | PULL_TO_REFRESH: "Ziehen zum Aktualisieren!"
RETRY: "Wiederholen"
CANCEL: "Cancel"
SUBMIT: "Submit"
BACK: "Zurück"
ERROR: "Etwas ging schief. Bitte erneut versuchen."
ATTEMPT_TO_CONNECT: "Verbinden: Versuch(e) {{attempt}} von {{attemptMax}}."
OK: "Ok"
YES: "Ja"
NO: "Nein"
EMPTY_LIST: "Keine Inhalte bisher!"
MENU: "Menü"
HOME: "Startseite"
TAGS: "Tags"
PAGES: "Pages"
POSTS: "Posts"
AUTHORS: "PI:NAME:<NAME>END_PI"
SEARCH: "Suche"
SOCIAL_NETWORKS: "Soziale Netzwerke"
CATEGORIES: "Kategorien"
SETTINGS: "Einstellungen"
CUSTOM_POSTS: "Custom posts"
CUSTOM_TAXO: "Custom Taxonomy"
CUSTOM_TAXO_TITLE: "{{term}}: {{name}}"
PUSH_NOTIFS: "Push notifications"
PUSH_NOTIF_TITLE: "Neue Inhalte!"
PUSH_NOTIF_TEXT: "Neu! Seite/Beitrag: '{{postTitle}}' wurde in {{appTitle}} veröffentlich, willst du es dir jetzt ansehen?"
BOOKMARKS: "Lesenzeichen"
BOOKMARKS_EMPTY: "Bisher noch nichts gespeichert!"
BOOKMARK_ADDED : "Lesezeichen gespeichert!"
BOOKMARK_REMOVED: "Lesezeichen gelöscht!"
ZOOM: "Zoom"
CACHE_CLEAR: "Clear cache"
CACHE_CLEARED: "Cache cleared"
"tags":
"title": "Tags"
"tag":
"title": "Tag: {{name}}"
"categories":
"title": "Kategorien"
"category":
"title": "Kategorie: {{name}}"
"home":
"title": "Startseite"
"search":
"inputPlaceholder": "Suche"
"title": "Suche"
"titleQuery": "Suche: {{query}}"
"sharing":
"shared": "Geteilt!"
AUTHORS: "PI:NAME:<NAME>END_PI"
AUTHOR: "Autor"
AUTHOR_TITLE: "Autor: {{name}}"
"pages":
"title": "Pages"
"posts":
"title": "Posts"
"featured": "Hervorgehoben"
"post":
"comments": "Kommentare"
"openInBrowser": "Im Browser öffnen"
"about":
"title": "Über"
"languages":
"de": "Deutsch"
"en": "English"
"fr": "Französisch"
"zh": "Chinesich"
"es": "Spanisch"
"pl": "Polnisch"
"pt": "Portugiesisch"
"it": "Italienisch"
"nl": "Holländisch"
"ru": "Russisch"
|
[
{
"context": "# Brian Kintz\n# 23.12.2014\n\ncommand: \"osascript 'nowplaying.wid",
"end": 13,
"score": 0.9998639225959778,
"start": 2,
"tag": "NAME",
"value": "Brian Kintz"
}
] | nowplaying.widget/index.coffee | elmugrat/uebersicht_nowplaying | 3 | # Brian Kintz
# 23.12.2014
command: "osascript 'nowplaying.widget/track_info.scpt'"
refreshFrequency: 2000
style: """
bottom: 20px
left: 270px
width: 400px
font-family: "Helvetica Neue"
font-size: 9pt
.nowplaying
height: 50px
padding: 9px 10px 10px 10px
background: rgba(#000, 0.3)
border-radius: 10px
.artwork, .metadata
display: inline-block
.artwork
float: left
margin-right: 10px
.metadata
max-width: 325px
.title, .artist, .album
height: 16px
position: relative
top: -1px
overflow: hidden
white-space: nowrap
text-overflow: ellipsis
.title
color: #FFF
font-weight: 600
.artist
color: rgba(#FFF, 0.9)
.album
color: rgba(#FFF, 0.6)
.progress
height: 2px
margin-top: 3px
background: rgba(#FFF, 0.6)
.trackId
display: none
"""
render: (_) -> """
<div class="nowplaying">
<embed class="artwork" width="44px" height="44px" type="image/tiff" />
<div class="metadata">
<div class="title"></div>
<div class="artist"></div>
<div class="album"></div>
</div>
<div class="progress"></div>
<div class="trackId"></div>
</div>
"""
update: (output, domEl) ->
if output.trim() == "Not Playing"
$(domEl).fadeOut 500
$(domEl).data('playing', false)
else
$(domEl).fadeIn 500
if !$(domEl).data('playing')
artwork = $(domEl).find('.artwork')
artwork.attr('src', artwork.attr('src') + '?' + new Date().getTime())
$(domEl).data('playing', true)
# { title, artist, album, progress, trackId }
data = $.parseJSON(output)
if (data.progress >= 0 and data.progress <= 100)
# reset padding in case the last song's progress wasn't available (Spotify)
if (data.progress < 3)
$(domEl).find('.artwork, .metadata').css "padding-top": "0"
$(domEl).find('.progress').css width: "#{data.progress}%"
else
$(domEl).find('.artwork, .metadata').css "padding-top": "2px"
$(domEl).find('.progress').css width: "0%"
previousId = $(domEl).find('.trackId').text()
if previousId != data.trackId
$(domEl).find('.trackId').text(data.trackId)
$(domEl).find('.title').text(data.title)
$(domEl).find('.artist').text(data.artist)
$(domEl).find('.album').text(data.album)
if data.player == "itunes"
$(domEl).find('.artwork').show().attr('src', 'nowplaying.widget/artwork.tiff')
else if data.player == "spotify"
parts = data.trackId.split(":")
# try to get artwork from the Spotify web API
if (parts[1] == "track")
$.get("https://api.spotify.com/v1/tracks/#{parts[2]}", (data) ->
$(domEl).find('.artwork').show().attr('src', data.album.images[2].url)
).fail(() ->
$(domEl).find('.artwork').hide()
)
else
$(domEl).find('.artwork').hide()
else
$(domEl).find('.artwork').hide() | 175690 | # <NAME>
# 23.12.2014
command: "osascript 'nowplaying.widget/track_info.scpt'"
refreshFrequency: 2000
style: """
bottom: 20px
left: 270px
width: 400px
font-family: "Helvetica Neue"
font-size: 9pt
.nowplaying
height: 50px
padding: 9px 10px 10px 10px
background: rgba(#000, 0.3)
border-radius: 10px
.artwork, .metadata
display: inline-block
.artwork
float: left
margin-right: 10px
.metadata
max-width: 325px
.title, .artist, .album
height: 16px
position: relative
top: -1px
overflow: hidden
white-space: nowrap
text-overflow: ellipsis
.title
color: #FFF
font-weight: 600
.artist
color: rgba(#FFF, 0.9)
.album
color: rgba(#FFF, 0.6)
.progress
height: 2px
margin-top: 3px
background: rgba(#FFF, 0.6)
.trackId
display: none
"""
render: (_) -> """
<div class="nowplaying">
<embed class="artwork" width="44px" height="44px" type="image/tiff" />
<div class="metadata">
<div class="title"></div>
<div class="artist"></div>
<div class="album"></div>
</div>
<div class="progress"></div>
<div class="trackId"></div>
</div>
"""
update: (output, domEl) ->
if output.trim() == "Not Playing"
$(domEl).fadeOut 500
$(domEl).data('playing', false)
else
$(domEl).fadeIn 500
if !$(domEl).data('playing')
artwork = $(domEl).find('.artwork')
artwork.attr('src', artwork.attr('src') + '?' + new Date().getTime())
$(domEl).data('playing', true)
# { title, artist, album, progress, trackId }
data = $.parseJSON(output)
if (data.progress >= 0 and data.progress <= 100)
# reset padding in case the last song's progress wasn't available (Spotify)
if (data.progress < 3)
$(domEl).find('.artwork, .metadata').css "padding-top": "0"
$(domEl).find('.progress').css width: "#{data.progress}%"
else
$(domEl).find('.artwork, .metadata').css "padding-top": "2px"
$(domEl).find('.progress').css width: "0%"
previousId = $(domEl).find('.trackId').text()
if previousId != data.trackId
$(domEl).find('.trackId').text(data.trackId)
$(domEl).find('.title').text(data.title)
$(domEl).find('.artist').text(data.artist)
$(domEl).find('.album').text(data.album)
if data.player == "itunes"
$(domEl).find('.artwork').show().attr('src', 'nowplaying.widget/artwork.tiff')
else if data.player == "spotify"
parts = data.trackId.split(":")
# try to get artwork from the Spotify web API
if (parts[1] == "track")
$.get("https://api.spotify.com/v1/tracks/#{parts[2]}", (data) ->
$(domEl).find('.artwork').show().attr('src', data.album.images[2].url)
).fail(() ->
$(domEl).find('.artwork').hide()
)
else
$(domEl).find('.artwork').hide()
else
$(domEl).find('.artwork').hide() | true | # PI:NAME:<NAME>END_PI
# 23.12.2014
command: "osascript 'nowplaying.widget/track_info.scpt'"
refreshFrequency: 2000
style: """
bottom: 20px
left: 270px
width: 400px
font-family: "Helvetica Neue"
font-size: 9pt
.nowplaying
height: 50px
padding: 9px 10px 10px 10px
background: rgba(#000, 0.3)
border-radius: 10px
.artwork, .metadata
display: inline-block
.artwork
float: left
margin-right: 10px
.metadata
max-width: 325px
.title, .artist, .album
height: 16px
position: relative
top: -1px
overflow: hidden
white-space: nowrap
text-overflow: ellipsis
.title
color: #FFF
font-weight: 600
.artist
color: rgba(#FFF, 0.9)
.album
color: rgba(#FFF, 0.6)
.progress
height: 2px
margin-top: 3px
background: rgba(#FFF, 0.6)
.trackId
display: none
"""
render: (_) -> """
<div class="nowplaying">
<embed class="artwork" width="44px" height="44px" type="image/tiff" />
<div class="metadata">
<div class="title"></div>
<div class="artist"></div>
<div class="album"></div>
</div>
<div class="progress"></div>
<div class="trackId"></div>
</div>
"""
update: (output, domEl) ->
if output.trim() == "Not Playing"
$(domEl).fadeOut 500
$(domEl).data('playing', false)
else
$(domEl).fadeIn 500
if !$(domEl).data('playing')
artwork = $(domEl).find('.artwork')
artwork.attr('src', artwork.attr('src') + '?' + new Date().getTime())
$(domEl).data('playing', true)
# { title, artist, album, progress, trackId }
data = $.parseJSON(output)
if (data.progress >= 0 and data.progress <= 100)
# reset padding in case the last song's progress wasn't available (Spotify)
if (data.progress < 3)
$(domEl).find('.artwork, .metadata').css "padding-top": "0"
$(domEl).find('.progress').css width: "#{data.progress}%"
else
$(domEl).find('.artwork, .metadata').css "padding-top": "2px"
$(domEl).find('.progress').css width: "0%"
previousId = $(domEl).find('.trackId').text()
if previousId != data.trackId
$(domEl).find('.trackId').text(data.trackId)
$(domEl).find('.title').text(data.title)
$(domEl).find('.artist').text(data.artist)
$(domEl).find('.album').text(data.album)
if data.player == "itunes"
$(domEl).find('.artwork').show().attr('src', 'nowplaying.widget/artwork.tiff')
else if data.player == "spotify"
parts = data.trackId.split(":")
# try to get artwork from the Spotify web API
if (parts[1] == "track")
$.get("https://api.spotify.com/v1/tracks/#{parts[2]}", (data) ->
$(domEl).find('.artwork').show().attr('src', data.album.images[2].url)
).fail(() ->
$(domEl).find('.artwork').hide()
)
else
$(domEl).find('.artwork').hide()
else
$(domEl).find('.artwork').hide() |
[
{
"context": " {vs.map (version) =>\n key = Object.keys(version.changeset)[0]\n changes = 'from '",
"end": 4235,
"score": 0.6493327617645264,
"start": 4231,
"tag": "KEY",
"value": "keys"
},
{
"context": ") =>\n key = Object.keys(version.changeset)[0]\n... | app/pages/admin/project-status.cjsx | alexbfree/Panoptes-Front-End | 0 | React = require 'react'
PromiseRenderer = require '../../components/promise-renderer'
apiClient = require 'panoptes-client/lib/api-client'
SetToggle = require '../../lib/set-toggle'
moment = require 'moment'
ChangeListener = require '../../components/change-listener'
ProjectIcon = require '../../components/project-icon'
AutoSave = require '../../components/auto-save'
handleInputChange = require '../../lib/handle-input-change'
getWorkflowsInOrder = require '../../lib/get-workflows-in-order'
WorkflowToggle = require '../../components/workflow-toggle'
EXPERIMENTAL_FEATURES = [
'survey'
'crop'
'text'
'combo'
'dropdown'
'mini-course'
'hide classification summaries'
'pan and zoom'
'worldwide telescope'
'hide previous marks'
'column'
'grid'
'invert'
'workflow assignment'
'Gravity Spy Gold Standard'
'allow workflow query'
]
ProjectToggle = React.createClass
displayName: "ProjectToggle"
mixins: [SetToggle]
getDefaultProps: ->
project: null
field: null
trueLabel: "True"
falseLabel: "False"
getInitialState: ->
error: null
setting: {}
setterProperty: 'project'
render: ->
setting = @props.project[@props.field]
<span>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name={@props.field} value={true} data-json-value={true} checked={setting} disabled={@state.setting.private} onChange={@set.bind this, @props.field, true} />
{@props.trueLabel}
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name={@props.field} value={false} data-json-value={true} checked={not setting} disabled={@state.setting.private} onChange={@set.bind this, @props.field, false} />
{@props.falseLabel}
</label>
</span>
ProjectExperimentalFeatures = React.createClass
displayName: "ProjectExperimentalFeatures"
getDefaultProps: ->
project: null
setting: (task) ->
task in (@props.project?.experimental_tools or [])
updateTasks: (task) ->
tools = @props.project.experimental_tools or []
if task in tools
tools.splice(tools.indexOf(task), 1)
else
tools = tools.concat([task])
@props.project.update({experimental_tools: tools})
render: ->
<div className="project-status__section">
<h4>Experimental Features</h4>
<AutoSave resource={@props.project}>
<div className="project-status__section-table">
{EXPERIMENTAL_FEATURES.map (task) =>
<label key={task} className="project-status__section-table-row">
<input type="checkbox" name={task} checked={@setting(task)} onChange={@updateTasks.bind @, task} />
{task.charAt(0).toUpperCase() + task.slice(1)}
</label>}
</div>
</AutoSave>
</div>
ProjectRedirectToggle = React.createClass
displayName: "ProjectRedirectToggle"
mixins: [SetToggle]
getDefaultProps: ->
project: null
validUrlRegex: /https?:\/\/[\w-]+(\.[\w-]*)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/
invalidUrl: "invalidUrl"
getInitialState: ->
error: null
updateRedirect: (e) ->
_redirectUrl = this.refs.redirectUrl.value
if _redirectUrl?.match(@props.validUrlRegex) || _redirectUrl == ""
handleInputChange.call(@props.project, e)
else
@setState(error: @props.invalidUrl)
validUrlMessage: ->
if @state.error == @props.invalidUrl
"Invalid URL - must be in https?://format"
render: ->
<div className="project-status__section">
<h4>Project Redirect</h4>
<AutoSave resource={@props.project}>
<input type="text" name="redirect" ref="redirectUrl" value={@props.project.redirect} placeholder="External redirect" onBlur={@updateRedirect} onChange={handleInputChange.bind @props.project} />
<span>{ @validUrlMessage() }</span>
</AutoSave>
</div>
VersionList = React.createClass
displayName: "VersionList"
getDefaultProps: ->
project: null
render: ->
<PromiseRenderer promise={@props.project.get 'versions'}>{ (versions) =>
vs = versions.sort()
<h4>Recent Status Changes</h4>
<ul className="project-status__section-list">
{vs.map (version) =>
key = Object.keys(version.changeset)[0]
changes = 'from ' + version.changeset[key].join ' to '
m = moment(version.created_at)
<PromiseRenderer key={version.id} promise={apiClient.type('users').get(version.whodunnit)} >{ (user) =>
<li>{user.display_name} changed {key} {changes} {m.fromNow()}</li>
}</PromiseRenderer>}
</ul>
}</PromiseRenderer>
ProjectStatus = React.createClass
displayName: "ProjectStatus"
propTypes:
project: React.PropTypes.object.isRequired
getInitialState: ->
error: null
usedWorkflowLevels: []
workflows: []
getDefaultProps: ->
project: null
componentDidMount: ->
@getWorkflows()
onChangeWorkflowLevel: (workflow, event) ->
selected = event.target.value
workflowToUpdate = workflow
if @state.error
@setState error: null
# Saving explicitly to avoid potential race condition with projects with many workflows
if selected is 'none'
workflowToUpdate.update({ 'configuration.level': undefined })
else
workflowToUpdate.update({ 'configuration.level': selected })
workflowToUpdate.save()
.then =>
@getWorkflows()
.catch (error) =>
@setState error: error
getWorkflows: ->
getWorkflowsInOrder @props.project, fields: 'display_name,active,configuration'
.then (workflows) =>
usedWorkflowLevels = @getUsedWorkflowLevels(workflows)
@setState { usedWorkflowLevels, workflows }
getUsedWorkflowLevels: (workflows) ->
usedWorkflowLevels = []
for workflow in workflows
if workflow.configuration.level?
usedWorkflowLevels.push(workflow.configuration.level);
usedWorkflowLevels
render: ->
<ChangeListener target={@props.project}>{ =>
<div className="project-status">
<ProjectIcon project={@props.project} />
<div className="project-status__section">
<h4>Visibility Settings</h4>
<ul className="project-status__section-list">
<li>Private: <ProjectToggle project={@props.project} field="private" trueLabel="Private" falseLabel="Public" /></li>
<li>Live: <ProjectToggle project={@props.project} field="live" trueLabel="Live" falseLabel="Development" /></li>
<li>Beta Requested: <ProjectToggle project={@props.project} field="beta_requested" /></li>
<li>Beta Approved: <ProjectToggle project={@props.project} field="beta_approved" /></li>
<li>Launch Requested: <ProjectToggle project={@props.project} field="launch_requested" /></li>
<li>Launch Approved: <ProjectToggle project={@props.project} field="launch_approved" /></li>
</ul>
</div>
<ProjectRedirectToggle project={@props.project} />
<ProjectExperimentalFeatures project={@props.project} />
<div className="project-status__section">
<h4>Workflow Settings</h4>
<small>The workflow level dropdown is for the workflow assignment experimental feature.</small>
{if @state.error
<div>{@state.error}</div>}
{if @state.workflows.length is 0
<div>No workflows found</div>
else
<ul className="project-status__section-list">
{@state.workflows.map (workflow) =>
<li key={workflow.id} className="section-list__item">
<WorkflowToggle workflow={workflow} project={@props.project} field="active" />{' | '}
<label>
Level:{' '}
<select
onChange={@onChangeWorkflowLevel.bind(null, workflow)}
value={if workflow.configuration.level? then workflow.configuration.level}
>
<option value="none">none</option>
{@state.workflows.map (workflow, i) =>
value = i + 1
<option
key={i + Math.random()}
value={value}
disabled={@state.usedWorkflowLevels.indexOf(value) > -1}
>
{value}
</option>}
</select>
</label>
</li>}
</ul>}
</div>
<hr />
<div className="project-status__section">
<VersionList project={@props.project} />
</div>
</div>
}</ChangeListener>
module.exports = React.createClass
displayName: "ProjectStatusPage"
getProject: ->
{owner, name} = @props.params
slug = owner + "/" + name
apiClient.type('projects').get(slug: slug)
render: ->
<PromiseRenderer promise={@getProject()}>{ ([project]) =>
<ProjectStatus project={project} />
}</PromiseRenderer>
| 53885 | React = require 'react'
PromiseRenderer = require '../../components/promise-renderer'
apiClient = require 'panoptes-client/lib/api-client'
SetToggle = require '../../lib/set-toggle'
moment = require 'moment'
ChangeListener = require '../../components/change-listener'
ProjectIcon = require '../../components/project-icon'
AutoSave = require '../../components/auto-save'
handleInputChange = require '../../lib/handle-input-change'
getWorkflowsInOrder = require '../../lib/get-workflows-in-order'
WorkflowToggle = require '../../components/workflow-toggle'
EXPERIMENTAL_FEATURES = [
'survey'
'crop'
'text'
'combo'
'dropdown'
'mini-course'
'hide classification summaries'
'pan and zoom'
'worldwide telescope'
'hide previous marks'
'column'
'grid'
'invert'
'workflow assignment'
'Gravity Spy Gold Standard'
'allow workflow query'
]
ProjectToggle = React.createClass
displayName: "ProjectToggle"
mixins: [SetToggle]
getDefaultProps: ->
project: null
field: null
trueLabel: "True"
falseLabel: "False"
getInitialState: ->
error: null
setting: {}
setterProperty: 'project'
render: ->
setting = @props.project[@props.field]
<span>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name={@props.field} value={true} data-json-value={true} checked={setting} disabled={@state.setting.private} onChange={@set.bind this, @props.field, true} />
{@props.trueLabel}
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name={@props.field} value={false} data-json-value={true} checked={not setting} disabled={@state.setting.private} onChange={@set.bind this, @props.field, false} />
{@props.falseLabel}
</label>
</span>
ProjectExperimentalFeatures = React.createClass
displayName: "ProjectExperimentalFeatures"
getDefaultProps: ->
project: null
setting: (task) ->
task in (@props.project?.experimental_tools or [])
updateTasks: (task) ->
tools = @props.project.experimental_tools or []
if task in tools
tools.splice(tools.indexOf(task), 1)
else
tools = tools.concat([task])
@props.project.update({experimental_tools: tools})
render: ->
<div className="project-status__section">
<h4>Experimental Features</h4>
<AutoSave resource={@props.project}>
<div className="project-status__section-table">
{EXPERIMENTAL_FEATURES.map (task) =>
<label key={task} className="project-status__section-table-row">
<input type="checkbox" name={task} checked={@setting(task)} onChange={@updateTasks.bind @, task} />
{task.charAt(0).toUpperCase() + task.slice(1)}
</label>}
</div>
</AutoSave>
</div>
ProjectRedirectToggle = React.createClass
displayName: "ProjectRedirectToggle"
mixins: [SetToggle]
getDefaultProps: ->
project: null
validUrlRegex: /https?:\/\/[\w-]+(\.[\w-]*)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/
invalidUrl: "invalidUrl"
getInitialState: ->
error: null
updateRedirect: (e) ->
_redirectUrl = this.refs.redirectUrl.value
if _redirectUrl?.match(@props.validUrlRegex) || _redirectUrl == ""
handleInputChange.call(@props.project, e)
else
@setState(error: @props.invalidUrl)
validUrlMessage: ->
if @state.error == @props.invalidUrl
"Invalid URL - must be in https?://format"
render: ->
<div className="project-status__section">
<h4>Project Redirect</h4>
<AutoSave resource={@props.project}>
<input type="text" name="redirect" ref="redirectUrl" value={@props.project.redirect} placeholder="External redirect" onBlur={@updateRedirect} onChange={handleInputChange.bind @props.project} />
<span>{ @validUrlMessage() }</span>
</AutoSave>
</div>
VersionList = React.createClass
displayName: "VersionList"
getDefaultProps: ->
project: null
render: ->
<PromiseRenderer promise={@props.project.get 'versions'}>{ (versions) =>
vs = versions.sort()
<h4>Recent Status Changes</h4>
<ul className="project-status__section-list">
{vs.map (version) =>
key = Object.<KEY>(version.changeset)[<KEY>]
changes = 'from ' + version.changeset[key].join ' to '
m = moment(version.created_at)
<PromiseRenderer key={version.id} promise={apiClient.type('users').get(version.whodunnit)} >{ (user) =>
<li>{user.display_name} changed {key} {changes} {m.fromNow()}</li>
}</PromiseRenderer>}
</ul>
}</PromiseRenderer>
ProjectStatus = React.createClass
displayName: "ProjectStatus"
propTypes:
project: React.PropTypes.object.isRequired
getInitialState: ->
error: null
usedWorkflowLevels: []
workflows: []
getDefaultProps: ->
project: null
componentDidMount: ->
@getWorkflows()
onChangeWorkflowLevel: (workflow, event) ->
selected = event.target.value
workflowToUpdate = workflow
if @state.error
@setState error: null
# Saving explicitly to avoid potential race condition with projects with many workflows
if selected is 'none'
workflowToUpdate.update({ 'configuration.level': undefined })
else
workflowToUpdate.update({ 'configuration.level': selected })
workflowToUpdate.save()
.then =>
@getWorkflows()
.catch (error) =>
@setState error: error
getWorkflows: ->
getWorkflowsInOrder @props.project, fields: 'display_name,active,configuration'
.then (workflows) =>
usedWorkflowLevels = @getUsedWorkflowLevels(workflows)
@setState { usedWorkflowLevels, workflows }
getUsedWorkflowLevels: (workflows) ->
usedWorkflowLevels = []
for workflow in workflows
if workflow.configuration.level?
usedWorkflowLevels.push(workflow.configuration.level);
usedWorkflowLevels
render: ->
<ChangeListener target={@props.project}>{ =>
<div className="project-status">
<ProjectIcon project={@props.project} />
<div className="project-status__section">
<h4>Visibility Settings</h4>
<ul className="project-status__section-list">
<li>Private: <ProjectToggle project={@props.project} field="private" trueLabel="Private" falseLabel="Public" /></li>
<li>Live: <ProjectToggle project={@props.project} field="live" trueLabel="Live" falseLabel="Development" /></li>
<li>Beta Requested: <ProjectToggle project={@props.project} field="beta_requested" /></li>
<li>Beta Approved: <ProjectToggle project={@props.project} field="beta_approved" /></li>
<li>Launch Requested: <ProjectToggle project={@props.project} field="launch_requested" /></li>
<li>Launch Approved: <ProjectToggle project={@props.project} field="launch_approved" /></li>
</ul>
</div>
<ProjectRedirectToggle project={@props.project} />
<ProjectExperimentalFeatures project={@props.project} />
<div className="project-status__section">
<h4>Workflow Settings</h4>
<small>The workflow level dropdown is for the workflow assignment experimental feature.</small>
{if @state.error
<div>{@state.error}</div>}
{if @state.workflows.length is 0
<div>No workflows found</div>
else
<ul className="project-status__section-list">
{@state.workflows.map (workflow) =>
<li key={workflow.id} className="section-list__item">
<WorkflowToggle workflow={workflow} project={@props.project} field="active" />{' | '}
<label>
Level:{' '}
<select
onChange={@onChangeWorkflowLevel.bind(null, workflow)}
value={if workflow.configuration.level? then workflow.configuration.level}
>
<option value="none">none</option>
{@state.workflows.map (workflow, i) =>
value = i + 1
<option
key={i + Math.random()}
value={value}
disabled={@state.usedWorkflowLevels.indexOf(value) > -1}
>
{value}
</option>}
</select>
</label>
</li>}
</ul>}
</div>
<hr />
<div className="project-status__section">
<VersionList project={@props.project} />
</div>
</div>
}</ChangeListener>
module.exports = React.createClass
displayName: "ProjectStatusPage"
getProject: ->
{owner, name} = @props.params
slug = owner + "/" + name
apiClient.type('projects').get(slug: slug)
render: ->
<PromiseRenderer promise={@getProject()}>{ ([project]) =>
<ProjectStatus project={project} />
}</PromiseRenderer>
| true | React = require 'react'
PromiseRenderer = require '../../components/promise-renderer'
apiClient = require 'panoptes-client/lib/api-client'
SetToggle = require '../../lib/set-toggle'
moment = require 'moment'
ChangeListener = require '../../components/change-listener'
ProjectIcon = require '../../components/project-icon'
AutoSave = require '../../components/auto-save'
handleInputChange = require '../../lib/handle-input-change'
getWorkflowsInOrder = require '../../lib/get-workflows-in-order'
WorkflowToggle = require '../../components/workflow-toggle'
EXPERIMENTAL_FEATURES = [
'survey'
'crop'
'text'
'combo'
'dropdown'
'mini-course'
'hide classification summaries'
'pan and zoom'
'worldwide telescope'
'hide previous marks'
'column'
'grid'
'invert'
'workflow assignment'
'Gravity Spy Gold Standard'
'allow workflow query'
]
ProjectToggle = React.createClass
displayName: "ProjectToggle"
mixins: [SetToggle]
getDefaultProps: ->
project: null
field: null
trueLabel: "True"
falseLabel: "False"
getInitialState: ->
error: null
setting: {}
setterProperty: 'project'
render: ->
setting = @props.project[@props.field]
<span>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name={@props.field} value={true} data-json-value={true} checked={setting} disabled={@state.setting.private} onChange={@set.bind this, @props.field, true} />
{@props.trueLabel}
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name={@props.field} value={false} data-json-value={true} checked={not setting} disabled={@state.setting.private} onChange={@set.bind this, @props.field, false} />
{@props.falseLabel}
</label>
</span>
ProjectExperimentalFeatures = React.createClass
displayName: "ProjectExperimentalFeatures"
getDefaultProps: ->
project: null
setting: (task) ->
task in (@props.project?.experimental_tools or [])
updateTasks: (task) ->
tools = @props.project.experimental_tools or []
if task in tools
tools.splice(tools.indexOf(task), 1)
else
tools = tools.concat([task])
@props.project.update({experimental_tools: tools})
render: ->
<div className="project-status__section">
<h4>Experimental Features</h4>
<AutoSave resource={@props.project}>
<div className="project-status__section-table">
{EXPERIMENTAL_FEATURES.map (task) =>
<label key={task} className="project-status__section-table-row">
<input type="checkbox" name={task} checked={@setting(task)} onChange={@updateTasks.bind @, task} />
{task.charAt(0).toUpperCase() + task.slice(1)}
</label>}
</div>
</AutoSave>
</div>
ProjectRedirectToggle = React.createClass
displayName: "ProjectRedirectToggle"
mixins: [SetToggle]
getDefaultProps: ->
project: null
validUrlRegex: /https?:\/\/[\w-]+(\.[\w-]*)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/
invalidUrl: "invalidUrl"
getInitialState: ->
error: null
updateRedirect: (e) ->
_redirectUrl = this.refs.redirectUrl.value
if _redirectUrl?.match(@props.validUrlRegex) || _redirectUrl == ""
handleInputChange.call(@props.project, e)
else
@setState(error: @props.invalidUrl)
validUrlMessage: ->
if @state.error == @props.invalidUrl
"Invalid URL - must be in https?://format"
render: ->
<div className="project-status__section">
<h4>Project Redirect</h4>
<AutoSave resource={@props.project}>
<input type="text" name="redirect" ref="redirectUrl" value={@props.project.redirect} placeholder="External redirect" onBlur={@updateRedirect} onChange={handleInputChange.bind @props.project} />
<span>{ @validUrlMessage() }</span>
</AutoSave>
</div>
VersionList = React.createClass
displayName: "VersionList"
getDefaultProps: ->
project: null
render: ->
<PromiseRenderer promise={@props.project.get 'versions'}>{ (versions) =>
vs = versions.sort()
<h4>Recent Status Changes</h4>
<ul className="project-status__section-list">
{vs.map (version) =>
key = Object.PI:KEY:<KEY>END_PI(version.changeset)[PI:KEY:<KEY>END_PI]
changes = 'from ' + version.changeset[key].join ' to '
m = moment(version.created_at)
<PromiseRenderer key={version.id} promise={apiClient.type('users').get(version.whodunnit)} >{ (user) =>
<li>{user.display_name} changed {key} {changes} {m.fromNow()}</li>
}</PromiseRenderer>}
</ul>
}</PromiseRenderer>
ProjectStatus = React.createClass
displayName: "ProjectStatus"
propTypes:
project: React.PropTypes.object.isRequired
getInitialState: ->
error: null
usedWorkflowLevels: []
workflows: []
getDefaultProps: ->
project: null
componentDidMount: ->
@getWorkflows()
onChangeWorkflowLevel: (workflow, event) ->
selected = event.target.value
workflowToUpdate = workflow
if @state.error
@setState error: null
# Saving explicitly to avoid potential race condition with projects with many workflows
if selected is 'none'
workflowToUpdate.update({ 'configuration.level': undefined })
else
workflowToUpdate.update({ 'configuration.level': selected })
workflowToUpdate.save()
.then =>
@getWorkflows()
.catch (error) =>
@setState error: error
getWorkflows: ->
getWorkflowsInOrder @props.project, fields: 'display_name,active,configuration'
.then (workflows) =>
usedWorkflowLevels = @getUsedWorkflowLevels(workflows)
@setState { usedWorkflowLevels, workflows }
getUsedWorkflowLevels: (workflows) ->
usedWorkflowLevels = []
for workflow in workflows
if workflow.configuration.level?
usedWorkflowLevels.push(workflow.configuration.level);
usedWorkflowLevels
render: ->
<ChangeListener target={@props.project}>{ =>
<div className="project-status">
<ProjectIcon project={@props.project} />
<div className="project-status__section">
<h4>Visibility Settings</h4>
<ul className="project-status__section-list">
<li>Private: <ProjectToggle project={@props.project} field="private" trueLabel="Private" falseLabel="Public" /></li>
<li>Live: <ProjectToggle project={@props.project} field="live" trueLabel="Live" falseLabel="Development" /></li>
<li>Beta Requested: <ProjectToggle project={@props.project} field="beta_requested" /></li>
<li>Beta Approved: <ProjectToggle project={@props.project} field="beta_approved" /></li>
<li>Launch Requested: <ProjectToggle project={@props.project} field="launch_requested" /></li>
<li>Launch Approved: <ProjectToggle project={@props.project} field="launch_approved" /></li>
</ul>
</div>
<ProjectRedirectToggle project={@props.project} />
<ProjectExperimentalFeatures project={@props.project} />
<div className="project-status__section">
<h4>Workflow Settings</h4>
<small>The workflow level dropdown is for the workflow assignment experimental feature.</small>
{if @state.error
<div>{@state.error}</div>}
{if @state.workflows.length is 0
<div>No workflows found</div>
else
<ul className="project-status__section-list">
{@state.workflows.map (workflow) =>
<li key={workflow.id} className="section-list__item">
<WorkflowToggle workflow={workflow} project={@props.project} field="active" />{' | '}
<label>
Level:{' '}
<select
onChange={@onChangeWorkflowLevel.bind(null, workflow)}
value={if workflow.configuration.level? then workflow.configuration.level}
>
<option value="none">none</option>
{@state.workflows.map (workflow, i) =>
value = i + 1
<option
key={i + Math.random()}
value={value}
disabled={@state.usedWorkflowLevels.indexOf(value) > -1}
>
{value}
</option>}
</select>
</label>
</li>}
</ul>}
</div>
<hr />
<div className="project-status__section">
<VersionList project={@props.project} />
</div>
</div>
}</ChangeListener>
module.exports = React.createClass
displayName: "ProjectStatusPage"
getProject: ->
{owner, name} = @props.params
slug = owner + "/" + name
apiClient.type('projects').get(slug: slug)
render: ->
<PromiseRenderer promise={@getProject()}>{ ([project]) =>
<ProjectStatus project={project} />
}</PromiseRenderer>
|
[
{
"context": "###\n@author Nicholas Sardo <gcc.programmer@gmail.com>\n©2018\n###\n\nimport { Me",
"end": 26,
"score": 0.999890923500061,
"start": 12,
"tag": "NAME",
"value": "Nicholas Sardo"
},
{
"context": "###\n@author Nicholas Sardo <gcc.programmer@gmail.com>\n©2018\n###\n\nimport... | server/main.coffee | nsardo/meteor-1.8-coffeescript-example | 0 | ###
@author Nicholas Sardo <gcc.programmer@gmail.com>
©2018
###
import { Meteor } from 'meteor/meteor'
Meteor.startup ->
###
@Foo.insert
title: "momo"
designation: "mofo"
### | 222506 | ###
@author <NAME> <<EMAIL>>
©2018
###
import { Meteor } from 'meteor/meteor'
Meteor.startup ->
###
@Foo.insert
title: "momo"
designation: "mofo"
### | true | ###
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
©2018
###
import { Meteor } from 'meteor/meteor'
Meteor.startup ->
###
@Foo.insert
title: "momo"
designation: "mofo"
### |
[
{
"context": " 'participants': [\n {\n 'name': 'Ben Bitdiddle',\n 'email': 'ben.bitdiddle@gmail.com'\n ",
"end": 492,
"score": 0.9998672008514404,
"start": 479,
"tag": "NAME",
"value": "Ben Bitdiddle"
},
{
"context": " 'name': 'Ben Bitdiddle',\n ... | test/controller/thread-spec.coffee | PriviPK/privipk-webapp | 47 | define ['angular', 'angularMocks', 'baobab.controller.thread'], (angular) ->
describe 'ThreadCtrl', ->
$scope = null
$namespaces = null
controller = null
promises = null
msg = null
downloadPromise = null
mockThread1 =
'id': 'fake_thread_id1',
'object': 'thread',
'namespace_id': 'fake_namespace_id',
'subject': 'Mock Thread 1',
'last_message_timestamp': 1398229259,
'participants': [
{
'name': 'Ben Bitdiddle',
'email': 'ben.bitdiddle@gmail.com'
},
{
'name': 'Bill Rogers',
'email': 'wrogers@mit.edu'
}
],
'snippet': 'Test thread 1...',
'tags': [
{
'name': 'inbox',
'id': 'f0idlvozkrpj3ihxze7obpivh',
'object': 'tag'
},
{
'name': 'unread',
'id': '8keda28h8ijj2nogpj83yjep8',
'object': 'tag'
}
],
'message_ids': [
'251r594smznew6yhiocht2v29',
'7upzl8ss738iz8xf48lm84q3e',
'ah5wuphj3t83j260jqucm9a28'
],
'draft_ids': []
'messages': () ->
then: (callback) ->
callback([])
'hasTag': () -> false
'drafts': () ->
then: (callback) ->
callback([])
beforeEach ->
`Promise = mockPromises.getMockPromise(Promise);`
angular.mock.module 'baobab.controller.thread'
$namespaces =
current: ->
emailAddress: -> "ben@inboxapp.com"
$threads =
item: -> mockThread1
angular.mock.inject ($rootScope, $controller) ->
$scope = $rootScope.$new()
controller = $controller 'ThreadCtrl',
$scope: $scope
$namespaces: $namespaces,
$threads: $threads,
$contacts: null,
$modal: null,
$scrollState: null,
$routeParams: {'id': 'fake_thread_id1'}
afterEach ->
`Promise = mockPromises.getOriginalPromise();`
describe 'viewAttachment()', ->
beforeEach ->
blob = new Blob(['<b>123</b>'], {type : 'text/html'})
downloadPromise = Promise.resolve(blob)
msg = null
msg =
attachment: () -> msg
download: () -> downloadPromise
it 'should download the attachment blob', ->
spyOn(msg, 'download').andReturn(downloadPromise)
mockPromises.executeForPromise(downloadPromise)
controller.viewAttachment(msg, 'bs')
expect(msg.download).toHaveBeenCalled()
it 'should not immediately download attachments that are images', ->
blob = new Blob(['23232323'], {type : 'image/png'})
downloadPromise = Promise.resolve(blob)
spyOn(controller, 'downloadCurrentAttachment')
controller.viewAttachment(msg, 'bs')
mockPromises.executeForPromise(downloadPromise)
expect(controller.downloadCurrentAttachment).not.toHaveBeenCalled()
it 'should immediately save attachments that are not images', ->
spyOn(controller, 'downloadCurrentAttachment')
controller.viewAttachment(msg, 'bs')
mockPromises.executeForPromise(downloadPromise)
expect(controller.downloadCurrentAttachment).toHaveBeenCalled()
describe 'hideAttachment()', ->
it 'should reset the attachment state', ->
controller.currentAttachmentDataURL = 'bla'
controller.currentAttachment = 'bla'
controller.hideAttachment()
expect(controller.currentAttachmentDataURL).toBe(null);
expect(controller.currentAttachment).toBe(null);
| 140331 | define ['angular', 'angularMocks', 'baobab.controller.thread'], (angular) ->
describe 'ThreadCtrl', ->
$scope = null
$namespaces = null
controller = null
promises = null
msg = null
downloadPromise = null
mockThread1 =
'id': 'fake_thread_id1',
'object': 'thread',
'namespace_id': 'fake_namespace_id',
'subject': 'Mock Thread 1',
'last_message_timestamp': 1398229259,
'participants': [
{
'name': '<NAME>',
'email': '<EMAIL>'
},
{
'name': '<NAME>',
'email': '<EMAIL>'
}
],
'snippet': 'Test thread 1...',
'tags': [
{
'name': 'inbox',
'id': 'f0idlvozkrpj3ihxze7obpivh',
'object': 'tag'
},
{
'name': 'unread',
'id': '8keda28h8ijj2nogpj83yjep8',
'object': 'tag'
}
],
'message_ids': [
'251r594smznew6yhiocht2v29',
'7upzl8ss738iz8xf48lm84q3e',
'ah5wuphj3t83j260jqucm9a28'
],
'draft_ids': []
'messages': () ->
then: (callback) ->
callback([])
'hasTag': () -> false
'drafts': () ->
then: (callback) ->
callback([])
beforeEach ->
`Promise = mockPromises.getMockPromise(Promise);`
angular.mock.module 'baobab.controller.thread'
$namespaces =
current: ->
emailAddress: -> "<EMAIL>"
$threads =
item: -> mockThread1
angular.mock.inject ($rootScope, $controller) ->
$scope = $rootScope.$new()
controller = $controller 'ThreadCtrl',
$scope: $scope
$namespaces: $namespaces,
$threads: $threads,
$contacts: null,
$modal: null,
$scrollState: null,
$routeParams: {'id': 'fake_thread_id1'}
afterEach ->
`Promise = mockPromises.getOriginalPromise();`
describe 'viewAttachment()', ->
beforeEach ->
blob = new Blob(['<b>123</b>'], {type : 'text/html'})
downloadPromise = Promise.resolve(blob)
msg = null
msg =
attachment: () -> msg
download: () -> downloadPromise
it 'should download the attachment blob', ->
spyOn(msg, 'download').andReturn(downloadPromise)
mockPromises.executeForPromise(downloadPromise)
controller.viewAttachment(msg, 'bs')
expect(msg.download).toHaveBeenCalled()
it 'should not immediately download attachments that are images', ->
blob = new Blob(['23232323'], {type : 'image/png'})
downloadPromise = Promise.resolve(blob)
spyOn(controller, 'downloadCurrentAttachment')
controller.viewAttachment(msg, 'bs')
mockPromises.executeForPromise(downloadPromise)
expect(controller.downloadCurrentAttachment).not.toHaveBeenCalled()
it 'should immediately save attachments that are not images', ->
spyOn(controller, 'downloadCurrentAttachment')
controller.viewAttachment(msg, 'bs')
mockPromises.executeForPromise(downloadPromise)
expect(controller.downloadCurrentAttachment).toHaveBeenCalled()
describe 'hideAttachment()', ->
it 'should reset the attachment state', ->
controller.currentAttachmentDataURL = 'bla'
controller.currentAttachment = 'bla'
controller.hideAttachment()
expect(controller.currentAttachmentDataURL).toBe(null);
expect(controller.currentAttachment).toBe(null);
| true | define ['angular', 'angularMocks', 'baobab.controller.thread'], (angular) ->
describe 'ThreadCtrl', ->
$scope = null
$namespaces = null
controller = null
promises = null
msg = null
downloadPromise = null
mockThread1 =
'id': 'fake_thread_id1',
'object': 'thread',
'namespace_id': 'fake_namespace_id',
'subject': 'Mock Thread 1',
'last_message_timestamp': 1398229259,
'participants': [
{
'name': 'PI:NAME:<NAME>END_PI',
'email': 'PI:EMAIL:<EMAIL>END_PI'
},
{
'name': 'PI:NAME:<NAME>END_PI',
'email': 'PI:EMAIL:<EMAIL>END_PI'
}
],
'snippet': 'Test thread 1...',
'tags': [
{
'name': 'inbox',
'id': 'f0idlvozkrpj3ihxze7obpivh',
'object': 'tag'
},
{
'name': 'unread',
'id': '8keda28h8ijj2nogpj83yjep8',
'object': 'tag'
}
],
'message_ids': [
'251r594smznew6yhiocht2v29',
'7upzl8ss738iz8xf48lm84q3e',
'ah5wuphj3t83j260jqucm9a28'
],
'draft_ids': []
'messages': () ->
then: (callback) ->
callback([])
'hasTag': () -> false
'drafts': () ->
then: (callback) ->
callback([])
beforeEach ->
`Promise = mockPromises.getMockPromise(Promise);`
angular.mock.module 'baobab.controller.thread'
$namespaces =
current: ->
emailAddress: -> "PI:EMAIL:<EMAIL>END_PI"
$threads =
item: -> mockThread1
angular.mock.inject ($rootScope, $controller) ->
$scope = $rootScope.$new()
controller = $controller 'ThreadCtrl',
$scope: $scope
$namespaces: $namespaces,
$threads: $threads,
$contacts: null,
$modal: null,
$scrollState: null,
$routeParams: {'id': 'fake_thread_id1'}
afterEach ->
`Promise = mockPromises.getOriginalPromise();`
describe 'viewAttachment()', ->
beforeEach ->
blob = new Blob(['<b>123</b>'], {type : 'text/html'})
downloadPromise = Promise.resolve(blob)
msg = null
msg =
attachment: () -> msg
download: () -> downloadPromise
it 'should download the attachment blob', ->
spyOn(msg, 'download').andReturn(downloadPromise)
mockPromises.executeForPromise(downloadPromise)
controller.viewAttachment(msg, 'bs')
expect(msg.download).toHaveBeenCalled()
it 'should not immediately download attachments that are images', ->
blob = new Blob(['23232323'], {type : 'image/png'})
downloadPromise = Promise.resolve(blob)
spyOn(controller, 'downloadCurrentAttachment')
controller.viewAttachment(msg, 'bs')
mockPromises.executeForPromise(downloadPromise)
expect(controller.downloadCurrentAttachment).not.toHaveBeenCalled()
it 'should immediately save attachments that are not images', ->
spyOn(controller, 'downloadCurrentAttachment')
controller.viewAttachment(msg, 'bs')
mockPromises.executeForPromise(downloadPromise)
expect(controller.downloadCurrentAttachment).toHaveBeenCalled()
describe 'hideAttachment()', ->
it 'should reset the attachment state', ->
controller.currentAttachmentDataURL = 'bla'
controller.currentAttachment = 'bla'
controller.hideAttachment()
expect(controller.currentAttachmentDataURL).toBe(null);
expect(controller.currentAttachment).toBe(null);
|
[
{
"context": "r, see: SICP, 4.1\r\n#\r\n# Port to CoffeeScript\r\n# by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>\r\n# (C) MIT Style Lic",
"end": 89,
"score": 0.9998796582221985,
"start": 73,
"tag": "NAME",
"value": "Dmitry Soshnikov"
},
{
"context": "#\r\n# Port to CoffeeScript\r... | eval.coffee | DmitrySoshnikov/scheme-on-coffee | 7 | # Lisp/Scheme evaluator, see: SICP, 4.1
#
# Port to CoffeeScript
# by Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
# (C) MIT Style License
#
# Features:
# - just a toy and very inefficient; just the version 0.1 ;)
#
# Scheme metacircular evaluator authors: book SICP
# see http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html#%_sec_4.1
#
# All comments in code are *not* my comments. This is the
# text of the chapter 4.1 of the SICP book
#
@LispMachine =
## --------------------------
## Eval
## --------------------------
# Eval takes as arguments an expression (exp)
# and an environment (env). It classifies the expression
# and directs its evaluation. Eval is structured as a case
# analysis of the syntactic type of the expression to be
# evaluated. In order to keep the procedure general, we express
# the determination of the type of an expression abstractly, making
# no commitment to any particular representation for the various
# types of expressions. Each type of expression has a predicate that tests
# for it and an abstract means for selecting its parts. This *abstract syntax*
# makes it easy to see how we can change the syntax of the language by using
# the same evaluator, but with a different collection of syntax procedures.
eval: (exp, env) ->
## --------------------------
## Primitive expressions
## --------------------------
# For self-evaluating expressions, such as numbers, eval returns the
# expression itself.
# console.log "isSelfEvaluating #{exp}", isSelfEvaluating(exp), typeof exp
if isSelfEvaluating exp
return exp
# Eval must look up variables in the environment to find their values.
# console.log "isVariable #{exp}", isVariable exp
if isVariable exp
return lookupVariableValue exp, env
## --------------------------
## Special forms
## --------------------------
# For quoted expressions, eval returns the expression that was quoted.
# console.log "isQuoted #{exp}", isQuoted exp
if isQuoted exp
return textOfQuotation exp
# An assignment to (or a definition of) a variable must recursively
# call eval to compute the new value to be associated with the variable.
# The environment must be modified to change (or create) the binding
# of the variable.
# console.log "isAssignment #{exp}", isAssignment exp
if isAssignment exp
return evalAssignment exp, env
# console.log "isDefinition #{exp}", isDefinition exp
if isDefinition exp
return evalDefinition exp, env
# An if expression requires special processing of its parts, so as to evaluate
# the consequent if the predicate is true, and otherwise to evaluate the alternative.
# console.log "isIf #{exp}", isIf exp
if isIf exp
return evalIf exp, env
# A lambda expression must be transformed into an applicable procedure by packaging
# together the parameters and body specified by the lambda expression with the
# environment of the evaluation.
#console.log "isLambda #{exp}", isLambda exp
if isLambda exp
return makeProcedure(
lambdaParameters(exp),
lambdaBody(exp),
env
)
# A begin expression requires evaluating its sequence of expressions in the order
# in which they appear.
# console.log "isBegin #{exp}", isBegin exp
if isBegin exp
return evalSequence(
beginActions(exp),
env
)
# A case analysis (cond) is transformed into a nest of if expressions and then evaluated.
# console.log "isCond #{exp}", isCond exp
if isCond exp
return LispMachine.eval(
condToIf(exp),
env
)
# console.log "isLet #{exp}", isLet exp
if isLet exp
return LispMachine.apply(
LispMachine.eval(
letToLambda(exp),
env
),
letValues(exp, env)
)
## --------------------------
## Combinations
## --------------------------
# For a procedure application, eval must recursively evaluate the operator part and the
# operands of the combination. The resulting procedure and arguments are passed to apply,
# which handles the actual procedure application.
#console.log "isApplication #{exp}", isApplication exp
if isApplication exp
return LispMachine.apply(
LispMachine.eval(operator(exp), env),
listOfValues(operands(exp), env)
)
throw "Unknown expression type -- LispMachine.eval: #{exp}"
## --------------------------
## Apply
## --------------------------
# Apply takes two arguments, a procedure and a list of arguments to which the procedure
# should be applied. Apply classifies procedures into two kinds: It calls *applyPrimitiveProcedure*
# to apply primitives; it applies compound procedures by sequentially evaluating the expressions
# that make up the body of the procedure. The environment for the evaluation of the body of a compound
# procedure is constructed by extending the base environment carried by the procedure to include a frame
# that binds the parameters of the procedure to the arguments to which the procedure is to be applied.
apply: (procedure, arguments) ->
#console.log "isPrimitiveProcedure", isPrimitiveProcedure procedure
if isPrimitiveProcedure procedure
return applyPrimitiveProcedure procedure, arguments
#console.log "isCompoundProcedure", isCompoundProcedure procedure
if isCompoundProcedure procedure
return evalSequence(
procedureBody(procedure),
extendEnvironment(
procedureParameters(procedure),
arguments,
procedureEnvironment(procedure)
)
)
throw "Unknown procedure type -- apply: #{procedure}"
##
## Helpers (global functions)
##
extend = (object, module) ->
for own k of module
object[k] = module[k]
object
extend @,
## --------------------------
## Procedure arguments
## --------------------------
# When eval processes a procedure application, it uses *listOfValues* to produce the list of arguments
# to which the procedure is to be applied. ListOfValues takes as an argument the operands of the combination.
# It evaluates each operand and returns a list of the corresponding values
listOfValues: (exps, env) ->
return null if noOperands exps
return cons(
LispMachine.eval(firstOperand(exps), env),
listOfValues(restOperands(exps), env)
)
## --------------------------
## Conditionals
## --------------------------
# EvalIf evaluates the predicate part of an if expression in the given environment. If the result is true, evalIf
# evaluates the consequent, otherwise it evaluates the alternative:
evalIf: (exp, env) ->
if LispMachine.eval(ifPredicate(exp), env)
return LispMachine.eval(ifConsequent(exp), env)
return LispMachine.eval(ifAlternative(exp), env)
## --------------------------
## Sequences
## --------------------------
# EvalSequence is used by apply to evaluate the sequence of expressions in a procedure body and by eval to evaluate
# the sequence of expressions in a begin expression. It takes as arguments a sequence of expressions and an environment,
# and evaluates the expressions in the order in which they occur. The value returned is the value of the final expression.
evalSequence: (exps, env) ->
if isLastExp exps
return LispMachine.eval(firstExp(exps), env)
LispMachine.eval(firstExp(exps), env)
evalSequence(restExps(exps), env)
## --------------------------
## Assignments and definitions
## --------------------------
# The following procedure handles assignments to variables. It calls eval to find the value to be assigned and transmits the
# variable and the resulting value to setVariableValue to be installed in the designated environment.
evalAssignment: (exp, env) ->
setVariableValue(
assignmentVariable(exp),
LispMachine.eval(assignmentValue(exp), env),
env
)
# Definitions of variables are handled in a similar manner.
evalDefinition: (exp, env) ->
defineVariable(
definitionVariable(exp),
LispMachine.eval(definitionValue(exp), env),
env
)
## ---------------------------------
## 4.1.2 Representing Expressions
## ---------------------------------
extend @,
# The only self-evaluating items are numbers and strings:
isSelfEvaluating: (exp) ->
return true if isNumber(exp) # or isString(exp)
false
# ad-hoc
isNumber: (exp) ->
not isNaN(Number(exp))
# ad-hoc
isString: (exp) ->
typeof exp is "string"
# Variables are represented by symbols:
isVariable: (exp) ->
isSymbol exp
# ad-hoc
isSymbol: (exp) ->
/^([a-z-A-Z0-9_$?!+*/=><\-]|>=|<=)+$/.test exp
# Quotations have the form (quote <text-of-quotation>)
isQuoted: (exp) ->
isTaggedList exp, 'quote'
textOfQuotation: (exp) ->
cadr exp
# `Quoted` is defined in terms of the procedure `isTaggedList`, which
# identifies lists beginning with a designated symbol:
isTaggedList: (exp, tag) ->
return false if not isPair exp
testTypeTag = (x) ->
eq car(exp), x
return tag.some testTypeTag if tag instanceof Array
testTypeTag tag
# ad-hoc
isPair: (o) ->
o instanceof Array and o.length is 2
cons: (x, y) ->
[x, y]
# ad-hoc
car: (p) ->
p[0] # (car '(1 2 3 4)) is 1
# ad-hoc
cdr: (p) ->
p[1] # (cdr '(1 2 3 4)) is '(2 3 4)
# ad-hoc
cadr: (o) ->
car(cdr(o)) # (cadr '(1 2 3 4)) is 2
caadr: (o) ->
car(car(cdr(o))) # (caadr '(1 (2 5) 3 4)) is 2
# ad-hoc
caddr: (o) ->
car(cdr(cdr(o))) # (caddr '(1 2 3 4)) is 3
# ad-hoc
cdadr: (o) ->
cdr(car(cdr(o))) # (cdadr '(1 (2 5) 3 4)) is (5)
# ad-hoc
cddr: (o) ->
cdr(cdr(o)) # (cddr '(1 2 3 4)) is (3 4)
# ad-hoc
cdddr: (o) ->
cdr(cdr(cdr(o))) # (cdddr '(1 2 3 4 5)) is (4 5)
# ad-hoc
cadddr: (o) ->
car(cdr(cdr(cdr(o)))) # (cdddr '(1 2 3 4 5)) is 4
# ad-hoc
eq: (x, y) ->
x == y
# ad-hoc
list: (items...) ->
items.reduceRight(
(y, x) -> [x, y],
null
)
# ad-hoc
# converts JS's array into Lisp's list
# Example: [1, 2, 3, 4] => [1, [2, [3, [4, null]]]]
# Rationale: to make cdr mutable
JSArray2LispList: (array) ->
array.reduceRight(
((y, x) ->
if x instanceof Array then cons(JSArray2LispList(x), y) else cons(x, y)),
null
)
# ad-hoc
# convers Lisp's list into JS's array
# Example: [1, [2, [3, [4, null]]]] => [1, 2, 3, 4]
# Rationale: use apply of JS functions
LispList2JSArray: (list) ->
retVal = []
while list
currentCar = car list
retVal.push(if isPair(currentCar) then LispList2JSArray(currentCar) else currentCar)
list = cdr list
retVal
# Assignments have the form (set! <variable> <value>)
isAssignment: (exp) ->
isTaggedList exp, 'set!'
assignmentVariable: (exp) ->
cadr exp
assignmentValue: (exp) ->
caddr exp
# Definitions have the form
#
# (define <variable> <value>)
#
# or the form
#
# (define (<variable> <parameter1> ... <parametern>)
# <body>)
#
# The latter form (standard procedure definition) is syntactic sugar for
#
# (define <variable>
# (lambda (<parameter1> ... <parametern>)
# <body>))
#
# The corresponding syntax procedures are the following:
isDefinition: (exp) ->
isTaggedList exp, ['define', 'setf']
definitionVariable: (exp) ->
return cadr exp if isSymbol cadr exp
caadr exp
definitionValue: (exp) ->
return caddr exp if isSymbol cadr exp
makeLambda(
cdadr(exp), # formal parameters
cddr(exp) # body
)
# Lambda expressions are lists that begin with the symbol lambda:
isLambda: (exp) ->
isTaggedList exp, 'lambda'
lambdaParameters: (exp) ->
cadr exp
lambdaBody: (exp) ->
cddr exp
# We also provide a constructor for lambda expressions, which is
# used by definition-value, above:
makeLambda: (parameters, body) ->
cons('lambda', cons(parameters, body))
# Conditionals begin with if and have a predicate, a consequent, and an (optional)
# alternative. If the expression has no alternative part, we provide false as the alternative.
isIf: (exp) ->
isTaggedList exp, 'if'
ifPredicate: (exp) ->
cadr exp
ifConsequent: (exp) ->
caddr exp
ifAlternative: (exp) ->
return cadddr(exp) if cdddr(exp) != null
false
# We also provide a constructor for if expressions, to be used by cond->if to transform
# cond expressions into if expressions:
makeIf: (predicate, consequent, alternative) ->
list 'if', predicate, consequent, alternative
# Begin packages a sequence of expressions into a single expression. We include syntax
# operations on begin expressions to extract the actual sequence from the begin expression,
# as well as selectors that return the first expression and the rest of the expressions in the sequence
isBegin: (exp) ->
isTaggedList exp, 'begin'
beginActions: (exp) ->
cdr exp
isLastExp: (seq) ->
cdr(seq) is null
firstExp: (seq) ->
car seq
restExps: (seq) ->
cdr seq
# We also include a constructor sequenceExp (for use by condToIf) that transforms a sequence into
# a single expression, using begin if necessary:
sequenceExp: (seq) ->
return seq if seq is null
return firstExp seq if isLastExp seq
makeBegin seq
makeBegin: (seq) ->
cons 'begin', seq
# A procedure application is any compound expression that is not one of the above expression types.
# The car of the expression is the operator, and the cdr is the list of operands:
isApplication: (exp) ->
isPair exp
operator: (exp) ->
car exp
operands: (exp) ->
cdr exp
noOperands: (ops) ->
ops is null
firstOperand: (ops) ->
car ops
restOperands: (ops) ->
cdr ops
## ---------------------------------
## Derived expressions
## ---------------------------------
# Some special forms in our language can be defined in terms of expressions involving other special forms,
# rather than being implemented directly. One example is cond, which can be implemented as a nest of if expressions.
# For example, we can reduce the problem of evaluating the expression
#
# (cond ((> x 0) x)
# ((= x 0) (display 'zero) 0)
# (else (- x)))
#
# to the problem of evaluating the following expression involving if and begin expressions:
#
# (if (> x 0)
# x
# (if (= x 0)
# (begin (display 'zero)
# 0)
# (- x)))
#
# Implementing the evaluation of cond in this way simplifies the evaluator because it reduces the number of special
# forms for which the evaluation process must be explicitly specified.
#
# We include syntax procedures that extract the parts of a cond expression, and a procedure cond->if that transforms
# cond expressions into if expressions. A case analysis begins with cond and has a list of predicate-action clauses.
# A clause is an else clause if its predicate is the symbol else.
isCond: (exp) ->
isTaggedList exp, 'cond'
condClauses: (exp) ->
cdr exp
isCondElseClause: (clause) ->
eq condPredicate(clause), 'else'
condPredicate: (clause) ->
car clause
condActions: (clause) ->
cdr clause
condToIf: (exp) ->
expandClauses condClauses(exp)
expandClauses: (clauses) ->
return false if clauses is null # no else clause
first = car clauses
rest = cdr clauses
if isCondElseClause first
throw "ELSE clause isn't last -- COND->IF: #{clauses}" if rest is not null
return sequenceExp condActions(first)
makeIf(
condPredicate(first),
sequenceExp(condActions(first)),
expandClauses(rest)
)
# DS: `let` is also a derived expression and just a syntactic sugar for lambda
# we could handle this in parser, but for now process in runtime
#
# Expression:
#
# (let ((x 5)
# (y 6))
# (* x y))
#
# Transforms into (create lambda and immidiately execute it):
#
# ((lambda (x y) (* x y)) 5 6)
#
isLet: (exp) ->
isTaggedList exp, 'let'
letBindings: (exp) ->
cadr exp
letVars: (exp) ->
map car, letBindings(exp)
letValues: (exp, env) ->
map(
(binding) -> LispMachine.eval(cadr(binding), env),
letBindings(exp)
)
letBody: (exp) ->
cddr(exp)
letToLambda: (exp) ->
makeLambda(
letVars(exp),
letBody(exp)
)
## ---------------------------------
## 4.1.3 Evaluator Data Structures
## ---------------------------------
# In addition to defining the external syntax of expressions, the evaluator implementation must also define the data
# structures that the evaluator manipulates internally, as part of the execution of a program, such as the representation
# of procedures and environments and the representation of true and false.
extend @,
## ---------------------------------
## Testing of predicates
## ---------------------------------
# For conditionals, we accept anything to be true that is not the explicit false object.
isTrue: (x) ->
not eq x ,false
isFalse: (x) ->
eq x, false
## ---------------------------------
## Representing procedures
## ---------------------------------
# To handle primitives, we assume that we have available the following procedures:
#
# * applyPrimitiveProcedure <proc>, <args>
# applies the given primitive procedure to the argument values in the list <args> and returns the result of the application.
#
# * isPrimitiveProcedure <proc>
# tests whether <proc> is a primitive procedure.
#
# These mechanisms for handling primitives are further described in section 4.1.4.
#
# Compound procedures are constructed from parameters, procedure bodies, and environments using the constructor make-procedure:
makeProcedure: (parameters, body, env) ->
#list 'procedure', parameters, body, env
# because of posible circular reference we
# store environment of the procedure as separate property
procedureObject = list 'procedure', parameters, body
procedureObject.environment = env
procedureObject
isCompoundProcedure: (p) ->
isTaggedList p, 'procedure'
procedureParameters : (p) ->
cadr p
procedureBody: (p) ->
caddr p
procedureEnvironment: (p) ->
#cadddr p
# since we have circular reference in case of using
# list structure to store environment in procedure,
# we instead use separate property for that
p.environment
## ---------------------------------
## Operations on Environments
## ---------------------------------
# The evaluator needs operations for manipulating environments. As explained in section 3.2, an environment is a sequence of frames,
# where each frame is a table of bindings that associate variables with their corresponding values. We use the following operations
# for manipulating environments:
#
# * (lookup-variable-value <variable> <env>)
# returns the value that is bound to the symbol <variable> in the environment <env>, or signals an error if the variable is unbound.
#
# * (extend-environment <variables> <values> <base-env>)
# returns a new environment, consisting of a new frame in which the symbols in the list <variables> are bound to the corresponding
# elements in the list <values>, where the enclosing environment is the environment <base-env>.
#
# * (define-variable! <variable> <value> <env>)
# adds to the first frame in the environment <env> a new binding that associates the variable <variable> with the value <value>.
#
# * (set-variable-value! <variable> <value> <env>)
# changes the binding of the variable <variable> in the environment <env> so that the variable is now bound to the value <value>, or
# signals an error if the variable is unbound.
#
# To implement these operations we represent an environment as a list of frames. The enclosing environment of an environment is the cdr
# of the list. The empty environment is simply the empty list.
#
# ! The method described here is only one of many plausible ways to represent environments. Since we used data abstraction to isolate
# the rest of the evaluator from the detailed choice of representation, we could change the environment representation if we wanted
# to. (See exercise 4.11.) In a production-quality Lisp system, the speed of the evaluator's environment operations -- especially
# that of variable lookup -- has a major impact on the performance of the system. The representation described here, although conceptually
# simple, is not efficient and would not ordinarily be used in a production system.
enclosingEnvironment: (env) ->
cdr env
firstFrame: (env) ->
car env
TheEmptyEnvironment: []
# Each frame of an environment is represented as a pair of lists: a list of the variables bound in that frame and a list of
# the associated values.
makeFrame: (variables, values) ->
cons variables, values
frameVariables: (frame) ->
car frame
frameValues: (frame) ->
cdr frame
addBindingToFrame: (variable, val, frame) ->
setCar frame, cons(variable, car(frame))
setCdr frame, cons(val, cdr(frame))
# ad-hoc
setCar: (p, v) ->
p[0] = v
# ad-hoc
setCdr: (p, v) ->
p[1] = v
# To extend an environment by a new frame that associates variables with values, we make a frame consisting of the list of
# variables and the list of values, and we adjoin this to the environment. We signal an error if the number of variables
# does not match the number of values.
extendEnvironment: (vars, vals, baseEnv) ->
#console.log "extendEnvironment:", vars, vals, baseEnv
throw "Count of vars and vals is not the same: #{vars}, #{vals}" if vars.length != vals.length
cons(makeFrame(vars, vals), baseEnv)
# To look up a variable in an environment, we scan the list of variables in the first frame. If we find the desired
# variable, we return the corresponding element in the list of values. If we do not find the variable in the current
# frame, we search the enclosing environment, and so on. If we reach the empty environment, we signal an ``unbound variable'' error.
lookupVariableValue: (variable, env) ->
envLoop = (env) ->
scan = (vars, vals) ->
return envLoop enclosingEnvironment(env) if vars is null
return car vals if car(vars) is variable
scan cdr(vars), cdr(vals)
return "Error: Unbound variable: \"#{variable}\"" if eq env, TheEmptyEnvironment
frame = firstFrame env
scan frameVariables(frame), frameValues(frame)
envLoop env
# To set a variable to a new value in a specified environment, we scan for the variable, just as in lookup-variable-value,
# and change the corresponding value when we find it.
setVariableValue: (variable, val, env) ->
envLoop = (env) ->
scan = (vars, vals) ->
return envLoop enclosingEnvironment(env) if vars is null
return setCar vals, val if eq variable, car(vars)
scan cdr(vars), cdr(vals)
throw "Unbound variable -- SET: \"#{variable}\"" if eq env, TheEmptyEnvironment
frame = firstFrame env
scan frameVariables(frame), frameValues(frame)
envLoop env
# To define a variable, we search the first frame for a binding for the variable, and change the binding if it exists (just
# as in set-variable-value!). If no such binding exists, we adjoin one to the first frame.
defineVariable: (variable, val, env) ->
frame = firstFrame env
scan = (vars, vals) ->
if vars is null
addBindingToFrame variable, val, frame
return (if val and isCompoundProcedure(val) then "ok" else val)
if eq variable, car(vars)
setCar(vals, val)
return (if val and isCompoundProcedure(val) then "ok" else val)
scan cdr(vars), cdr(vals)
scan frameVariables(frame), frameValues(frame)
## ---------------------------------
## 4.1.4 Running the Evaluator as a Program
## ---------------------------------
# Given the evaluator, we have in our hands a description (expressed in CoffeeScript) of the process by which Lisp expressions are evaluated.
# One advantage of expressing the evaluator as a program is that we can run the program. This gives us, running within Lisp, a working
# model of how Lisp itself evaluates expressions. This can serve as a framework for experimenting with evaluation rules, as we shall do
# later in this chapter.
#
# Our evaluator program reduces expressions ultimately to the application of primitive procedures. Therefore, all that we need to run
# the evaluator is to create a mechanism that calls on the underlying Lisp system to model the application of primitive procedures.
#
# There must be a binding for each primitive procedure name, so that when eval evaluates the operator of an application of a primitive,
# it will find an object to pass to apply. We thus set up a global environment that associates unique objects with the names of the
# primitive procedures that can appear in the expressions we will be evaluating. The global environment also includes bindings for the
# symbols true and false, so that they can be used as variables in expressions to be evaluated.
extend @,
setupEnvironment: ->
initialEnv = extendEnvironment(
primitiveProcedureNames,
primitiveProcedureObjects,
TheEmptyEnvironment
)
defineVariable 'true', true, initialEnv
defineVariable 'false', false, initialEnv
defineVariable 'null', null, initialEnv
defineVariable 'nil', null, initialEnv
# define ad-hoc map in the global environment
execute("
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
", initialEnv)
initialEnv
# It does not matter how we represent the primitive procedure objects, so long as apply can identify and apply them by using
# the procedures primitive-procedure? and apply-primitive-procedure. We have chosen to represent a primitive procedure as a list
# beginning with the symbol primitive and containing a procedure in the underlying Lisp that implements that primitive.
# ad-hoc mapping on Coffee level
@map = (proc, items) ->
return null if items is null
cons(proc(car(items)), map(proc, cdr(items)))
extend @,
isPrimitiveProcedure: (proc) ->
isTaggedList proc, 'primitive'
primitiveImplementation: (proc) ->
cadr proc
primitiveProcedures: list(
# lists
list('car', car),
list('cdr', cdr),
list('cons', cons),
list('list', list),
list('list-ref', (l, i) -> l[i]),
list('length', (items) -> items.length),
list('append', (x, y) -> JSArray2LispList(x.concat(y))),
list('reverse', (x) -> JSArray2LispList(x.reverse())),
# predicates
list('true?', isTrue),
list('false?', isFalse),
list('pair?', isPair),
list('null?', (x) -> x is null),
# relational
list('=', eq),
list('eq', eq),
list('>', (x, y) -> x > y),
list('>=', (x, y) -> x >= y),
list('<', (x, y) -> x < y),
list('<=', (x, y) -> x <= y),
# some math
list('+', (args...) -> args.reduce (a, b) -> a + b),
list('*', (args...) -> args.reduce (a, b) -> a * b),
list('min', (args...) -> Math.min.apply Math, args),
list('max', (args...) -> Math.max.apply Math, args),
list('abs', (x) -> if x > 0 then x else -x),
list('-', (args...) ->
return -args[0] if args.length is 1
args.reduce (a, b) -> a - b
),
list('/', (args...) ->
return 1/args[0] if args.length is 1
args.reduce (a, b) -> a / b
)
)
@primitiveProcedureNames = map car, primitiveProcedures
@primitiveProcedureObjects = map ((proc) -> list 'primitive', cadr(proc)), primitiveProcedures
extend @,
# To apply a primitive procedure, we simply apply the implementation procedure to the arguments, using the
# underlying Lisp system:
applyPrimitiveProcedure: (proc, args) ->
applyProc = primitiveImplementation(proc)
if applyProc is car or applyProc is cdr
applyArgs = args
else if applyProc is cons
applyArgs = cons(car(args), cadr(args))
else
applyArgs = LispList2JSArray(args)
primitiveImplementation(proc) applyArgs...
# For convenience in running the metacircular evaluator, we provide a driver loop that models the read-eval-print loop of the
# underlying Lisp system. It prints a prompt, reads an input expression, evaluates this expression in the global environment,
# and prints the result. We precede each printed result by an output prompt so as to distinguish the value of the expression
# from other output that may be printed.
inputPrompt: ";;; Coffee-Lisp-Eval input:"
outputPrompt: ";;; Coffee-Lisp-Eval value:"
driverLoop: (input) ->
return 'no input' if not input
# promptForInput inputPrompt
output = LispMachine.eval(parse(input), TheGlobalEnvironment)
# announceOutput outputPrompt
userPrint output
output
execute: (input, env) ->
return 'no input' if not input
expressions = parse(input)
output = null
env ?= TheGlobalEnvironment
expressions.forEach (exp) ->
output = LispMachine.eval exp, env
if output and car(output) is "procedure"
return if isVariable(input) then "<#procedure \"#{input}\">" else "<#anonymous procedure>"
if isPair(output)
return if isPair(cdr(output)) then "(#{LispList2JSArray(output).join(' ')})" else "(#{output.join(' . ')})"
output
promptForInput: (string) ->
console.log string
announceOutput: (string) ->
console.log string
# We use a special printing procedure, user-print, to avoid printing the environment part of a compound procedure, which may
# be a very long list (or may even contain cycles).
userPrint: (object) ->
if isCompoundProcedure object
return console.log list('compound-procedure', procedureParameters(object), procedureBody(object), '<procedure-env>')
console.log object
## -----------------------------------------------------
## 4.1.7 Separating Syntactic Analysis from Execution
## -----------------------------------------------------
# The evaluator implemented above is simple, but it is very inefficient, because the syntactic analysis
# of expressions is interleaved with their execution. Thus if a program is executed many times, its syntax
# is analyzed many times. Consider, for example, evaluating (factorial 4) using the following definition of factorial:
#
# (define (factorial n)
# (if (= n 1)
# 1
# (* (factorial (- n 1)) n)))
#
# Each time factorial is called, the evaluator must determine that the body is an if expression and
# extract the predicate. Only then can it evaluate the predicate and dispatch on its value. Each time
# it evaluates the expression (* (factorial (- n 1)) n), or the subexpressions (factorial (- n 1)) and (- n 1),
# the evaluator must perform the case analysis in eval to determine that the expression is an application,
# and must extract its operator and operands. This analysis is expensive. Performing it repeatedly is wasteful.
#
# We can transform the evaluator to be significantly more efficient by arranging things so that syntactic
# analysis is performed only once.28 We split `eval`, which takes an expression and an environment, into two parts.
# The procedure `analyze` takes only the `expression`. It performs the syntactic analysis and returns a new procedure,
# the execution procedure, that encapsulates the work to be done in executing the analyzed expression. The execution
# procedure takes an environment as its argument and completes the evaluation. This saves work because analyze will be
# called only once on an expression, while the execution procedure may be called many times.
#
# With the separation into analysis and execution, eval now becomes
# DS: Save old (unoptimized `eval`)
@LispMachine.interpretationalEval = @LispMachine.eval
@LispMachine.eval = (exp, env) ->
# parse all needed data
executionProcedure = analyze(exp)
#console.log "executionProcedure #{executionProcedure}"
# and complete the execution
executionProcedure env
extend @,
# The result of calling analyze is the execution procedure to be applied to the environment. The analyze procedure
# is the same case analysis as performed by the original eval of section 4.1.1, except that the procedures to which we
# dispatch perform only analysis, not full evaluation:
analyze: (exp) ->
return analyzeSelfEvaluating exp if isSelfEvaluating exp
return analyzeQuoted exp if isQuoted exp
return analyzeVariable exp if isVariable exp
return analyzeAssignment exp if isAssignment exp
return analyzeDefinition exp if isDefinition exp
return analyzeIf exp if isIf exp
return analyzeLambda exp if isLambda exp
if isLet exp
return analyzeLet(analyzeLambda(letToLambda(exp)), exp)
return analyzeSequence(beginActions(exp)) if isBegin exp
return analyze(condToIf(exp)) if isCond exp
return analyzeApplication exp if isApplication exp
throw "Unknown expression type -- ANALYZE #{exp}"
# Here is the simplest syntactic analysis procedure, which handles self-evaluating expressions. It returns an execution
# procedure that ignores its environment argument and just returns the expression:
analyzeSelfEvaluating: (exp) ->
(env) -> exp
# For a quoted expression, we can gain a little efficiency by extracting the text of the quotation only once, in the
# analysis phase, rather than in the execution phase.
analyzeQuoted: (exp) ->
quotedValue = textOfQuotation exp
(env) -> quotedValue
# Looking up a variable value must still be done in the execution phase, since this depends upon knowing the environment.
analyzeVariable: (exp) ->
(env) -> lookupVariableValue exp, env
# `analyzeAssignment` also must defer actually setting the variable until the execution, when the environment has been supplied.
# However, the fact that the `assignmentValue` expression can be analyzed (recursively) during analysis is a major gain in
# efficiency, because the assignment-value expression will now be analyzed only once. The same holds true for definitions.
analyzeAssignment: (exp) ->
variable = assignmentVariable exp
valueProc = analyze(assignmentValue(exp))
(env) ->
setVariableValue(
variable,
valueProc(env),
env
)
"ok"
analyzeDefinition: (exp) ->
variable = definitionVariable exp
valueProc = analyze(definitionValue(exp))
(env) ->
defineVariable(
variable,
valueProc(env),
env
)
"ok"
# For if expressions, we extract and analyze the predicate, consequent, and alternative at analysis time.
analyzeIf: (exp) ->
predicateProc = analyze(ifPredicate(exp))
consequentProc = analyze(ifConsequent(exp))
alternativeProc = analyze(ifAlternative(exp))
(env) ->
return consequentProc env if predicateProc(env) is true
alternativeProc env
# Analyzing a lambda expression also achieves a major gain in efficiency: We analyze the lambda body only once,
# even though procedures resulting from evaluation of the lambda may be applied many times.
analyzeLambda: (exp) ->
vars = lambdaParameters exp
bodyProc = analyzeSequence(lambdaBody(exp))
(env) -> makeProcedure(vars, bodyProc, env)
# Analysis of a sequence of expressions (as in a begin or the body of a lambda expression) is more involved.
# Each expression in the sequence is analyzed, yielding an execution procedure. These execution procedures
# are combined to produce an execution procedure that takes an environment as argument and sequentially calls
# each individual execution procedure with the environment as argument.
analyzeSequence: (exps) ->
sequentially = (proc1, proc2) ->
(env) ->
proc1 env
proc2 env
sequenceLoop = (firstProc, restProcs) ->
return firstProc if restProcs is null
sequenceLoop(sequentially(firstProc, car(restProcs)), cdr(restProcs))
procs = map(analyze, exps)
throw "Empty sequence -- ANALYZE" if procs is null
sequenceLoop(car(procs), cdr(procs))
# To analyze an application, we analyze the operator and operands and construct an execution procedure that
# calls the operator execution procedure (to obtain the actual procedure to be applied) and the operand execution
# procedures (to obtain the actual arguments). We then pass these to execute-application, which is the analog of
# apply in section 4.1.1. Execute-application differs from apply in that the procedure body for a compound procedure
# has already been analyzed, so there is no need to do further analysis. Instead, we just call the execution procedure
# for the body on the extended environment.
analyzeApplication: (exp) ->
getOperatorProc = analyze(operator(exp))
operandProcs = map(analyze, operands(exp))
(env) ->
executeApplication(
getOperatorProc(env), # operator proc
map(((operandProc) -> operandProc(env)), operandProcs) # args
)
executeApplication: (proc, args) ->
if isPrimitiveProcedure proc
return applyPrimitiveProcedure(proc, args)
if isCompoundProcedure proc
code = procedureBody(proc)
return code(extendEnvironment(procedureParameters(proc), args, procedureEnvironment(proc)))
throw "Unknown procedure type -- EXECUTE-APPLICATION #{proc}"
# Our new evaluator uses the same data structures, syntax procedures, and run-time support
# procedures as in sections 4.1.2, 4.1.3, and 4.1.4.
analyzeLet: (lambda, exp) ->
(env) ->
executeApplication(
lambda(env),
letVals = letValues(exp, env)
)
# Now all we need to do to run the evaluator is to initialize the global environment and start the driver loop.
# Here is a sample interaction:
@TheGlobalEnvironment = setupEnvironment()
# debug aliases
@global = TheGlobalEnvironment
@empty = TheEmptyEnvironment
@G = TheGlobalEnvironment
@E = TheEmptyEnvironment | 64146 | # Lisp/Scheme evaluator, see: SICP, 4.1
#
# Port to CoffeeScript
# by <NAME> <<EMAIL>>
# (C) MIT Style License
#
# Features:
# - just a toy and very inefficient; just the version 0.1 ;)
#
# Scheme metacircular evaluator authors: book SICP
# see http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html#%_sec_4.1
#
# All comments in code are *not* my comments. This is the
# text of the chapter 4.1 of the SICP book
#
@LispMachine =
## --------------------------
## Eval
## --------------------------
# Eval takes as arguments an expression (exp)
# and an environment (env). It classifies the expression
# and directs its evaluation. Eval is structured as a case
# analysis of the syntactic type of the expression to be
# evaluated. In order to keep the procedure general, we express
# the determination of the type of an expression abstractly, making
# no commitment to any particular representation for the various
# types of expressions. Each type of expression has a predicate that tests
# for it and an abstract means for selecting its parts. This *abstract syntax*
# makes it easy to see how we can change the syntax of the language by using
# the same evaluator, but with a different collection of syntax procedures.
eval: (exp, env) ->
## --------------------------
## Primitive expressions
## --------------------------
# For self-evaluating expressions, such as numbers, eval returns the
# expression itself.
# console.log "isSelfEvaluating #{exp}", isSelfEvaluating(exp), typeof exp
if isSelfEvaluating exp
return exp
# Eval must look up variables in the environment to find their values.
# console.log "isVariable #{exp}", isVariable exp
if isVariable exp
return lookupVariableValue exp, env
## --------------------------
## Special forms
## --------------------------
# For quoted expressions, eval returns the expression that was quoted.
# console.log "isQuoted #{exp}", isQuoted exp
if isQuoted exp
return textOfQuotation exp
# An assignment to (or a definition of) a variable must recursively
# call eval to compute the new value to be associated with the variable.
# The environment must be modified to change (or create) the binding
# of the variable.
# console.log "isAssignment #{exp}", isAssignment exp
if isAssignment exp
return evalAssignment exp, env
# console.log "isDefinition #{exp}", isDefinition exp
if isDefinition exp
return evalDefinition exp, env
# An if expression requires special processing of its parts, so as to evaluate
# the consequent if the predicate is true, and otherwise to evaluate the alternative.
# console.log "isIf #{exp}", isIf exp
if isIf exp
return evalIf exp, env
# A lambda expression must be transformed into an applicable procedure by packaging
# together the parameters and body specified by the lambda expression with the
# environment of the evaluation.
#console.log "isLambda #{exp}", isLambda exp
if isLambda exp
return makeProcedure(
lambdaParameters(exp),
lambdaBody(exp),
env
)
# A begin expression requires evaluating its sequence of expressions in the order
# in which they appear.
# console.log "isBegin #{exp}", isBegin exp
if isBegin exp
return evalSequence(
beginActions(exp),
env
)
# A case analysis (cond) is transformed into a nest of if expressions and then evaluated.
# console.log "isCond #{exp}", isCond exp
if isCond exp
return LispMachine.eval(
condToIf(exp),
env
)
# console.log "isLet #{exp}", isLet exp
if isLet exp
return LispMachine.apply(
LispMachine.eval(
letToLambda(exp),
env
),
letValues(exp, env)
)
## --------------------------
## Combinations
## --------------------------
# For a procedure application, eval must recursively evaluate the operator part and the
# operands of the combination. The resulting procedure and arguments are passed to apply,
# which handles the actual procedure application.
#console.log "isApplication #{exp}", isApplication exp
if isApplication exp
return LispMachine.apply(
LispMachine.eval(operator(exp), env),
listOfValues(operands(exp), env)
)
throw "Unknown expression type -- LispMachine.eval: #{exp}"
## --------------------------
## Apply
## --------------------------
# Apply takes two arguments, a procedure and a list of arguments to which the procedure
# should be applied. Apply classifies procedures into two kinds: It calls *applyPrimitiveProcedure*
# to apply primitives; it applies compound procedures by sequentially evaluating the expressions
# that make up the body of the procedure. The environment for the evaluation of the body of a compound
# procedure is constructed by extending the base environment carried by the procedure to include a frame
# that binds the parameters of the procedure to the arguments to which the procedure is to be applied.
apply: (procedure, arguments) ->
#console.log "isPrimitiveProcedure", isPrimitiveProcedure procedure
if isPrimitiveProcedure procedure
return applyPrimitiveProcedure procedure, arguments
#console.log "isCompoundProcedure", isCompoundProcedure procedure
if isCompoundProcedure procedure
return evalSequence(
procedureBody(procedure),
extendEnvironment(
procedureParameters(procedure),
arguments,
procedureEnvironment(procedure)
)
)
throw "Unknown procedure type -- apply: #{procedure}"
##
## Helpers (global functions)
##
extend = (object, module) ->
for own k of module
object[k] = module[k]
object
extend @,
## --------------------------
## Procedure arguments
## --------------------------
# When eval processes a procedure application, it uses *listOfValues* to produce the list of arguments
# to which the procedure is to be applied. ListOfValues takes as an argument the operands of the combination.
# It evaluates each operand and returns a list of the corresponding values
listOfValues: (exps, env) ->
return null if noOperands exps
return cons(
LispMachine.eval(firstOperand(exps), env),
listOfValues(restOperands(exps), env)
)
## --------------------------
## Conditionals
## --------------------------
# EvalIf evaluates the predicate part of an if expression in the given environment. If the result is true, evalIf
# evaluates the consequent, otherwise it evaluates the alternative:
evalIf: (exp, env) ->
if LispMachine.eval(ifPredicate(exp), env)
return LispMachine.eval(ifConsequent(exp), env)
return LispMachine.eval(ifAlternative(exp), env)
## --------------------------
## Sequences
## --------------------------
# EvalSequence is used by apply to evaluate the sequence of expressions in a procedure body and by eval to evaluate
# the sequence of expressions in a begin expression. It takes as arguments a sequence of expressions and an environment,
# and evaluates the expressions in the order in which they occur. The value returned is the value of the final expression.
evalSequence: (exps, env) ->
if isLastExp exps
return LispMachine.eval(firstExp(exps), env)
LispMachine.eval(firstExp(exps), env)
evalSequence(restExps(exps), env)
## --------------------------
## Assignments and definitions
## --------------------------
# The following procedure handles assignments to variables. It calls eval to find the value to be assigned and transmits the
# variable and the resulting value to setVariableValue to be installed in the designated environment.
evalAssignment: (exp, env) ->
setVariableValue(
assignmentVariable(exp),
LispMachine.eval(assignmentValue(exp), env),
env
)
# Definitions of variables are handled in a similar manner.
evalDefinition: (exp, env) ->
defineVariable(
definitionVariable(exp),
LispMachine.eval(definitionValue(exp), env),
env
)
## ---------------------------------
## 4.1.2 Representing Expressions
## ---------------------------------
extend @,
# The only self-evaluating items are numbers and strings:
isSelfEvaluating: (exp) ->
return true if isNumber(exp) # or isString(exp)
false
# ad-hoc
isNumber: (exp) ->
not isNaN(Number(exp))
# ad-hoc
isString: (exp) ->
typeof exp is "string"
# Variables are represented by symbols:
isVariable: (exp) ->
isSymbol exp
# ad-hoc
isSymbol: (exp) ->
/^([a-z-A-Z0-9_$?!+*/=><\-]|>=|<=)+$/.test exp
# Quotations have the form (quote <text-of-quotation>)
isQuoted: (exp) ->
isTaggedList exp, 'quote'
textOfQuotation: (exp) ->
cadr exp
# `Quoted` is defined in terms of the procedure `isTaggedList`, which
# identifies lists beginning with a designated symbol:
isTaggedList: (exp, tag) ->
return false if not isPair exp
testTypeTag = (x) ->
eq car(exp), x
return tag.some testTypeTag if tag instanceof Array
testTypeTag tag
# ad-hoc
isPair: (o) ->
o instanceof Array and o.length is 2
cons: (x, y) ->
[x, y]
# ad-hoc
car: (p) ->
p[0] # (car '(1 2 3 4)) is 1
# ad-hoc
cdr: (p) ->
p[1] # (cdr '(1 2 3 4)) is '(2 3 4)
# ad-hoc
cadr: (o) ->
car(cdr(o)) # (cadr '(1 2 3 4)) is 2
caadr: (o) ->
car(car(cdr(o))) # (caadr '(1 (2 5) 3 4)) is 2
# ad-hoc
caddr: (o) ->
car(cdr(cdr(o))) # (caddr '(1 2 3 4)) is 3
# ad-hoc
cdadr: (o) ->
cdr(car(cdr(o))) # (cdadr '(1 (2 5) 3 4)) is (5)
# ad-hoc
cddr: (o) ->
cdr(cdr(o)) # (cddr '(1 2 3 4)) is (3 4)
# ad-hoc
cdddr: (o) ->
cdr(cdr(cdr(o))) # (cdddr '(1 2 3 4 5)) is (4 5)
# ad-hoc
cadddr: (o) ->
car(cdr(cdr(cdr(o)))) # (cdddr '(1 2 3 4 5)) is 4
# ad-hoc
eq: (x, y) ->
x == y
# ad-hoc
list: (items...) ->
items.reduceRight(
(y, x) -> [x, y],
null
)
# ad-hoc
# converts JS's array into Lisp's list
# Example: [1, 2, 3, 4] => [1, [2, [3, [4, null]]]]
# Rationale: to make cdr mutable
JSArray2LispList: (array) ->
array.reduceRight(
((y, x) ->
if x instanceof Array then cons(JSArray2LispList(x), y) else cons(x, y)),
null
)
# ad-hoc
# convers Lisp's list into JS's array
# Example: [1, [2, [3, [4, null]]]] => [1, 2, 3, 4]
# Rationale: use apply of JS functions
LispList2JSArray: (list) ->
retVal = []
while list
currentCar = car list
retVal.push(if isPair(currentCar) then LispList2JSArray(currentCar) else currentCar)
list = cdr list
retVal
# Assignments have the form (set! <variable> <value>)
isAssignment: (exp) ->
isTaggedList exp, 'set!'
assignmentVariable: (exp) ->
cadr exp
assignmentValue: (exp) ->
caddr exp
# Definitions have the form
#
# (define <variable> <value>)
#
# or the form
#
# (define (<variable> <parameter1> ... <parametern>)
# <body>)
#
# The latter form (standard procedure definition) is syntactic sugar for
#
# (define <variable>
# (lambda (<parameter1> ... <parametern>)
# <body>))
#
# The corresponding syntax procedures are the following:
isDefinition: (exp) ->
isTaggedList exp, ['define', 'setf']
definitionVariable: (exp) ->
return cadr exp if isSymbol cadr exp
caadr exp
definitionValue: (exp) ->
return caddr exp if isSymbol cadr exp
makeLambda(
cdadr(exp), # formal parameters
cddr(exp) # body
)
# Lambda expressions are lists that begin with the symbol lambda:
isLambda: (exp) ->
isTaggedList exp, 'lambda'
lambdaParameters: (exp) ->
cadr exp
lambdaBody: (exp) ->
cddr exp
# We also provide a constructor for lambda expressions, which is
# used by definition-value, above:
makeLambda: (parameters, body) ->
cons('lambda', cons(parameters, body))
# Conditionals begin with if and have a predicate, a consequent, and an (optional)
# alternative. If the expression has no alternative part, we provide false as the alternative.
isIf: (exp) ->
isTaggedList exp, 'if'
ifPredicate: (exp) ->
cadr exp
ifConsequent: (exp) ->
caddr exp
ifAlternative: (exp) ->
return cadddr(exp) if cdddr(exp) != null
false
# We also provide a constructor for if expressions, to be used by cond->if to transform
# cond expressions into if expressions:
makeIf: (predicate, consequent, alternative) ->
list 'if', predicate, consequent, alternative
# Begin packages a sequence of expressions into a single expression. We include syntax
# operations on begin expressions to extract the actual sequence from the begin expression,
# as well as selectors that return the first expression and the rest of the expressions in the sequence
isBegin: (exp) ->
isTaggedList exp, 'begin'
beginActions: (exp) ->
cdr exp
isLastExp: (seq) ->
cdr(seq) is null
firstExp: (seq) ->
car seq
restExps: (seq) ->
cdr seq
# We also include a constructor sequenceExp (for use by condToIf) that transforms a sequence into
# a single expression, using begin if necessary:
sequenceExp: (seq) ->
return seq if seq is null
return firstExp seq if isLastExp seq
makeBegin seq
makeBegin: (seq) ->
cons 'begin', seq
# A procedure application is any compound expression that is not one of the above expression types.
# The car of the expression is the operator, and the cdr is the list of operands:
isApplication: (exp) ->
isPair exp
operator: (exp) ->
car exp
operands: (exp) ->
cdr exp
noOperands: (ops) ->
ops is null
firstOperand: (ops) ->
car ops
restOperands: (ops) ->
cdr ops
## ---------------------------------
## Derived expressions
## ---------------------------------
# Some special forms in our language can be defined in terms of expressions involving other special forms,
# rather than being implemented directly. One example is cond, which can be implemented as a nest of if expressions.
# For example, we can reduce the problem of evaluating the expression
#
# (cond ((> x 0) x)
# ((= x 0) (display 'zero) 0)
# (else (- x)))
#
# to the problem of evaluating the following expression involving if and begin expressions:
#
# (if (> x 0)
# x
# (if (= x 0)
# (begin (display 'zero)
# 0)
# (- x)))
#
# Implementing the evaluation of cond in this way simplifies the evaluator because it reduces the number of special
# forms for which the evaluation process must be explicitly specified.
#
# We include syntax procedures that extract the parts of a cond expression, and a procedure cond->if that transforms
# cond expressions into if expressions. A case analysis begins with cond and has a list of predicate-action clauses.
# A clause is an else clause if its predicate is the symbol else.
isCond: (exp) ->
isTaggedList exp, 'cond'
condClauses: (exp) ->
cdr exp
isCondElseClause: (clause) ->
eq condPredicate(clause), 'else'
condPredicate: (clause) ->
car clause
condActions: (clause) ->
cdr clause
condToIf: (exp) ->
expandClauses condClauses(exp)
expandClauses: (clauses) ->
return false if clauses is null # no else clause
first = car clauses
rest = cdr clauses
if isCondElseClause first
throw "ELSE clause isn't last -- COND->IF: #{clauses}" if rest is not null
return sequenceExp condActions(first)
makeIf(
condPredicate(first),
sequenceExp(condActions(first)),
expandClauses(rest)
)
# DS: `let` is also a derived expression and just a syntactic sugar for lambda
# we could handle this in parser, but for now process in runtime
#
# Expression:
#
# (let ((x 5)
# (y 6))
# (* x y))
#
# Transforms into (create lambda and immidiately execute it):
#
# ((lambda (x y) (* x y)) 5 6)
#
isLet: (exp) ->
isTaggedList exp, 'let'
letBindings: (exp) ->
cadr exp
letVars: (exp) ->
map car, letBindings(exp)
letValues: (exp, env) ->
map(
(binding) -> LispMachine.eval(cadr(binding), env),
letBindings(exp)
)
letBody: (exp) ->
cddr(exp)
letToLambda: (exp) ->
makeLambda(
letVars(exp),
letBody(exp)
)
## ---------------------------------
## 4.1.3 Evaluator Data Structures
## ---------------------------------
# In addition to defining the external syntax of expressions, the evaluator implementation must also define the data
# structures that the evaluator manipulates internally, as part of the execution of a program, such as the representation
# of procedures and environments and the representation of true and false.
extend @,
## ---------------------------------
## Testing of predicates
## ---------------------------------
# For conditionals, we accept anything to be true that is not the explicit false object.
isTrue: (x) ->
not eq x ,false
isFalse: (x) ->
eq x, false
## ---------------------------------
## Representing procedures
## ---------------------------------
# To handle primitives, we assume that we have available the following procedures:
#
# * applyPrimitiveProcedure <proc>, <args>
# applies the given primitive procedure to the argument values in the list <args> and returns the result of the application.
#
# * isPrimitiveProcedure <proc>
# tests whether <proc> is a primitive procedure.
#
# These mechanisms for handling primitives are further described in section 4.1.4.
#
# Compound procedures are constructed from parameters, procedure bodies, and environments using the constructor make-procedure:
makeProcedure: (parameters, body, env) ->
#list 'procedure', parameters, body, env
# because of posible circular reference we
# store environment of the procedure as separate property
procedureObject = list 'procedure', parameters, body
procedureObject.environment = env
procedureObject
isCompoundProcedure: (p) ->
isTaggedList p, 'procedure'
procedureParameters : (p) ->
cadr p
procedureBody: (p) ->
caddr p
procedureEnvironment: (p) ->
#cadddr p
# since we have circular reference in case of using
# list structure to store environment in procedure,
# we instead use separate property for that
p.environment
## ---------------------------------
## Operations on Environments
## ---------------------------------
# The evaluator needs operations for manipulating environments. As explained in section 3.2, an environment is a sequence of frames,
# where each frame is a table of bindings that associate variables with their corresponding values. We use the following operations
# for manipulating environments:
#
# * (lookup-variable-value <variable> <env>)
# returns the value that is bound to the symbol <variable> in the environment <env>, or signals an error if the variable is unbound.
#
# * (extend-environment <variables> <values> <base-env>)
# returns a new environment, consisting of a new frame in which the symbols in the list <variables> are bound to the corresponding
# elements in the list <values>, where the enclosing environment is the environment <base-env>.
#
# * (define-variable! <variable> <value> <env>)
# adds to the first frame in the environment <env> a new binding that associates the variable <variable> with the value <value>.
#
# * (set-variable-value! <variable> <value> <env>)
# changes the binding of the variable <variable> in the environment <env> so that the variable is now bound to the value <value>, or
# signals an error if the variable is unbound.
#
# To implement these operations we represent an environment as a list of frames. The enclosing environment of an environment is the cdr
# of the list. The empty environment is simply the empty list.
#
# ! The method described here is only one of many plausible ways to represent environments. Since we used data abstraction to isolate
# the rest of the evaluator from the detailed choice of representation, we could change the environment representation if we wanted
# to. (See exercise 4.11.) In a production-quality Lisp system, the speed of the evaluator's environment operations -- especially
# that of variable lookup -- has a major impact on the performance of the system. The representation described here, although conceptually
# simple, is not efficient and would not ordinarily be used in a production system.
enclosingEnvironment: (env) ->
cdr env
firstFrame: (env) ->
car env
TheEmptyEnvironment: []
# Each frame of an environment is represented as a pair of lists: a list of the variables bound in that frame and a list of
# the associated values.
makeFrame: (variables, values) ->
cons variables, values
frameVariables: (frame) ->
car frame
frameValues: (frame) ->
cdr frame
addBindingToFrame: (variable, val, frame) ->
setCar frame, cons(variable, car(frame))
setCdr frame, cons(val, cdr(frame))
# ad-hoc
setCar: (p, v) ->
p[0] = v
# ad-hoc
setCdr: (p, v) ->
p[1] = v
# To extend an environment by a new frame that associates variables with values, we make a frame consisting of the list of
# variables and the list of values, and we adjoin this to the environment. We signal an error if the number of variables
# does not match the number of values.
extendEnvironment: (vars, vals, baseEnv) ->
#console.log "extendEnvironment:", vars, vals, baseEnv
throw "Count of vars and vals is not the same: #{vars}, #{vals}" if vars.length != vals.length
cons(makeFrame(vars, vals), baseEnv)
# To look up a variable in an environment, we scan the list of variables in the first frame. If we find the desired
# variable, we return the corresponding element in the list of values. If we do not find the variable in the current
# frame, we search the enclosing environment, and so on. If we reach the empty environment, we signal an ``unbound variable'' error.
lookupVariableValue: (variable, env) ->
envLoop = (env) ->
scan = (vars, vals) ->
return envLoop enclosingEnvironment(env) if vars is null
return car vals if car(vars) is variable
scan cdr(vars), cdr(vals)
return "Error: Unbound variable: \"#{variable}\"" if eq env, TheEmptyEnvironment
frame = firstFrame env
scan frameVariables(frame), frameValues(frame)
envLoop env
# To set a variable to a new value in a specified environment, we scan for the variable, just as in lookup-variable-value,
# and change the corresponding value when we find it.
setVariableValue: (variable, val, env) ->
envLoop = (env) ->
scan = (vars, vals) ->
return envLoop enclosingEnvironment(env) if vars is null
return setCar vals, val if eq variable, car(vars)
scan cdr(vars), cdr(vals)
throw "Unbound variable -- SET: \"#{variable}\"" if eq env, TheEmptyEnvironment
frame = firstFrame env
scan frameVariables(frame), frameValues(frame)
envLoop env
# To define a variable, we search the first frame for a binding for the variable, and change the binding if it exists (just
# as in set-variable-value!). If no such binding exists, we adjoin one to the first frame.
defineVariable: (variable, val, env) ->
frame = firstFrame env
scan = (vars, vals) ->
if vars is null
addBindingToFrame variable, val, frame
return (if val and isCompoundProcedure(val) then "ok" else val)
if eq variable, car(vars)
setCar(vals, val)
return (if val and isCompoundProcedure(val) then "ok" else val)
scan cdr(vars), cdr(vals)
scan frameVariables(frame), frameValues(frame)
## ---------------------------------
## 4.1.4 Running the Evaluator as a Program
## ---------------------------------
# Given the evaluator, we have in our hands a description (expressed in CoffeeScript) of the process by which Lisp expressions are evaluated.
# One advantage of expressing the evaluator as a program is that we can run the program. This gives us, running within Lisp, a working
# model of how Lisp itself evaluates expressions. This can serve as a framework for experimenting with evaluation rules, as we shall do
# later in this chapter.
#
# Our evaluator program reduces expressions ultimately to the application of primitive procedures. Therefore, all that we need to run
# the evaluator is to create a mechanism that calls on the underlying Lisp system to model the application of primitive procedures.
#
# There must be a binding for each primitive procedure name, so that when eval evaluates the operator of an application of a primitive,
# it will find an object to pass to apply. We thus set up a global environment that associates unique objects with the names of the
# primitive procedures that can appear in the expressions we will be evaluating. The global environment also includes bindings for the
# symbols true and false, so that they can be used as variables in expressions to be evaluated.
extend @,
setupEnvironment: ->
initialEnv = extendEnvironment(
primitiveProcedureNames,
primitiveProcedureObjects,
TheEmptyEnvironment
)
defineVariable 'true', true, initialEnv
defineVariable 'false', false, initialEnv
defineVariable 'null', null, initialEnv
defineVariable 'nil', null, initialEnv
# define ad-hoc map in the global environment
execute("
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
", initialEnv)
initialEnv
# It does not matter how we represent the primitive procedure objects, so long as apply can identify and apply them by using
# the procedures primitive-procedure? and apply-primitive-procedure. We have chosen to represent a primitive procedure as a list
# beginning with the symbol primitive and containing a procedure in the underlying Lisp that implements that primitive.
# ad-hoc mapping on Coffee level
@map = (proc, items) ->
return null if items is null
cons(proc(car(items)), map(proc, cdr(items)))
extend @,
isPrimitiveProcedure: (proc) ->
isTaggedList proc, 'primitive'
primitiveImplementation: (proc) ->
cadr proc
primitiveProcedures: list(
# lists
list('car', car),
list('cdr', cdr),
list('cons', cons),
list('list', list),
list('list-ref', (l, i) -> l[i]),
list('length', (items) -> items.length),
list('append', (x, y) -> JSArray2LispList(x.concat(y))),
list('reverse', (x) -> JSArray2LispList(x.reverse())),
# predicates
list('true?', isTrue),
list('false?', isFalse),
list('pair?', isPair),
list('null?', (x) -> x is null),
# relational
list('=', eq),
list('eq', eq),
list('>', (x, y) -> x > y),
list('>=', (x, y) -> x >= y),
list('<', (x, y) -> x < y),
list('<=', (x, y) -> x <= y),
# some math
list('+', (args...) -> args.reduce (a, b) -> a + b),
list('*', (args...) -> args.reduce (a, b) -> a * b),
list('min', (args...) -> Math.min.apply Math, args),
list('max', (args...) -> Math.max.apply Math, args),
list('abs', (x) -> if x > 0 then x else -x),
list('-', (args...) ->
return -args[0] if args.length is 1
args.reduce (a, b) -> a - b
),
list('/', (args...) ->
return 1/args[0] if args.length is 1
args.reduce (a, b) -> a / b
)
)
@primitiveProcedureNames = map car, primitiveProcedures
@primitiveProcedureObjects = map ((proc) -> list 'primitive', cadr(proc)), primitiveProcedures
extend @,
# To apply a primitive procedure, we simply apply the implementation procedure to the arguments, using the
# underlying Lisp system:
applyPrimitiveProcedure: (proc, args) ->
applyProc = primitiveImplementation(proc)
if applyProc is car or applyProc is cdr
applyArgs = args
else if applyProc is cons
applyArgs = cons(car(args), cadr(args))
else
applyArgs = LispList2JSArray(args)
primitiveImplementation(proc) applyArgs...
# For convenience in running the metacircular evaluator, we provide a driver loop that models the read-eval-print loop of the
# underlying Lisp system. It prints a prompt, reads an input expression, evaluates this expression in the global environment,
# and prints the result. We precede each printed result by an output prompt so as to distinguish the value of the expression
# from other output that may be printed.
inputPrompt: ";;; Coffee-Lisp-Eval input:"
outputPrompt: ";;; Coffee-Lisp-Eval value:"
driverLoop: (input) ->
return 'no input' if not input
# promptForInput inputPrompt
output = LispMachine.eval(parse(input), TheGlobalEnvironment)
# announceOutput outputPrompt
userPrint output
output
execute: (input, env) ->
return 'no input' if not input
expressions = parse(input)
output = null
env ?= TheGlobalEnvironment
expressions.forEach (exp) ->
output = LispMachine.eval exp, env
if output and car(output) is "procedure"
return if isVariable(input) then "<#procedure \"#{input}\">" else "<#anonymous procedure>"
if isPair(output)
return if isPair(cdr(output)) then "(#{LispList2JSArray(output).join(' ')})" else "(#{output.join(' . ')})"
output
promptForInput: (string) ->
console.log string
announceOutput: (string) ->
console.log string
# We use a special printing procedure, user-print, to avoid printing the environment part of a compound procedure, which may
# be a very long list (or may even contain cycles).
userPrint: (object) ->
if isCompoundProcedure object
return console.log list('compound-procedure', procedureParameters(object), procedureBody(object), '<procedure-env>')
console.log object
## -----------------------------------------------------
## 4.1.7 Separating Syntactic Analysis from Execution
## -----------------------------------------------------
# The evaluator implemented above is simple, but it is very inefficient, because the syntactic analysis
# of expressions is interleaved with their execution. Thus if a program is executed many times, its syntax
# is analyzed many times. Consider, for example, evaluating (factorial 4) using the following definition of factorial:
#
# (define (factorial n)
# (if (= n 1)
# 1
# (* (factorial (- n 1)) n)))
#
# Each time factorial is called, the evaluator must determine that the body is an if expression and
# extract the predicate. Only then can it evaluate the predicate and dispatch on its value. Each time
# it evaluates the expression (* (factorial (- n 1)) n), or the subexpressions (factorial (- n 1)) and (- n 1),
# the evaluator must perform the case analysis in eval to determine that the expression is an application,
# and must extract its operator and operands. This analysis is expensive. Performing it repeatedly is wasteful.
#
# We can transform the evaluator to be significantly more efficient by arranging things so that syntactic
# analysis is performed only once.28 We split `eval`, which takes an expression and an environment, into two parts.
# The procedure `analyze` takes only the `expression`. It performs the syntactic analysis and returns a new procedure,
# the execution procedure, that encapsulates the work to be done in executing the analyzed expression. The execution
# procedure takes an environment as its argument and completes the evaluation. This saves work because analyze will be
# called only once on an expression, while the execution procedure may be called many times.
#
# With the separation into analysis and execution, eval now becomes
# DS: Save old (unoptimized `eval`)
@LispMachine.interpretationalEval = @LispMachine.eval
@LispMachine.eval = (exp, env) ->
# parse all needed data
executionProcedure = analyze(exp)
#console.log "executionProcedure #{executionProcedure}"
# and complete the execution
executionProcedure env
extend @,
# The result of calling analyze is the execution procedure to be applied to the environment. The analyze procedure
# is the same case analysis as performed by the original eval of section 4.1.1, except that the procedures to which we
# dispatch perform only analysis, not full evaluation:
analyze: (exp) ->
return analyzeSelfEvaluating exp if isSelfEvaluating exp
return analyzeQuoted exp if isQuoted exp
return analyzeVariable exp if isVariable exp
return analyzeAssignment exp if isAssignment exp
return analyzeDefinition exp if isDefinition exp
return analyzeIf exp if isIf exp
return analyzeLambda exp if isLambda exp
if isLet exp
return analyzeLet(analyzeLambda(letToLambda(exp)), exp)
return analyzeSequence(beginActions(exp)) if isBegin exp
return analyze(condToIf(exp)) if isCond exp
return analyzeApplication exp if isApplication exp
throw "Unknown expression type -- ANALYZE #{exp}"
# Here is the simplest syntactic analysis procedure, which handles self-evaluating expressions. It returns an execution
# procedure that ignores its environment argument and just returns the expression:
analyzeSelfEvaluating: (exp) ->
(env) -> exp
# For a quoted expression, we can gain a little efficiency by extracting the text of the quotation only once, in the
# analysis phase, rather than in the execution phase.
analyzeQuoted: (exp) ->
quotedValue = textOfQuotation exp
(env) -> quotedValue
# Looking up a variable value must still be done in the execution phase, since this depends upon knowing the environment.
analyzeVariable: (exp) ->
(env) -> lookupVariableValue exp, env
# `analyzeAssignment` also must defer actually setting the variable until the execution, when the environment has been supplied.
# However, the fact that the `assignmentValue` expression can be analyzed (recursively) during analysis is a major gain in
# efficiency, because the assignment-value expression will now be analyzed only once. The same holds true for definitions.
analyzeAssignment: (exp) ->
variable = assignmentVariable exp
valueProc = analyze(assignmentValue(exp))
(env) ->
setVariableValue(
variable,
valueProc(env),
env
)
"ok"
analyzeDefinition: (exp) ->
variable = definitionVariable exp
valueProc = analyze(definitionValue(exp))
(env) ->
defineVariable(
variable,
valueProc(env),
env
)
"ok"
# For if expressions, we extract and analyze the predicate, consequent, and alternative at analysis time.
analyzeIf: (exp) ->
predicateProc = analyze(ifPredicate(exp))
consequentProc = analyze(ifConsequent(exp))
alternativeProc = analyze(ifAlternative(exp))
(env) ->
return consequentProc env if predicateProc(env) is true
alternativeProc env
# Analyzing a lambda expression also achieves a major gain in efficiency: We analyze the lambda body only once,
# even though procedures resulting from evaluation of the lambda may be applied many times.
analyzeLambda: (exp) ->
vars = lambdaParameters exp
bodyProc = analyzeSequence(lambdaBody(exp))
(env) -> makeProcedure(vars, bodyProc, env)
# Analysis of a sequence of expressions (as in a begin or the body of a lambda expression) is more involved.
# Each expression in the sequence is analyzed, yielding an execution procedure. These execution procedures
# are combined to produce an execution procedure that takes an environment as argument and sequentially calls
# each individual execution procedure with the environment as argument.
analyzeSequence: (exps) ->
sequentially = (proc1, proc2) ->
(env) ->
proc1 env
proc2 env
sequenceLoop = (firstProc, restProcs) ->
return firstProc if restProcs is null
sequenceLoop(sequentially(firstProc, car(restProcs)), cdr(restProcs))
procs = map(analyze, exps)
throw "Empty sequence -- ANALYZE" if procs is null
sequenceLoop(car(procs), cdr(procs))
# To analyze an application, we analyze the operator and operands and construct an execution procedure that
# calls the operator execution procedure (to obtain the actual procedure to be applied) and the operand execution
# procedures (to obtain the actual arguments). We then pass these to execute-application, which is the analog of
# apply in section 4.1.1. Execute-application differs from apply in that the procedure body for a compound procedure
# has already been analyzed, so there is no need to do further analysis. Instead, we just call the execution procedure
# for the body on the extended environment.
analyzeApplication: (exp) ->
getOperatorProc = analyze(operator(exp))
operandProcs = map(analyze, operands(exp))
(env) ->
executeApplication(
getOperatorProc(env), # operator proc
map(((operandProc) -> operandProc(env)), operandProcs) # args
)
executeApplication: (proc, args) ->
if isPrimitiveProcedure proc
return applyPrimitiveProcedure(proc, args)
if isCompoundProcedure proc
code = procedureBody(proc)
return code(extendEnvironment(procedureParameters(proc), args, procedureEnvironment(proc)))
throw "Unknown procedure type -- EXECUTE-APPLICATION #{proc}"
# Our new evaluator uses the same data structures, syntax procedures, and run-time support
# procedures as in sections 4.1.2, 4.1.3, and 4.1.4.
analyzeLet: (lambda, exp) ->
(env) ->
executeApplication(
lambda(env),
letVals = letValues(exp, env)
)
# Now all we need to do to run the evaluator is to initialize the global environment and start the driver loop.
# Here is a sample interaction:
@TheGlobalEnvironment = setupEnvironment()
# debug aliases
@global = TheGlobalEnvironment
@empty = TheEmptyEnvironment
@G = TheGlobalEnvironment
@E = TheEmptyEnvironment | true | # Lisp/Scheme evaluator, see: SICP, 4.1
#
# Port to CoffeeScript
# by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# (C) MIT Style License
#
# Features:
# - just a toy and very inefficient; just the version 0.1 ;)
#
# Scheme metacircular evaluator authors: book SICP
# see http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html#%_sec_4.1
#
# All comments in code are *not* my comments. This is the
# text of the chapter 4.1 of the SICP book
#
@LispMachine =
## --------------------------
## Eval
## --------------------------
# Eval takes as arguments an expression (exp)
# and an environment (env). It classifies the expression
# and directs its evaluation. Eval is structured as a case
# analysis of the syntactic type of the expression to be
# evaluated. In order to keep the procedure general, we express
# the determination of the type of an expression abstractly, making
# no commitment to any particular representation for the various
# types of expressions. Each type of expression has a predicate that tests
# for it and an abstract means for selecting its parts. This *abstract syntax*
# makes it easy to see how we can change the syntax of the language by using
# the same evaluator, but with a different collection of syntax procedures.
eval: (exp, env) ->
## --------------------------
## Primitive expressions
## --------------------------
# For self-evaluating expressions, such as numbers, eval returns the
# expression itself.
# console.log "isSelfEvaluating #{exp}", isSelfEvaluating(exp), typeof exp
if isSelfEvaluating exp
return exp
# Eval must look up variables in the environment to find their values.
# console.log "isVariable #{exp}", isVariable exp
if isVariable exp
return lookupVariableValue exp, env
## --------------------------
## Special forms
## --------------------------
# For quoted expressions, eval returns the expression that was quoted.
# console.log "isQuoted #{exp}", isQuoted exp
if isQuoted exp
return textOfQuotation exp
# An assignment to (or a definition of) a variable must recursively
# call eval to compute the new value to be associated with the variable.
# The environment must be modified to change (or create) the binding
# of the variable.
# console.log "isAssignment #{exp}", isAssignment exp
if isAssignment exp
return evalAssignment exp, env
# console.log "isDefinition #{exp}", isDefinition exp
if isDefinition exp
return evalDefinition exp, env
# An if expression requires special processing of its parts, so as to evaluate
# the consequent if the predicate is true, and otherwise to evaluate the alternative.
# console.log "isIf #{exp}", isIf exp
if isIf exp
return evalIf exp, env
# A lambda expression must be transformed into an applicable procedure by packaging
# together the parameters and body specified by the lambda expression with the
# environment of the evaluation.
#console.log "isLambda #{exp}", isLambda exp
if isLambda exp
return makeProcedure(
lambdaParameters(exp),
lambdaBody(exp),
env
)
# A begin expression requires evaluating its sequence of expressions in the order
# in which they appear.
# console.log "isBegin #{exp}", isBegin exp
if isBegin exp
return evalSequence(
beginActions(exp),
env
)
# A case analysis (cond) is transformed into a nest of if expressions and then evaluated.
# console.log "isCond #{exp}", isCond exp
if isCond exp
return LispMachine.eval(
condToIf(exp),
env
)
# console.log "isLet #{exp}", isLet exp
if isLet exp
return LispMachine.apply(
LispMachine.eval(
letToLambda(exp),
env
),
letValues(exp, env)
)
## --------------------------
## Combinations
## --------------------------
# For a procedure application, eval must recursively evaluate the operator part and the
# operands of the combination. The resulting procedure and arguments are passed to apply,
# which handles the actual procedure application.
#console.log "isApplication #{exp}", isApplication exp
if isApplication exp
return LispMachine.apply(
LispMachine.eval(operator(exp), env),
listOfValues(operands(exp), env)
)
throw "Unknown expression type -- LispMachine.eval: #{exp}"
## --------------------------
## Apply
## --------------------------
# Apply takes two arguments, a procedure and a list of arguments to which the procedure
# should be applied. Apply classifies procedures into two kinds: It calls *applyPrimitiveProcedure*
# to apply primitives; it applies compound procedures by sequentially evaluating the expressions
# that make up the body of the procedure. The environment for the evaluation of the body of a compound
# procedure is constructed by extending the base environment carried by the procedure to include a frame
# that binds the parameters of the procedure to the arguments to which the procedure is to be applied.
apply: (procedure, arguments) ->
#console.log "isPrimitiveProcedure", isPrimitiveProcedure procedure
if isPrimitiveProcedure procedure
return applyPrimitiveProcedure procedure, arguments
#console.log "isCompoundProcedure", isCompoundProcedure procedure
if isCompoundProcedure procedure
return evalSequence(
procedureBody(procedure),
extendEnvironment(
procedureParameters(procedure),
arguments,
procedureEnvironment(procedure)
)
)
throw "Unknown procedure type -- apply: #{procedure}"
##
## Helpers (global functions)
##
extend = (object, module) ->
for own k of module
object[k] = module[k]
object
extend @,
## --------------------------
## Procedure arguments
## --------------------------
# When eval processes a procedure application, it uses *listOfValues* to produce the list of arguments
# to which the procedure is to be applied. ListOfValues takes as an argument the operands of the combination.
# It evaluates each operand and returns a list of the corresponding values
listOfValues: (exps, env) ->
return null if noOperands exps
return cons(
LispMachine.eval(firstOperand(exps), env),
listOfValues(restOperands(exps), env)
)
## --------------------------
## Conditionals
## --------------------------
# EvalIf evaluates the predicate part of an if expression in the given environment. If the result is true, evalIf
# evaluates the consequent, otherwise it evaluates the alternative:
evalIf: (exp, env) ->
if LispMachine.eval(ifPredicate(exp), env)
return LispMachine.eval(ifConsequent(exp), env)
return LispMachine.eval(ifAlternative(exp), env)
## --------------------------
## Sequences
## --------------------------
# EvalSequence is used by apply to evaluate the sequence of expressions in a procedure body and by eval to evaluate
# the sequence of expressions in a begin expression. It takes as arguments a sequence of expressions and an environment,
# and evaluates the expressions in the order in which they occur. The value returned is the value of the final expression.
evalSequence: (exps, env) ->
if isLastExp exps
return LispMachine.eval(firstExp(exps), env)
LispMachine.eval(firstExp(exps), env)
evalSequence(restExps(exps), env)
## --------------------------
## Assignments and definitions
## --------------------------
# The following procedure handles assignments to variables. It calls eval to find the value to be assigned and transmits the
# variable and the resulting value to setVariableValue to be installed in the designated environment.
evalAssignment: (exp, env) ->
setVariableValue(
assignmentVariable(exp),
LispMachine.eval(assignmentValue(exp), env),
env
)
# Definitions of variables are handled in a similar manner.
evalDefinition: (exp, env) ->
defineVariable(
definitionVariable(exp),
LispMachine.eval(definitionValue(exp), env),
env
)
## ---------------------------------
## 4.1.2 Representing Expressions
## ---------------------------------
extend @,
# The only self-evaluating items are numbers and strings:
isSelfEvaluating: (exp) ->
return true if isNumber(exp) # or isString(exp)
false
# ad-hoc
isNumber: (exp) ->
not isNaN(Number(exp))
# ad-hoc
isString: (exp) ->
typeof exp is "string"
# Variables are represented by symbols:
isVariable: (exp) ->
isSymbol exp
# ad-hoc
isSymbol: (exp) ->
/^([a-z-A-Z0-9_$?!+*/=><\-]|>=|<=)+$/.test exp
# Quotations have the form (quote <text-of-quotation>)
isQuoted: (exp) ->
isTaggedList exp, 'quote'
textOfQuotation: (exp) ->
cadr exp
# `Quoted` is defined in terms of the procedure `isTaggedList`, which
# identifies lists beginning with a designated symbol:
isTaggedList: (exp, tag) ->
return false if not isPair exp
testTypeTag = (x) ->
eq car(exp), x
return tag.some testTypeTag if tag instanceof Array
testTypeTag tag
# ad-hoc
isPair: (o) ->
o instanceof Array and o.length is 2
cons: (x, y) ->
[x, y]
# ad-hoc
car: (p) ->
p[0] # (car '(1 2 3 4)) is 1
# ad-hoc
cdr: (p) ->
p[1] # (cdr '(1 2 3 4)) is '(2 3 4)
# ad-hoc
cadr: (o) ->
car(cdr(o)) # (cadr '(1 2 3 4)) is 2
caadr: (o) ->
car(car(cdr(o))) # (caadr '(1 (2 5) 3 4)) is 2
# ad-hoc
caddr: (o) ->
car(cdr(cdr(o))) # (caddr '(1 2 3 4)) is 3
# ad-hoc
cdadr: (o) ->
cdr(car(cdr(o))) # (cdadr '(1 (2 5) 3 4)) is (5)
# ad-hoc
cddr: (o) ->
cdr(cdr(o)) # (cddr '(1 2 3 4)) is (3 4)
# ad-hoc
cdddr: (o) ->
cdr(cdr(cdr(o))) # (cdddr '(1 2 3 4 5)) is (4 5)
# ad-hoc
cadddr: (o) ->
car(cdr(cdr(cdr(o)))) # (cdddr '(1 2 3 4 5)) is 4
# ad-hoc
eq: (x, y) ->
x == y
# ad-hoc
list: (items...) ->
items.reduceRight(
(y, x) -> [x, y],
null
)
# ad-hoc
# converts JS's array into Lisp's list
# Example: [1, 2, 3, 4] => [1, [2, [3, [4, null]]]]
# Rationale: to make cdr mutable
JSArray2LispList: (array) ->
array.reduceRight(
((y, x) ->
if x instanceof Array then cons(JSArray2LispList(x), y) else cons(x, y)),
null
)
# ad-hoc
# convers Lisp's list into JS's array
# Example: [1, [2, [3, [4, null]]]] => [1, 2, 3, 4]
# Rationale: use apply of JS functions
LispList2JSArray: (list) ->
retVal = []
while list
currentCar = car list
retVal.push(if isPair(currentCar) then LispList2JSArray(currentCar) else currentCar)
list = cdr list
retVal
# Assignments have the form (set! <variable> <value>)
isAssignment: (exp) ->
isTaggedList exp, 'set!'
assignmentVariable: (exp) ->
cadr exp
assignmentValue: (exp) ->
caddr exp
# Definitions have the form
#
# (define <variable> <value>)
#
# or the form
#
# (define (<variable> <parameter1> ... <parametern>)
# <body>)
#
# The latter form (standard procedure definition) is syntactic sugar for
#
# (define <variable>
# (lambda (<parameter1> ... <parametern>)
# <body>))
#
# The corresponding syntax procedures are the following:
isDefinition: (exp) ->
isTaggedList exp, ['define', 'setf']
definitionVariable: (exp) ->
return cadr exp if isSymbol cadr exp
caadr exp
definitionValue: (exp) ->
return caddr exp if isSymbol cadr exp
makeLambda(
cdadr(exp), # formal parameters
cddr(exp) # body
)
# Lambda expressions are lists that begin with the symbol lambda:
isLambda: (exp) ->
isTaggedList exp, 'lambda'
lambdaParameters: (exp) ->
cadr exp
lambdaBody: (exp) ->
cddr exp
# We also provide a constructor for lambda expressions, which is
# used by definition-value, above:
makeLambda: (parameters, body) ->
cons('lambda', cons(parameters, body))
# Conditionals begin with if and have a predicate, a consequent, and an (optional)
# alternative. If the expression has no alternative part, we provide false as the alternative.
isIf: (exp) ->
isTaggedList exp, 'if'
ifPredicate: (exp) ->
cadr exp
ifConsequent: (exp) ->
caddr exp
ifAlternative: (exp) ->
return cadddr(exp) if cdddr(exp) != null
false
# We also provide a constructor for if expressions, to be used by cond->if to transform
# cond expressions into if expressions:
makeIf: (predicate, consequent, alternative) ->
list 'if', predicate, consequent, alternative
# Begin packages a sequence of expressions into a single expression. We include syntax
# operations on begin expressions to extract the actual sequence from the begin expression,
# as well as selectors that return the first expression and the rest of the expressions in the sequence
isBegin: (exp) ->
isTaggedList exp, 'begin'
beginActions: (exp) ->
cdr exp
isLastExp: (seq) ->
cdr(seq) is null
firstExp: (seq) ->
car seq
restExps: (seq) ->
cdr seq
# We also include a constructor sequenceExp (for use by condToIf) that transforms a sequence into
# a single expression, using begin if necessary:
sequenceExp: (seq) ->
return seq if seq is null
return firstExp seq if isLastExp seq
makeBegin seq
makeBegin: (seq) ->
cons 'begin', seq
# A procedure application is any compound expression that is not one of the above expression types.
# The car of the expression is the operator, and the cdr is the list of operands:
isApplication: (exp) ->
isPair exp
operator: (exp) ->
car exp
operands: (exp) ->
cdr exp
noOperands: (ops) ->
ops is null
firstOperand: (ops) ->
car ops
restOperands: (ops) ->
cdr ops
## ---------------------------------
## Derived expressions
## ---------------------------------
# Some special forms in our language can be defined in terms of expressions involving other special forms,
# rather than being implemented directly. One example is cond, which can be implemented as a nest of if expressions.
# For example, we can reduce the problem of evaluating the expression
#
# (cond ((> x 0) x)
# ((= x 0) (display 'zero) 0)
# (else (- x)))
#
# to the problem of evaluating the following expression involving if and begin expressions:
#
# (if (> x 0)
# x
# (if (= x 0)
# (begin (display 'zero)
# 0)
# (- x)))
#
# Implementing the evaluation of cond in this way simplifies the evaluator because it reduces the number of special
# forms for which the evaluation process must be explicitly specified.
#
# We include syntax procedures that extract the parts of a cond expression, and a procedure cond->if that transforms
# cond expressions into if expressions. A case analysis begins with cond and has a list of predicate-action clauses.
# A clause is an else clause if its predicate is the symbol else.
isCond: (exp) ->
isTaggedList exp, 'cond'
condClauses: (exp) ->
cdr exp
isCondElseClause: (clause) ->
eq condPredicate(clause), 'else'
condPredicate: (clause) ->
car clause
condActions: (clause) ->
cdr clause
condToIf: (exp) ->
expandClauses condClauses(exp)
expandClauses: (clauses) ->
return false if clauses is null # no else clause
first = car clauses
rest = cdr clauses
if isCondElseClause first
throw "ELSE clause isn't last -- COND->IF: #{clauses}" if rest is not null
return sequenceExp condActions(first)
makeIf(
condPredicate(first),
sequenceExp(condActions(first)),
expandClauses(rest)
)
# DS: `let` is also a derived expression and just a syntactic sugar for lambda
# we could handle this in parser, but for now process in runtime
#
# Expression:
#
# (let ((x 5)
# (y 6))
# (* x y))
#
# Transforms into (create lambda and immidiately execute it):
#
# ((lambda (x y) (* x y)) 5 6)
#
isLet: (exp) ->
isTaggedList exp, 'let'
letBindings: (exp) ->
cadr exp
letVars: (exp) ->
map car, letBindings(exp)
letValues: (exp, env) ->
map(
(binding) -> LispMachine.eval(cadr(binding), env),
letBindings(exp)
)
letBody: (exp) ->
cddr(exp)
letToLambda: (exp) ->
makeLambda(
letVars(exp),
letBody(exp)
)
## ---------------------------------
## 4.1.3 Evaluator Data Structures
## ---------------------------------
# In addition to defining the external syntax of expressions, the evaluator implementation must also define the data
# structures that the evaluator manipulates internally, as part of the execution of a program, such as the representation
# of procedures and environments and the representation of true and false.
extend @,
## ---------------------------------
## Testing of predicates
## ---------------------------------
# For conditionals, we accept anything to be true that is not the explicit false object.
isTrue: (x) ->
not eq x ,false
isFalse: (x) ->
eq x, false
## ---------------------------------
## Representing procedures
## ---------------------------------
# To handle primitives, we assume that we have available the following procedures:
#
# * applyPrimitiveProcedure <proc>, <args>
# applies the given primitive procedure to the argument values in the list <args> and returns the result of the application.
#
# * isPrimitiveProcedure <proc>
# tests whether <proc> is a primitive procedure.
#
# These mechanisms for handling primitives are further described in section 4.1.4.
#
# Compound procedures are constructed from parameters, procedure bodies, and environments using the constructor make-procedure:
makeProcedure: (parameters, body, env) ->
#list 'procedure', parameters, body, env
# because of posible circular reference we
# store environment of the procedure as separate property
procedureObject = list 'procedure', parameters, body
procedureObject.environment = env
procedureObject
isCompoundProcedure: (p) ->
isTaggedList p, 'procedure'
procedureParameters : (p) ->
cadr p
procedureBody: (p) ->
caddr p
procedureEnvironment: (p) ->
#cadddr p
# since we have circular reference in case of using
# list structure to store environment in procedure,
# we instead use separate property for that
p.environment
## ---------------------------------
## Operations on Environments
## ---------------------------------
# The evaluator needs operations for manipulating environments. As explained in section 3.2, an environment is a sequence of frames,
# where each frame is a table of bindings that associate variables with their corresponding values. We use the following operations
# for manipulating environments:
#
# * (lookup-variable-value <variable> <env>)
# returns the value that is bound to the symbol <variable> in the environment <env>, or signals an error if the variable is unbound.
#
# * (extend-environment <variables> <values> <base-env>)
# returns a new environment, consisting of a new frame in which the symbols in the list <variables> are bound to the corresponding
# elements in the list <values>, where the enclosing environment is the environment <base-env>.
#
# * (define-variable! <variable> <value> <env>)
# adds to the first frame in the environment <env> a new binding that associates the variable <variable> with the value <value>.
#
# * (set-variable-value! <variable> <value> <env>)
# changes the binding of the variable <variable> in the environment <env> so that the variable is now bound to the value <value>, or
# signals an error if the variable is unbound.
#
# To implement these operations we represent an environment as a list of frames. The enclosing environment of an environment is the cdr
# of the list. The empty environment is simply the empty list.
#
# ! The method described here is only one of many plausible ways to represent environments. Since we used data abstraction to isolate
# the rest of the evaluator from the detailed choice of representation, we could change the environment representation if we wanted
# to. (See exercise 4.11.) In a production-quality Lisp system, the speed of the evaluator's environment operations -- especially
# that of variable lookup -- has a major impact on the performance of the system. The representation described here, although conceptually
# simple, is not efficient and would not ordinarily be used in a production system.
enclosingEnvironment: (env) ->
cdr env
firstFrame: (env) ->
car env
TheEmptyEnvironment: []
# Each frame of an environment is represented as a pair of lists: a list of the variables bound in that frame and a list of
# the associated values.
makeFrame: (variables, values) ->
cons variables, values
frameVariables: (frame) ->
car frame
frameValues: (frame) ->
cdr frame
addBindingToFrame: (variable, val, frame) ->
setCar frame, cons(variable, car(frame))
setCdr frame, cons(val, cdr(frame))
# ad-hoc
setCar: (p, v) ->
p[0] = v
# ad-hoc
setCdr: (p, v) ->
p[1] = v
# To extend an environment by a new frame that associates variables with values, we make a frame consisting of the list of
# variables and the list of values, and we adjoin this to the environment. We signal an error if the number of variables
# does not match the number of values.
extendEnvironment: (vars, vals, baseEnv) ->
#console.log "extendEnvironment:", vars, vals, baseEnv
throw "Count of vars and vals is not the same: #{vars}, #{vals}" if vars.length != vals.length
cons(makeFrame(vars, vals), baseEnv)
# To look up a variable in an environment, we scan the list of variables in the first frame. If we find the desired
# variable, we return the corresponding element in the list of values. If we do not find the variable in the current
# frame, we search the enclosing environment, and so on. If we reach the empty environment, we signal an ``unbound variable'' error.
lookupVariableValue: (variable, env) ->
envLoop = (env) ->
scan = (vars, vals) ->
return envLoop enclosingEnvironment(env) if vars is null
return car vals if car(vars) is variable
scan cdr(vars), cdr(vals)
return "Error: Unbound variable: \"#{variable}\"" if eq env, TheEmptyEnvironment
frame = firstFrame env
scan frameVariables(frame), frameValues(frame)
envLoop env
# To set a variable to a new value in a specified environment, we scan for the variable, just as in lookup-variable-value,
# and change the corresponding value when we find it.
setVariableValue: (variable, val, env) ->
envLoop = (env) ->
scan = (vars, vals) ->
return envLoop enclosingEnvironment(env) if vars is null
return setCar vals, val if eq variable, car(vars)
scan cdr(vars), cdr(vals)
throw "Unbound variable -- SET: \"#{variable}\"" if eq env, TheEmptyEnvironment
frame = firstFrame env
scan frameVariables(frame), frameValues(frame)
envLoop env
# To define a variable, we search the first frame for a binding for the variable, and change the binding if it exists (just
# as in set-variable-value!). If no such binding exists, we adjoin one to the first frame.
defineVariable: (variable, val, env) ->
frame = firstFrame env
scan = (vars, vals) ->
if vars is null
addBindingToFrame variable, val, frame
return (if val and isCompoundProcedure(val) then "ok" else val)
if eq variable, car(vars)
setCar(vals, val)
return (if val and isCompoundProcedure(val) then "ok" else val)
scan cdr(vars), cdr(vals)
scan frameVariables(frame), frameValues(frame)
## ---------------------------------
## 4.1.4 Running the Evaluator as a Program
## ---------------------------------
# Given the evaluator, we have in our hands a description (expressed in CoffeeScript) of the process by which Lisp expressions are evaluated.
# One advantage of expressing the evaluator as a program is that we can run the program. This gives us, running within Lisp, a working
# model of how Lisp itself evaluates expressions. This can serve as a framework for experimenting with evaluation rules, as we shall do
# later in this chapter.
#
# Our evaluator program reduces expressions ultimately to the application of primitive procedures. Therefore, all that we need to run
# the evaluator is to create a mechanism that calls on the underlying Lisp system to model the application of primitive procedures.
#
# There must be a binding for each primitive procedure name, so that when eval evaluates the operator of an application of a primitive,
# it will find an object to pass to apply. We thus set up a global environment that associates unique objects with the names of the
# primitive procedures that can appear in the expressions we will be evaluating. The global environment also includes bindings for the
# symbols true and false, so that they can be used as variables in expressions to be evaluated.
extend @,
setupEnvironment: ->
initialEnv = extendEnvironment(
primitiveProcedureNames,
primitiveProcedureObjects,
TheEmptyEnvironment
)
defineVariable 'true', true, initialEnv
defineVariable 'false', false, initialEnv
defineVariable 'null', null, initialEnv
defineVariable 'nil', null, initialEnv
# define ad-hoc map in the global environment
execute("
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
", initialEnv)
initialEnv
# It does not matter how we represent the primitive procedure objects, so long as apply can identify and apply them by using
# the procedures primitive-procedure? and apply-primitive-procedure. We have chosen to represent a primitive procedure as a list
# beginning with the symbol primitive and containing a procedure in the underlying Lisp that implements that primitive.
# ad-hoc mapping on Coffee level
@map = (proc, items) ->
return null if items is null
cons(proc(car(items)), map(proc, cdr(items)))
extend @,
isPrimitiveProcedure: (proc) ->
isTaggedList proc, 'primitive'
primitiveImplementation: (proc) ->
cadr proc
primitiveProcedures: list(
# lists
list('car', car),
list('cdr', cdr),
list('cons', cons),
list('list', list),
list('list-ref', (l, i) -> l[i]),
list('length', (items) -> items.length),
list('append', (x, y) -> JSArray2LispList(x.concat(y))),
list('reverse', (x) -> JSArray2LispList(x.reverse())),
# predicates
list('true?', isTrue),
list('false?', isFalse),
list('pair?', isPair),
list('null?', (x) -> x is null),
# relational
list('=', eq),
list('eq', eq),
list('>', (x, y) -> x > y),
list('>=', (x, y) -> x >= y),
list('<', (x, y) -> x < y),
list('<=', (x, y) -> x <= y),
# some math
list('+', (args...) -> args.reduce (a, b) -> a + b),
list('*', (args...) -> args.reduce (a, b) -> a * b),
list('min', (args...) -> Math.min.apply Math, args),
list('max', (args...) -> Math.max.apply Math, args),
list('abs', (x) -> if x > 0 then x else -x),
list('-', (args...) ->
return -args[0] if args.length is 1
args.reduce (a, b) -> a - b
),
list('/', (args...) ->
return 1/args[0] if args.length is 1
args.reduce (a, b) -> a / b
)
)
@primitiveProcedureNames = map car, primitiveProcedures
@primitiveProcedureObjects = map ((proc) -> list 'primitive', cadr(proc)), primitiveProcedures
extend @,
# To apply a primitive procedure, we simply apply the implementation procedure to the arguments, using the
# underlying Lisp system:
applyPrimitiveProcedure: (proc, args) ->
applyProc = primitiveImplementation(proc)
if applyProc is car or applyProc is cdr
applyArgs = args
else if applyProc is cons
applyArgs = cons(car(args), cadr(args))
else
applyArgs = LispList2JSArray(args)
primitiveImplementation(proc) applyArgs...
# For convenience in running the metacircular evaluator, we provide a driver loop that models the read-eval-print loop of the
# underlying Lisp system. It prints a prompt, reads an input expression, evaluates this expression in the global environment,
# and prints the result. We precede each printed result by an output prompt so as to distinguish the value of the expression
# from other output that may be printed.
inputPrompt: ";;; Coffee-Lisp-Eval input:"
outputPrompt: ";;; Coffee-Lisp-Eval value:"
driverLoop: (input) ->
return 'no input' if not input
# promptForInput inputPrompt
output = LispMachine.eval(parse(input), TheGlobalEnvironment)
# announceOutput outputPrompt
userPrint output
output
execute: (input, env) ->
return 'no input' if not input
expressions = parse(input)
output = null
env ?= TheGlobalEnvironment
expressions.forEach (exp) ->
output = LispMachine.eval exp, env
if output and car(output) is "procedure"
return if isVariable(input) then "<#procedure \"#{input}\">" else "<#anonymous procedure>"
if isPair(output)
return if isPair(cdr(output)) then "(#{LispList2JSArray(output).join(' ')})" else "(#{output.join(' . ')})"
output
promptForInput: (string) ->
console.log string
announceOutput: (string) ->
console.log string
# We use a special printing procedure, user-print, to avoid printing the environment part of a compound procedure, which may
# be a very long list (or may even contain cycles).
userPrint: (object) ->
if isCompoundProcedure object
return console.log list('compound-procedure', procedureParameters(object), procedureBody(object), '<procedure-env>')
console.log object
## -----------------------------------------------------
## 4.1.7 Separating Syntactic Analysis from Execution
## -----------------------------------------------------
# The evaluator implemented above is simple, but it is very inefficient, because the syntactic analysis
# of expressions is interleaved with their execution. Thus if a program is executed many times, its syntax
# is analyzed many times. Consider, for example, evaluating (factorial 4) using the following definition of factorial:
#
# (define (factorial n)
# (if (= n 1)
# 1
# (* (factorial (- n 1)) n)))
#
# Each time factorial is called, the evaluator must determine that the body is an if expression and
# extract the predicate. Only then can it evaluate the predicate and dispatch on its value. Each time
# it evaluates the expression (* (factorial (- n 1)) n), or the subexpressions (factorial (- n 1)) and (- n 1),
# the evaluator must perform the case analysis in eval to determine that the expression is an application,
# and must extract its operator and operands. This analysis is expensive. Performing it repeatedly is wasteful.
#
# We can transform the evaluator to be significantly more efficient by arranging things so that syntactic
# analysis is performed only once.28 We split `eval`, which takes an expression and an environment, into two parts.
# The procedure `analyze` takes only the `expression`. It performs the syntactic analysis and returns a new procedure,
# the execution procedure, that encapsulates the work to be done in executing the analyzed expression. The execution
# procedure takes an environment as its argument and completes the evaluation. This saves work because analyze will be
# called only once on an expression, while the execution procedure may be called many times.
#
# With the separation into analysis and execution, eval now becomes
# DS: Save old (unoptimized `eval`)
@LispMachine.interpretationalEval = @LispMachine.eval
@LispMachine.eval = (exp, env) ->
# parse all needed data
executionProcedure = analyze(exp)
#console.log "executionProcedure #{executionProcedure}"
# and complete the execution
executionProcedure env
extend @,
# The result of calling analyze is the execution procedure to be applied to the environment. The analyze procedure
# is the same case analysis as performed by the original eval of section 4.1.1, except that the procedures to which we
# dispatch perform only analysis, not full evaluation:
analyze: (exp) ->
return analyzeSelfEvaluating exp if isSelfEvaluating exp
return analyzeQuoted exp if isQuoted exp
return analyzeVariable exp if isVariable exp
return analyzeAssignment exp if isAssignment exp
return analyzeDefinition exp if isDefinition exp
return analyzeIf exp if isIf exp
return analyzeLambda exp if isLambda exp
if isLet exp
return analyzeLet(analyzeLambda(letToLambda(exp)), exp)
return analyzeSequence(beginActions(exp)) if isBegin exp
return analyze(condToIf(exp)) if isCond exp
return analyzeApplication exp if isApplication exp
throw "Unknown expression type -- ANALYZE #{exp}"
# Here is the simplest syntactic analysis procedure, which handles self-evaluating expressions. It returns an execution
# procedure that ignores its environment argument and just returns the expression:
analyzeSelfEvaluating: (exp) ->
(env) -> exp
# For a quoted expression, we can gain a little efficiency by extracting the text of the quotation only once, in the
# analysis phase, rather than in the execution phase.
analyzeQuoted: (exp) ->
quotedValue = textOfQuotation exp
(env) -> quotedValue
# Looking up a variable value must still be done in the execution phase, since this depends upon knowing the environment.
analyzeVariable: (exp) ->
(env) -> lookupVariableValue exp, env
# `analyzeAssignment` also must defer actually setting the variable until the execution, when the environment has been supplied.
# However, the fact that the `assignmentValue` expression can be analyzed (recursively) during analysis is a major gain in
# efficiency, because the assignment-value expression will now be analyzed only once. The same holds true for definitions.
analyzeAssignment: (exp) ->
variable = assignmentVariable exp
valueProc = analyze(assignmentValue(exp))
(env) ->
setVariableValue(
variable,
valueProc(env),
env
)
"ok"
analyzeDefinition: (exp) ->
variable = definitionVariable exp
valueProc = analyze(definitionValue(exp))
(env) ->
defineVariable(
variable,
valueProc(env),
env
)
"ok"
# For if expressions, we extract and analyze the predicate, consequent, and alternative at analysis time.
analyzeIf: (exp) ->
predicateProc = analyze(ifPredicate(exp))
consequentProc = analyze(ifConsequent(exp))
alternativeProc = analyze(ifAlternative(exp))
(env) ->
return consequentProc env if predicateProc(env) is true
alternativeProc env
# Analyzing a lambda expression also achieves a major gain in efficiency: We analyze the lambda body only once,
# even though procedures resulting from evaluation of the lambda may be applied many times.
analyzeLambda: (exp) ->
vars = lambdaParameters exp
bodyProc = analyzeSequence(lambdaBody(exp))
(env) -> makeProcedure(vars, bodyProc, env)
# Analysis of a sequence of expressions (as in a begin or the body of a lambda expression) is more involved.
# Each expression in the sequence is analyzed, yielding an execution procedure. These execution procedures
# are combined to produce an execution procedure that takes an environment as argument and sequentially calls
# each individual execution procedure with the environment as argument.
analyzeSequence: (exps) ->
sequentially = (proc1, proc2) ->
(env) ->
proc1 env
proc2 env
sequenceLoop = (firstProc, restProcs) ->
return firstProc if restProcs is null
sequenceLoop(sequentially(firstProc, car(restProcs)), cdr(restProcs))
procs = map(analyze, exps)
throw "Empty sequence -- ANALYZE" if procs is null
sequenceLoop(car(procs), cdr(procs))
# To analyze an application, we analyze the operator and operands and construct an execution procedure that
# calls the operator execution procedure (to obtain the actual procedure to be applied) and the operand execution
# procedures (to obtain the actual arguments). We then pass these to execute-application, which is the analog of
# apply in section 4.1.1. Execute-application differs from apply in that the procedure body for a compound procedure
# has already been analyzed, so there is no need to do further analysis. Instead, we just call the execution procedure
# for the body on the extended environment.
analyzeApplication: (exp) ->
getOperatorProc = analyze(operator(exp))
operandProcs = map(analyze, operands(exp))
(env) ->
executeApplication(
getOperatorProc(env), # operator proc
map(((operandProc) -> operandProc(env)), operandProcs) # args
)
executeApplication: (proc, args) ->
if isPrimitiveProcedure proc
return applyPrimitiveProcedure(proc, args)
if isCompoundProcedure proc
code = procedureBody(proc)
return code(extendEnvironment(procedureParameters(proc), args, procedureEnvironment(proc)))
throw "Unknown procedure type -- EXECUTE-APPLICATION #{proc}"
# Our new evaluator uses the same data structures, syntax procedures, and run-time support
# procedures as in sections 4.1.2, 4.1.3, and 4.1.4.
analyzeLet: (lambda, exp) ->
(env) ->
executeApplication(
lambda(env),
letVals = letValues(exp, env)
)
# Now all we need to do to run the evaluator is to initialize the global environment and start the driver loop.
# Here is a sample interaction:
@TheGlobalEnvironment = setupEnvironment()
# debug aliases
@global = TheGlobalEnvironment
@empty = TheEmptyEnvironment
@G = TheGlobalEnvironment
@E = TheEmptyEnvironment |
[
{
"context": "odeURIComponent(longUrl)}&appid=801399639&openkey=898eab772e8dbd603f03c4db1963de93\"\n xmlhttp.open('GET', url, false)\n xmlhttp.onre",
"end": 2534,
"score": 0.9997406601905823,
"start": 2502,
"tag": "KEY",
"value": "898eab772e8dbd603f03c4db1963de93"
},
{
"context": "... | src/extension/background/tools.coffee | roceys/cm | 248 | ###
# QR码、短网址、快递工具
###
queryKd = (num, tab, back, incognito)->
### 根据快递单号查找快递信息 ###
xmlhttp = new XMLHttpRequest()
xmlhttp.open('GET',
"http://www.kuaidi100.com/autonumber/auto?num=#{num}", true)
xmlhttp.setRequestHeader('Content-Type', 'application/json')
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
for r in response
show("http://www.kuaidi100.com/chaxun?com=#{r.comCode}&nu=%s",
num, tab, back, incognito)
xmlhttp.send()
1
copy2Clipboard = (str)->
### 复制到剪贴板 ###
input = document.getElementById('url')
if input == undefined
return
input.value = str
input.select()
document.execCommand('copy', false, null)
readClipboard = ->
### 读取剪贴板 ###
input = document.getElementById('url')
if input == undefined
return
input.select()
document.execCommand('paste')
input.value
createUrl = ->
### 创建url对象 ###
input = document.createElement('input')
input.type = 'text'
input.id = 'url'
document.body.appendChild(input)
createUrl()
createQR = (value, tab, back, incognito)->
### 生成QR码 ###
size = JU.lsGet('qr_size', 250)
show("http://qr.liantu.com/api.php?w=#{size}&text=%s",
value, tab, back, incognito)
qrcode.callback = (str)->
### QR码解析回调函数 ###
if /\w{3,}:\/\/*/.test(str)
chrome.tabs.create(url: str)
else
alert(str)
copyResponse = (response)->
### 复制剪贴板回调函数 ###
if response.status == 'error'
alert('response error')
else
copy2Clipboard(response.message)
alertResponse = (response)->
### 弹出回调函数 ###
if response.status == 'error'
alert('response error')
else
alert(response.message)
shortenUrlCopy = (url, tab, back, incognito)->
### 短网址复制剪贴板 ###
shortenUrl(url, false, copyResponse)
shortenUrlAlert = (url, tab, back, incognito)->
### 短网址弹出 ###
shortenUrl(url, false, alertResponse)
shortenUrl = (longUrl, incognito, callback)->
### 生成短网址 ###
name = JU.lsGet('shorten', 'googl')
switch name
when 'dwz' then dwz(longUrl, incognito, callback)
when 'sinat' then sinat(longUrl, incognito, callback)
when 'urlcn' then urlcn(longUrl, incognito, callback)
else googl(longUrl, incognito, callback)
ga('send', 'event', 'shorten', name)
urlcn = (longUrl, incognito, callback)->
### 腾讯短网址 ###
xmlhttp = new XMLHttpRequest()
url = "http://open.t.qq.com/api/short_url/shorten?format=json&long_url=#{encodeURIComponent(longUrl)}&appid=801399639&openkey=898eab772e8dbd603f03c4db1963de93"
xmlhttp.open('GET', url, false)
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.errcode == 102
alert response.msg
else
callback(
status: 'success'
message: "http://url.cn/#{response['data']['short_url']}"
)
xmlhttp.send()
sinat = (longUrl, incognito, callback)->
### 新浪短网址 ###
xmlhttp = new XMLHttpRequest()
url = "http://api.t.sina.com.cn/short_url/shorten.json?source=1144650722&url_long=#{encodeURIComponent(longUrl)}"
xmlhttp.open('GET', url, false)
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.error_code == 500
alert response.error
else
callback(
status: 'success'
message: response[0]['url_short']
)
xmlhttp.send()
dwz = (longUrl, incognito, callback)->
### 百度短网址 ###
xmlhttp = new XMLHttpRequest()
xmlhttp.open('POST',
'http://dwz.cn/create.php', true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
callback(
status: 'success'
message: response.tinyurl
)
xmlhttp.send("url=#{encodeURIComponent(longUrl)}")
googl = (longUrl, incognito, callback)->
### Google 短网址 ###
auth = getOauth().hasToken() and !incognito
xmlhttp = new XMLHttpRequest()
xmlhttp.open('POST',"#{URL}?key=#{KEY}", true)
xmlhttp.setRequestHeader('Content-Type', 'application/json')
if auth
xmlhttp.setRequestHeader('Authorization',
oauth.getAuthorizationHeader(URL, 'POST', {'key': KEY}))
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.id == undefined
if response.error.code == '401'
oauth.clearTokens()
callback({status: 'error', message: response.error.message})
else
callback(
status: 'success'
message: response.id
added_to_history: auth
)
xmlhttp.send(JSON.stringify('longUrl': longUrl))
KEY = 'AIzaSyAfKgyjoxWmR4RJyRhmk0X-J7q2WB9TbGA'
TIMER = null
URL = 'https://www.googleapis.com/urlshortener/v1/url'
getOauth = ->
### 获取oauth对象 ###
if !window.OAUTH
window.OAUTH = ChromeExOAuth.initBackgroundPage(
'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken'
'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken'
'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken'
'consumer_key' : '293074347131.apps.googleusercontent.com'
'consumer_secret' : '2AtwN_96VFpevnorbSWK8czI'
'scope' : 'https://www.googleapis.com/auth/urlshortener'
'app_name' : 'Right search menu'
)
window.OAUTH
tabClose = (value, tab, back, incognito)->
### 关闭标签页 ###
chrome.tabs.remove(tab.id)
| 56767 | ###
# QR码、短网址、快递工具
###
queryKd = (num, tab, back, incognito)->
### 根据快递单号查找快递信息 ###
xmlhttp = new XMLHttpRequest()
xmlhttp.open('GET',
"http://www.kuaidi100.com/autonumber/auto?num=#{num}", true)
xmlhttp.setRequestHeader('Content-Type', 'application/json')
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
for r in response
show("http://www.kuaidi100.com/chaxun?com=#{r.comCode}&nu=%s",
num, tab, back, incognito)
xmlhttp.send()
1
copy2Clipboard = (str)->
### 复制到剪贴板 ###
input = document.getElementById('url')
if input == undefined
return
input.value = str
input.select()
document.execCommand('copy', false, null)
readClipboard = ->
### 读取剪贴板 ###
input = document.getElementById('url')
if input == undefined
return
input.select()
document.execCommand('paste')
input.value
createUrl = ->
### 创建url对象 ###
input = document.createElement('input')
input.type = 'text'
input.id = 'url'
document.body.appendChild(input)
createUrl()
createQR = (value, tab, back, incognito)->
### 生成QR码 ###
size = JU.lsGet('qr_size', 250)
show("http://qr.liantu.com/api.php?w=#{size}&text=%s",
value, tab, back, incognito)
qrcode.callback = (str)->
### QR码解析回调函数 ###
if /\w{3,}:\/\/*/.test(str)
chrome.tabs.create(url: str)
else
alert(str)
copyResponse = (response)->
### 复制剪贴板回调函数 ###
if response.status == 'error'
alert('response error')
else
copy2Clipboard(response.message)
alertResponse = (response)->
### 弹出回调函数 ###
if response.status == 'error'
alert('response error')
else
alert(response.message)
shortenUrlCopy = (url, tab, back, incognito)->
### 短网址复制剪贴板 ###
shortenUrl(url, false, copyResponse)
shortenUrlAlert = (url, tab, back, incognito)->
### 短网址弹出 ###
shortenUrl(url, false, alertResponse)
shortenUrl = (longUrl, incognito, callback)->
### 生成短网址 ###
name = JU.lsGet('shorten', 'googl')
switch name
when 'dwz' then dwz(longUrl, incognito, callback)
when 'sinat' then sinat(longUrl, incognito, callback)
when 'urlcn' then urlcn(longUrl, incognito, callback)
else googl(longUrl, incognito, callback)
ga('send', 'event', 'shorten', name)
urlcn = (longUrl, incognito, callback)->
### 腾讯短网址 ###
xmlhttp = new XMLHttpRequest()
url = "http://open.t.qq.com/api/short_url/shorten?format=json&long_url=#{encodeURIComponent(longUrl)}&appid=801399639&openkey=<KEY>"
xmlhttp.open('GET', url, false)
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.errcode == 102
alert response.msg
else
callback(
status: 'success'
message: "http://url.cn/#{response['data']['short_url']}"
)
xmlhttp.send()
sinat = (longUrl, incognito, callback)->
### 新浪短网址 ###
xmlhttp = new XMLHttpRequest()
url = "http://api.t.sina.com.cn/short_url/shorten.json?source=1144650722&url_long=#{encodeURIComponent(longUrl)}"
xmlhttp.open('GET', url, false)
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.error_code == 500
alert response.error
else
callback(
status: 'success'
message: response[0]['url_short']
)
xmlhttp.send()
dwz = (longUrl, incognito, callback)->
### 百度短网址 ###
xmlhttp = new XMLHttpRequest()
xmlhttp.open('POST',
'http://dwz.cn/create.php', true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
callback(
status: 'success'
message: response.tinyurl
)
xmlhttp.send("url=#{encodeURIComponent(longUrl)}")
googl = (longUrl, incognito, callback)->
### Google 短网址 ###
auth = getOauth().hasToken() and !incognito
xmlhttp = new XMLHttpRequest()
xmlhttp.open('POST',"#{URL}?key=#{KEY}", true)
xmlhttp.setRequestHeader('Content-Type', 'application/json')
if auth
xmlhttp.setRequestHeader('Authorization',
oauth.getAuthorizationHeader(URL, 'POST', {'key': KEY}))
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.id == undefined
if response.error.code == '401'
oauth.clearTokens()
callback({status: 'error', message: response.error.message})
else
callback(
status: 'success'
message: response.id
added_to_history: auth
)
xmlhttp.send(JSON.stringify('longUrl': longUrl))
KEY = '<KEY>'
TIMER = null
URL = 'https://www.googleapis.com/urlshortener/v1/url'
getOauth = ->
### 获取oauth对象 ###
if !window.OAUTH
window.OAUTH = ChromeExOAuth.initBackgroundPage(
'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken'
'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken'
'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken'
'consumer_key' : '<KEY>'
'consumer_secret' : '<KEY>'
'scope' : 'https://www.googleapis.com/auth/urlshortener'
'app_name' : 'Right search menu'
)
window.OAUTH
tabClose = (value, tab, back, incognito)->
### 关闭标签页 ###
chrome.tabs.remove(tab.id)
| true | ###
# QR码、短网址、快递工具
###
queryKd = (num, tab, back, incognito)->
### 根据快递单号查找快递信息 ###
xmlhttp = new XMLHttpRequest()
xmlhttp.open('GET',
"http://www.kuaidi100.com/autonumber/auto?num=#{num}", true)
xmlhttp.setRequestHeader('Content-Type', 'application/json')
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
for r in response
show("http://www.kuaidi100.com/chaxun?com=#{r.comCode}&nu=%s",
num, tab, back, incognito)
xmlhttp.send()
1
copy2Clipboard = (str)->
### 复制到剪贴板 ###
input = document.getElementById('url')
if input == undefined
return
input.value = str
input.select()
document.execCommand('copy', false, null)
readClipboard = ->
### 读取剪贴板 ###
input = document.getElementById('url')
if input == undefined
return
input.select()
document.execCommand('paste')
input.value
createUrl = ->
### 创建url对象 ###
input = document.createElement('input')
input.type = 'text'
input.id = 'url'
document.body.appendChild(input)
createUrl()
createQR = (value, tab, back, incognito)->
### 生成QR码 ###
size = JU.lsGet('qr_size', 250)
show("http://qr.liantu.com/api.php?w=#{size}&text=%s",
value, tab, back, incognito)
qrcode.callback = (str)->
### QR码解析回调函数 ###
if /\w{3,}:\/\/*/.test(str)
chrome.tabs.create(url: str)
else
alert(str)
copyResponse = (response)->
### 复制剪贴板回调函数 ###
if response.status == 'error'
alert('response error')
else
copy2Clipboard(response.message)
alertResponse = (response)->
### 弹出回调函数 ###
if response.status == 'error'
alert('response error')
else
alert(response.message)
shortenUrlCopy = (url, tab, back, incognito)->
### 短网址复制剪贴板 ###
shortenUrl(url, false, copyResponse)
shortenUrlAlert = (url, tab, back, incognito)->
### 短网址弹出 ###
shortenUrl(url, false, alertResponse)
shortenUrl = (longUrl, incognito, callback)->
### 生成短网址 ###
name = JU.lsGet('shorten', 'googl')
switch name
when 'dwz' then dwz(longUrl, incognito, callback)
when 'sinat' then sinat(longUrl, incognito, callback)
when 'urlcn' then urlcn(longUrl, incognito, callback)
else googl(longUrl, incognito, callback)
ga('send', 'event', 'shorten', name)
urlcn = (longUrl, incognito, callback)->
### 腾讯短网址 ###
xmlhttp = new XMLHttpRequest()
url = "http://open.t.qq.com/api/short_url/shorten?format=json&long_url=#{encodeURIComponent(longUrl)}&appid=801399639&openkey=PI:KEY:<KEY>END_PI"
xmlhttp.open('GET', url, false)
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.errcode == 102
alert response.msg
else
callback(
status: 'success'
message: "http://url.cn/#{response['data']['short_url']}"
)
xmlhttp.send()
sinat = (longUrl, incognito, callback)->
### 新浪短网址 ###
xmlhttp = new XMLHttpRequest()
url = "http://api.t.sina.com.cn/short_url/shorten.json?source=1144650722&url_long=#{encodeURIComponent(longUrl)}"
xmlhttp.open('GET', url, false)
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.error_code == 500
alert response.error
else
callback(
status: 'success'
message: response[0]['url_short']
)
xmlhttp.send()
dwz = (longUrl, incognito, callback)->
### 百度短网址 ###
xmlhttp = new XMLHttpRequest()
xmlhttp.open('POST',
'http://dwz.cn/create.php', true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
callback(
status: 'success'
message: response.tinyurl
)
xmlhttp.send("url=#{encodeURIComponent(longUrl)}")
googl = (longUrl, incognito, callback)->
### Google 短网址 ###
auth = getOauth().hasToken() and !incognito
xmlhttp = new XMLHttpRequest()
xmlhttp.open('POST',"#{URL}?key=#{KEY}", true)
xmlhttp.setRequestHeader('Content-Type', 'application/json')
if auth
xmlhttp.setRequestHeader('Authorization',
oauth.getAuthorizationHeader(URL, 'POST', {'key': KEY}))
xmlhttp.onreadystatechange = ->
if xmlhttp.readyState == 4 and xmlhttp.status != 0
response = JSON.parse(xmlhttp.responseText)
if response.id == undefined
if response.error.code == '401'
oauth.clearTokens()
callback({status: 'error', message: response.error.message})
else
callback(
status: 'success'
message: response.id
added_to_history: auth
)
xmlhttp.send(JSON.stringify('longUrl': longUrl))
KEY = 'PI:KEY:<KEY>END_PI'
TIMER = null
URL = 'https://www.googleapis.com/urlshortener/v1/url'
getOauth = ->
### 获取oauth对象 ###
if !window.OAUTH
window.OAUTH = ChromeExOAuth.initBackgroundPage(
'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken'
'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken'
'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken'
'consumer_key' : 'PI:KEY:<KEY>END_PI'
'consumer_secret' : 'PI:KEY:<KEY>END_PI'
'scope' : 'https://www.googleapis.com/auth/urlshortener'
'app_name' : 'Right search menu'
)
window.OAUTH
tabClose = (value, tab, back, incognito)->
### 关闭标签页 ###
chrome.tabs.remove(tab.id)
|
[
{
"context": "e in unpatched `loupe.js`, see https://github.com/chaijs/loupe/issues/40 ###\n [ [ 1, 'XXXX', ], fals",
"end": 2189,
"score": 0.9993081092834473,
"start": 2183,
"tag": "USERNAME",
"value": "chaijs"
},
{
"context": "llobject', ]\n [ ( { constructor:... | dev/intertype/src/es6classes.test.coffee | loveencounterflow/hengist | 0 |
'use strict'
############################################################################################################
# njs_util = require 'util'
njs_path = require 'path'
# njs_fs = require 'fs'
#...........................................................................................................
CND = require 'cnd'
rpr = CND.rpr.bind CND
badge = 'INTERTYPE/tests/es6classes'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
praise = CND.get_logger 'praise', badge
echo = CND.echo.bind CND
#...........................................................................................................
test = require 'guy-test'
#-----------------------------------------------------------------------------------------------------------
@[ "undeclared types cause correct error (loupe breakage fix)" ] = ( T, done ) ->
#.........................................................................................................
INTERTYPE = require '../../../apps/intertype'
{ Intertype, } = INTERTYPE
intertype = new Intertype()
{ isa
validate
type_of
types_of
size_of
declare
all_keys_of } = intertype.export()
#.........................................................................................................
probes_and_matchers = [
[ [ true, 'XXXX', ], false, "not a valid XXXX", ]
[ [ 1n, 'XXXX', ], false, "not a valid XXXX", ]
[ [ 1n, 'bigint', ], true, null, ] ### NOTE `1n` used to cause breakage in unpatched `loupe.js`, see https://github.com/chaijs/loupe/issues/40 ###
[ [ 1, 'XXXX', ], false, "not a valid XXXX", ]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
[ value, type, ] = probe
result = isa[ type ] value
validate[ type ] value
T.ok true
resolve result
done()
return null
# #-----------------------------------------------------------------------------------------------------------
# @[ "undeclared types cause correct error (loupe breakage fix) XXX" ] = ( T, done ) ->
# #.........................................................................................................
# INTERTYPE = require '../../../apps/intertype'
# { Intertype, } = INTERTYPE
# intertype = new Intertype()
# { isa
# validate
# type_of
# types_of
# size_of
# declare
# all_keys_of } = intertype.export()
# #.........................................................................................................
# probes_and_matchers = [
# [ [ 1n, 'bigint', ], true, null, ]
# [ [ 1n, 'XXXX', ], false, "not a valid XXXX", ]
# ]
# #.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# [ value, type, ] = probe
# result = isa[ type ] value
# validate[ type ] value
# # T.ok true
# # resolve result
# # done()
# return null
#-----------------------------------------------------------------------------------------------------------
get_probes_and_matchers = ->
#.........................................................................................................
# class Array
class MyBareClass
class MyObjectClass extends Object
class MyArrayClass extends Array
SomeConstructor = ->
OtherConstructor = -> 42
#.........................................................................................................
# thx to https://www.reddit.com/r/javascript/comments/gnbqoy/askjs_is_objectprototypetostringcall_the_best/fra7fg9?utm_source=share&utm_medium=web2x
# toString = Function.prototype.call.bind Object.prototype.toString
FooObject = {}
FooObject[ Symbol.toStringTag ] = 'Foo'
# console.log(toString(FooObject)) // [object Foo]
#.........................................................................................................
probes_and_matchers = [
[ ( Object.create null ), 'nullobject', ]
[ ( { constructor: 'Bob', } ), 'object', ]
[ ( { CONSTRUCTOR: 'Bob', } ), 'object', ]
[ ( MyBareClass ), 'class', ]
[ ( MyObjectClass ), 'class', ]
[ ( MyArrayClass ), 'class', ]
[ ( Array ), 'function', ]
[ ( SomeConstructor ), 'function', ]
[ ( new MyBareClass() ), 'mybareclass', ]
[ ( new MyObjectClass() ), 'myobjectclass', ]
[ ( new MyArrayClass() ), 'myarrayclass', ]
[ ( new SomeConstructor() ), 'someconstructor', ]
[ ( new OtherConstructor() ), 'otherconstructor', ]
[ ( null ), 'null', ]
[ ( undefined ), 'undefined', ]
[ ( Object ), 'function', ]
[ ( Array ), 'function', ]
[ ( {} ), 'object', ]
[ ( [] ), 'list', ]
[ ( '42' ), 'text', ]
[ ( 42 ), 'float', ]
[ ( NaN ), 'nan', ]
[ ( Infinity ), 'infinity', ]
[ ( -> await f() ), 'asyncfunction', ]
[ ( -> yield from await f() ), 'asyncgeneratorfunction', ]
[ ( -> yield 42 ), 'generatorfunction', ]
[ ( ( -> yield 42 )() ), 'generator', ]
[ ( /x/ ), 'regex', ]
[ ( new Date() ), 'date', ]
[ ( Set ), 'function', ]
[ ( new Set() ), 'set', ]
[ ( Symbol ), 'function', ]
[ ( Symbol 'abc' ), 'symbol', ]
[ ( Symbol.for 'abc' ), 'symbol', ]
[ ( new Uint8Array [ 42, ] ), 'uint8array', ]
[ ( Buffer.from [ 42, ] ), 'buffer', ]
[ ( 12345678912345678912345n ), 'bigint', ]
[ ( FooObject ), 'foo', ]
[ ( new Promise ( resolve ) -> ), 'promise', ]
[ ( new Number 42 ), 'wrapper', ]
[ ( new String '42' ), 'wrapper', ]
[ ( new Boolean true ), 'wrapper', ]
[ ( new RegExp 'x*' ), 'regex', ] ### NOTE not functionally different ###
[ ( new Function 'a', 'b', 'return a + b' ), 'function', ] ### NOTE not functionally different ###
[ ( [].keys() ), 'arrayiterator', ]
[ ( ( new Set [] ).keys() ), 'setiterator', ]
[ ( ( new Map [] ).keys() ), 'mapiterator', ]
[ ( new Array() ), 'list', ]
[ ( ( 'x' )[ Symbol.iterator ]() ), 'stringiterator', ]
]
#-----------------------------------------------------------------------------------------------------------
type_of_v3 = ( xP... ) ->
js_type_of = ( x ) -> ( ( Object::toString.call x ).slice 8, -1 ).toLowerCase().replace /\s+/g, ''
### TAINT this should be generalized for all Intertype types that split up / rename a JS type: ###
throw new Error "^7746^ expected 1 argument, got #{arity}" unless xP.length is 1
switch R = js_type_of xP...
when 'uint8array'
R = 'buffer' if Buffer.isBuffer xP...
when 'number'
[ x, ] = xP
unless Number.isFinite x
R = if ( Number.isNaN x ) then 'nan' else 'infinity'
when 'regexp' then R = 'regex'
when 'string' then R = 'text'
when 'array' then R = 'list'
when 'arrayiterator' then R = 'listiterator'
when 'stringiterator' then R = 'textiterator'
### Refuse to answer question in case type found is not in specs: ###
# debug 'µ33332', R, ( k for k of @specs )
# throw new Error "µ6623 unknown type #{rpr R}" unless R of @specs
return R
#-----------------------------------------------------------------------------------------------------------
@[ "es6classes type detection devices (prototype)" ] = ( T, done ) ->
INTERTYPE = require '../../../apps/intertype'
{ Intertype, } = INTERTYPE
intertype = new Intertype()
{ isa
validate } = intertype.export()
type_of_v4 = intertype.export().type_of
js_type_of = ( x ) -> ( ( Object::toString.call x ).slice 8, -1 )
{ domenic_denicola_device, mark_miller_device, } = require '../../../apps/intertype/lib/helpers'
#.........................................................................................................
debug()
column_width = 25
#.........................................................................................................
headers = [
'probe'
'typeof'
# 'toString()'
'string_tag'
'miller'
'type_of_v3'
'denicola'
'type_of_v4'
'expected' ]
headers = ( h[ ... column_width ].padEnd column_width for h in headers ).join '|'
echo headers
#.........................................................................................................
for [ probe, matcher, ] in get_probes_and_matchers()
type_of_v4_type = type_of_v4 probe
string_tag = if probe? then probe[ Symbol.toStringTag ] else './.'
# toString = if probe? then probe.toString?() ? './.' else './.'
raw_results = [
rpr probe
typeof probe
# toString
string_tag
mark_miller_device probe
type_of_v3 probe
domenic_denicola_device probe
type_of_v4_type
matcher ]
results = []
last_idx = raw_results.length - 1
for raw_result, idx in raw_results
if isa.text raw_result
raw_result = raw_result.replace /\n/g, '⏎'
lc_result = raw_result.toLowerCase().replace /\s/g, ''
else
raw_result = ''
lc_result = null
if ( idx in [ 0, last_idx, ] )
color = CND.cyan
else
if raw_result is matcher then color = CND.green
else if lc_result is matcher then color = CND.lime
else color = CND.red
results.push color ( raw_result[ ... column_width ].padEnd column_width )
echo results.join '|'
T.eq type_of_v4_type, matcher
# debug rpr ( ( -> yield 42 )() ).constructor
# debug rpr ( ( -> yield 42 )() ).constructor.name
# debug '^338-10^', mmd MyBareClass # Function
# debug '^338-11^', mmd MyObjectClass # Function
# debug '^338-12^', mmd MyArrayClass # Function
# debug '^338-13^', mmd new MyBareClass() # Object
# debug '^338-14^', mmd new MyObjectClass() # Object
# debug '^338-15^', mmd new MyArrayClass() # Array
# debug() #
# debug '^338-16^', ddd MyBareClass # Function
# debug '^338-17^', ddd MyObjectClass # Function
# debug '^338-18^', ddd MyArrayClass # Function
# debug '^338-19^', ddd new MyBareClass() # MyBareClass
# debug '^338-20^', ddd new MyObjectClass() # MyObjectClass
# debug '^338-21^', ddd new MyArrayClass() # MyArrayClass
done()
#-----------------------------------------------------------------------------------------------------------
@[ "_es6classes equals" ] = ( T, done ) ->
intertype = new Intertype()
{ isa
check
equals } = intertype.export()
### TAINT copy more extensive tests from CND, `js_eq`? ###
T.eq ( equals 3, 3 ), true
T.eq ( equals 3, 4 ), false
done() if done?
#-----------------------------------------------------------------------------------------------------------
demo_test_for_generator = ->
GeneratorFunction = ( -> yield 42 ).constructor
Generator = ( ( -> yield 42 )() ).constructor
debug rpr GeneratorFunction.name == 'GeneratorFunction'
debug rpr Generator.name == ''
debug ( -> yield 42 ).constructor is GeneratorFunction
debug ( -> yield 42 ).constructor is Generator
debug ( ( -> yield 42 )() ).constructor is GeneratorFunction
debug ( ( -> yield 42 )() ).constructor is Generator
#-----------------------------------------------------------------------------------------------------------
demo = ->
# ```
# echo( 'helo' );
# echo( rpr(
# ( function*() { yield 42; } ).constructor.name
# ) );
# echo( rpr(
# ( function*() { yield 42; } )().constructor.name
# ) );
# ```
# node -p "require('util').inspect( ( function*() { yield 42; } ).constructor )"
# node -p "require('util').inspect( ( function*() { yield 42; } ).constructor.name )"
# node -p "require('util').inspect( ( function*() { yield 42; } )().constructor )"
# node -p "require('util').inspect( ( function*() { yield 42; } )().constructor.name )"
info rpr ( -> yield 42; ).constructor
info rpr ( -> yield 42; ).constructor.name
info rpr ( -> yield 42; )().constructor
info rpr ( -> yield 42; )().constructor.name
# info rpr NaN.constructor.name
info arrayiterator = [].keys().constructor
info setiterator = ( new Set [] ).keys().constructor
info mapiterator = ( new Map [] ).keys().constructor
info stringiterator = ( 'x' )[ Symbol.iterator ]().constructor
types = new Intertype()
# debug types.all_keys_of Buffer.alloc 10
# debug types.all_keys_of new Uint8Array 10
# class X extends NaN
# class X extends null
# class X extends undefined
# class X extends 1
# class X extends {}
myfunction = ->
class X
class O extends Object
info '^87-1^', rpr ( myfunction:: )
info '^87-2^', rpr ( myfunction:: ).constructor
info '^87-3^', rpr ( myfunction:: ).constructor.name
info '^87-4^', rpr ( X:: )
info '^87-5^', rpr ( X:: ).constructor
info '^87-6^', rpr ( X:: ).constructor.name
info '^87-7^', rpr ( O:: )
info '^87-8^', rpr ( O:: ).constructor
info '^87-9^', rpr ( O:: ).constructor.name
info Object.hasOwnProperty X, 'arguments'
info Object.hasOwnProperty ( -> ), 'arguments'
info Object.hasOwnProperty ( ( x ) -> ), 'arguments'
info Object.hasOwnProperty ( ( -> ):: ), 'arguments'
info Object.hasOwnProperty ( ( ( x ) -> ):: ), 'arguments'
urge Object.getOwnPropertyNames X
urge Object.getOwnPropertyNames ( -> )
info new Array()
############################################################################################################
if module is require.main then do =>
# demo_test_for_generator()
test @
# test @[ "undeclared types cause correct error (loupe breakage fix)" ]
# @[ "undeclared types cause correct error (loupe breakage fix)" ]()
# test @[ "undeclared but implement types can be used" ]
| 46966 |
'use strict'
############################################################################################################
# njs_util = require 'util'
njs_path = require 'path'
# njs_fs = require 'fs'
#...........................................................................................................
CND = require 'cnd'
rpr = CND.rpr.bind CND
badge = 'INTERTYPE/tests/es6classes'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
praise = CND.get_logger 'praise', badge
echo = CND.echo.bind CND
#...........................................................................................................
test = require 'guy-test'
#-----------------------------------------------------------------------------------------------------------
@[ "undeclared types cause correct error (loupe breakage fix)" ] = ( T, done ) ->
#.........................................................................................................
INTERTYPE = require '../../../apps/intertype'
{ Intertype, } = INTERTYPE
intertype = new Intertype()
{ isa
validate
type_of
types_of
size_of
declare
all_keys_of } = intertype.export()
#.........................................................................................................
probes_and_matchers = [
[ [ true, 'XXXX', ], false, "not a valid XXXX", ]
[ [ 1n, 'XXXX', ], false, "not a valid XXXX", ]
[ [ 1n, 'bigint', ], true, null, ] ### NOTE `1n` used to cause breakage in unpatched `loupe.js`, see https://github.com/chaijs/loupe/issues/40 ###
[ [ 1, 'XXXX', ], false, "not a valid XXXX", ]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
[ value, type, ] = probe
result = isa[ type ] value
validate[ type ] value
T.ok true
resolve result
done()
return null
# #-----------------------------------------------------------------------------------------------------------
# @[ "undeclared types cause correct error (loupe breakage fix) XXX" ] = ( T, done ) ->
# #.........................................................................................................
# INTERTYPE = require '../../../apps/intertype'
# { Intertype, } = INTERTYPE
# intertype = new Intertype()
# { isa
# validate
# type_of
# types_of
# size_of
# declare
# all_keys_of } = intertype.export()
# #.........................................................................................................
# probes_and_matchers = [
# [ [ 1n, 'bigint', ], true, null, ]
# [ [ 1n, 'XXXX', ], false, "not a valid XXXX", ]
# ]
# #.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# [ value, type, ] = probe
# result = isa[ type ] value
# validate[ type ] value
# # T.ok true
# # resolve result
# # done()
# return null
#-----------------------------------------------------------------------------------------------------------
get_probes_and_matchers = ->
#.........................................................................................................
# class Array
class MyBareClass
class MyObjectClass extends Object
class MyArrayClass extends Array
SomeConstructor = ->
OtherConstructor = -> 42
#.........................................................................................................
# thx to https://www.reddit.com/r/javascript/comments/gnbqoy/askjs_is_objectprototypetostringcall_the_best/fra7fg9?utm_source=share&utm_medium=web2x
# toString = Function.prototype.call.bind Object.prototype.toString
FooObject = {}
FooObject[ Symbol.toStringTag ] = 'Foo'
# console.log(toString(FooObject)) // [object Foo]
#.........................................................................................................
probes_and_matchers = [
[ ( Object.create null ), 'nullobject', ]
[ ( { constructor: '<NAME>', } ), 'object', ]
[ ( { CONSTRUCTOR: '<NAME>', } ), 'object', ]
[ ( MyBareClass ), 'class', ]
[ ( MyObjectClass ), 'class', ]
[ ( MyArrayClass ), 'class', ]
[ ( Array ), 'function', ]
[ ( SomeConstructor ), 'function', ]
[ ( new MyBareClass() ), 'mybareclass', ]
[ ( new MyObjectClass() ), 'myobjectclass', ]
[ ( new MyArrayClass() ), 'myarrayclass', ]
[ ( new SomeConstructor() ), 'someconstructor', ]
[ ( new OtherConstructor() ), 'otherconstructor', ]
[ ( null ), 'null', ]
[ ( undefined ), 'undefined', ]
[ ( Object ), 'function', ]
[ ( Array ), 'function', ]
[ ( {} ), 'object', ]
[ ( [] ), 'list', ]
[ ( '42' ), 'text', ]
[ ( 42 ), 'float', ]
[ ( NaN ), 'nan', ]
[ ( Infinity ), 'infinity', ]
[ ( -> await f() ), 'asyncfunction', ]
[ ( -> yield from await f() ), 'asyncgeneratorfunction', ]
[ ( -> yield 42 ), 'generatorfunction', ]
[ ( ( -> yield 42 )() ), 'generator', ]
[ ( /x/ ), 'regex', ]
[ ( new Date() ), 'date', ]
[ ( Set ), 'function', ]
[ ( new Set() ), 'set', ]
[ ( Symbol ), 'function', ]
[ ( Symbol 'abc' ), 'symbol', ]
[ ( Symbol.for 'abc' ), 'symbol', ]
[ ( new Uint8Array [ 42, ] ), 'uint8array', ]
[ ( Buffer.from [ 42, ] ), 'buffer', ]
[ ( 12345678912345678912345n ), 'bigint', ]
[ ( FooObject ), 'foo', ]
[ ( new Promise ( resolve ) -> ), 'promise', ]
[ ( new Number 42 ), 'wrapper', ]
[ ( new String '42' ), 'wrapper', ]
[ ( new Boolean true ), 'wrapper', ]
[ ( new RegExp 'x*' ), 'regex', ] ### NOTE not functionally different ###
[ ( new Function 'a', 'b', 'return a + b' ), 'function', ] ### NOTE not functionally different ###
[ ( [].keys() ), 'arrayiterator', ]
[ ( ( new Set [] ).keys() ), 'setiterator', ]
[ ( ( new Map [] ).keys() ), 'mapiterator', ]
[ ( new Array() ), 'list', ]
[ ( ( 'x' )[ Symbol.iterator ]() ), 'stringiterator', ]
]
#-----------------------------------------------------------------------------------------------------------
type_of_v3 = ( xP... ) ->
js_type_of = ( x ) -> ( ( Object::toString.call x ).slice 8, -1 ).toLowerCase().replace /\s+/g, ''
### TAINT this should be generalized for all Intertype types that split up / rename a JS type: ###
throw new Error "^7746^ expected 1 argument, got #{arity}" unless xP.length is 1
switch R = js_type_of xP...
when 'uint8array'
R = 'buffer' if Buffer.isBuffer xP...
when 'number'
[ x, ] = xP
unless Number.isFinite x
R = if ( Number.isNaN x ) then 'nan' else 'infinity'
when 'regexp' then R = 'regex'
when 'string' then R = 'text'
when 'array' then R = 'list'
when 'arrayiterator' then R = 'listiterator'
when 'stringiterator' then R = 'textiterator'
### Refuse to answer question in case type found is not in specs: ###
# debug 'µ33332', R, ( k for k of @specs )
# throw new Error "µ6623 unknown type #{rpr R}" unless R of @specs
return R
#-----------------------------------------------------------------------------------------------------------
@[ "es6classes type detection devices (prototype)" ] = ( T, done ) ->
INTERTYPE = require '../../../apps/intertype'
{ Intertype, } = INTERTYPE
intertype = new Intertype()
{ isa
validate } = intertype.export()
type_of_v4 = intertype.export().type_of
js_type_of = ( x ) -> ( ( Object::toString.call x ).slice 8, -1 )
{ domenic_denicola_device, mark_miller_device, } = require '../../../apps/intertype/lib/helpers'
#.........................................................................................................
debug()
column_width = 25
#.........................................................................................................
headers = [
'probe'
'typeof'
# 'toString()'
'string_tag'
'miller'
'type_of_v3'
'denicola'
'type_of_v4'
'expected' ]
headers = ( h[ ... column_width ].padEnd column_width for h in headers ).join '|'
echo headers
#.........................................................................................................
for [ probe, matcher, ] in get_probes_and_matchers()
type_of_v4_type = type_of_v4 probe
string_tag = if probe? then probe[ Symbol.toStringTag ] else './.'
# toString = if probe? then probe.toString?() ? './.' else './.'
raw_results = [
rpr probe
typeof probe
# toString
string_tag
mark_miller_device probe
type_of_v3 probe
domenic_denicola_device probe
type_of_v4_type
matcher ]
results = []
last_idx = raw_results.length - 1
for raw_result, idx in raw_results
if isa.text raw_result
raw_result = raw_result.replace /\n/g, '⏎'
lc_result = raw_result.toLowerCase().replace /\s/g, ''
else
raw_result = ''
lc_result = null
if ( idx in [ 0, last_idx, ] )
color = CND.cyan
else
if raw_result is matcher then color = CND.green
else if lc_result is matcher then color = CND.lime
else color = CND.red
results.push color ( raw_result[ ... column_width ].padEnd column_width )
echo results.join '|'
T.eq type_of_v4_type, matcher
# debug rpr ( ( -> yield 42 )() ).constructor
# debug rpr ( ( -> yield 42 )() ).constructor.name
# debug '^338-10^', mmd MyBareClass # Function
# debug '^338-11^', mmd MyObjectClass # Function
# debug '^338-12^', mmd MyArrayClass # Function
# debug '^338-13^', mmd new MyBareClass() # Object
# debug '^338-14^', mmd new MyObjectClass() # Object
# debug '^338-15^', mmd new MyArrayClass() # Array
# debug() #
# debug '^338-16^', ddd MyBareClass # Function
# debug '^338-17^', ddd MyObjectClass # Function
# debug '^338-18^', ddd MyArrayClass # Function
# debug '^338-19^', ddd new MyBareClass() # MyBareClass
# debug '^338-20^', ddd new MyObjectClass() # MyObjectClass
# debug '^338-21^', ddd new MyArrayClass() # MyArrayClass
done()
#-----------------------------------------------------------------------------------------------------------
@[ "_es6classes equals" ] = ( T, done ) ->
intertype = new Intertype()
{ isa
check
equals } = intertype.export()
### TAINT copy more extensive tests from CND, `js_eq`? ###
T.eq ( equals 3, 3 ), true
T.eq ( equals 3, 4 ), false
done() if done?
#-----------------------------------------------------------------------------------------------------------
demo_test_for_generator = ->
GeneratorFunction = ( -> yield 42 ).constructor
Generator = ( ( -> yield 42 )() ).constructor
debug rpr GeneratorFunction.name == 'GeneratorFunction'
debug rpr Generator.name == ''
debug ( -> yield 42 ).constructor is GeneratorFunction
debug ( -> yield 42 ).constructor is Generator
debug ( ( -> yield 42 )() ).constructor is GeneratorFunction
debug ( ( -> yield 42 )() ).constructor is Generator
#-----------------------------------------------------------------------------------------------------------
demo = ->
# ```
# echo( 'helo' );
# echo( rpr(
# ( function*() { yield 42; } ).constructor.name
# ) );
# echo( rpr(
# ( function*() { yield 42; } )().constructor.name
# ) );
# ```
# node -p "require('util').inspect( ( function*() { yield 42; } ).constructor )"
# node -p "require('util').inspect( ( function*() { yield 42; } ).constructor.name )"
# node -p "require('util').inspect( ( function*() { yield 42; } )().constructor )"
# node -p "require('util').inspect( ( function*() { yield 42; } )().constructor.name )"
info rpr ( -> yield 42; ).constructor
info rpr ( -> yield 42; ).constructor.name
info rpr ( -> yield 42; )().constructor
info rpr ( -> yield 42; )().constructor.name
# info rpr NaN.constructor.name
info arrayiterator = [].keys().constructor
info setiterator = ( new Set [] ).keys().constructor
info mapiterator = ( new Map [] ).keys().constructor
info stringiterator = ( 'x' )[ Symbol.iterator ]().constructor
types = new Intertype()
# debug types.all_keys_of Buffer.alloc 10
# debug types.all_keys_of new Uint8Array 10
# class X extends NaN
# class X extends null
# class X extends undefined
# class X extends 1
# class X extends {}
myfunction = ->
class X
class O extends Object
info '^87-1^', rpr ( myfunction:: )
info '^87-2^', rpr ( myfunction:: ).constructor
info '^87-3^', rpr ( myfunction:: ).constructor.name
info '^87-4^', rpr ( X:: )
info '^87-5^', rpr ( X:: ).constructor
info '^87-6^', rpr ( X:: ).constructor.name
info '^87-7^', rpr ( O:: )
info '^87-8^', rpr ( O:: ).constructor
info '^87-9^', rpr ( O:: ).constructor.name
info Object.hasOwnProperty X, 'arguments'
info Object.hasOwnProperty ( -> ), 'arguments'
info Object.hasOwnProperty ( ( x ) -> ), 'arguments'
info Object.hasOwnProperty ( ( -> ):: ), 'arguments'
info Object.hasOwnProperty ( ( ( x ) -> ):: ), 'arguments'
urge Object.getOwnPropertyNames X
urge Object.getOwnPropertyNames ( -> )
info new Array()
############################################################################################################
if module is require.main then do =>
# demo_test_for_generator()
test @
# test @[ "undeclared types cause correct error (loupe breakage fix)" ]
# @[ "undeclared types cause correct error (loupe breakage fix)" ]()
# test @[ "undeclared but implement types can be used" ]
| true |
'use strict'
############################################################################################################
# njs_util = require 'util'
njs_path = require 'path'
# njs_fs = require 'fs'
#...........................................................................................................
CND = require 'cnd'
rpr = CND.rpr.bind CND
badge = 'INTERTYPE/tests/es6classes'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
praise = CND.get_logger 'praise', badge
echo = CND.echo.bind CND
#...........................................................................................................
test = require 'guy-test'
#-----------------------------------------------------------------------------------------------------------
@[ "undeclared types cause correct error (loupe breakage fix)" ] = ( T, done ) ->
#.........................................................................................................
INTERTYPE = require '../../../apps/intertype'
{ Intertype, } = INTERTYPE
intertype = new Intertype()
{ isa
validate
type_of
types_of
size_of
declare
all_keys_of } = intertype.export()
#.........................................................................................................
probes_and_matchers = [
[ [ true, 'XXXX', ], false, "not a valid XXXX", ]
[ [ 1n, 'XXXX', ], false, "not a valid XXXX", ]
[ [ 1n, 'bigint', ], true, null, ] ### NOTE `1n` used to cause breakage in unpatched `loupe.js`, see https://github.com/chaijs/loupe/issues/40 ###
[ [ 1, 'XXXX', ], false, "not a valid XXXX", ]
]
#.........................................................................................................
for [ probe, matcher, error, ] in probes_and_matchers
await T.perform probe, matcher, error, -> return new Promise ( resolve, reject ) ->
[ value, type, ] = probe
result = isa[ type ] value
validate[ type ] value
T.ok true
resolve result
done()
return null
# #-----------------------------------------------------------------------------------------------------------
# @[ "undeclared types cause correct error (loupe breakage fix) XXX" ] = ( T, done ) ->
# #.........................................................................................................
# INTERTYPE = require '../../../apps/intertype'
# { Intertype, } = INTERTYPE
# intertype = new Intertype()
# { isa
# validate
# type_of
# types_of
# size_of
# declare
# all_keys_of } = intertype.export()
# #.........................................................................................................
# probes_and_matchers = [
# [ [ 1n, 'bigint', ], true, null, ]
# [ [ 1n, 'XXXX', ], false, "not a valid XXXX", ]
# ]
# #.........................................................................................................
# for [ probe, matcher, error, ] in probes_and_matchers
# [ value, type, ] = probe
# result = isa[ type ] value
# validate[ type ] value
# # T.ok true
# # resolve result
# # done()
# return null
#-----------------------------------------------------------------------------------------------------------
get_probes_and_matchers = ->
#.........................................................................................................
# class Array
class MyBareClass
class MyObjectClass extends Object
class MyArrayClass extends Array
SomeConstructor = ->
OtherConstructor = -> 42
#.........................................................................................................
# thx to https://www.reddit.com/r/javascript/comments/gnbqoy/askjs_is_objectprototypetostringcall_the_best/fra7fg9?utm_source=share&utm_medium=web2x
# toString = Function.prototype.call.bind Object.prototype.toString
FooObject = {}
FooObject[ Symbol.toStringTag ] = 'Foo'
# console.log(toString(FooObject)) // [object Foo]
#.........................................................................................................
probes_and_matchers = [
[ ( Object.create null ), 'nullobject', ]
[ ( { constructor: 'PI:NAME:<NAME>END_PI', } ), 'object', ]
[ ( { CONSTRUCTOR: 'PI:NAME:<NAME>END_PI', } ), 'object', ]
[ ( MyBareClass ), 'class', ]
[ ( MyObjectClass ), 'class', ]
[ ( MyArrayClass ), 'class', ]
[ ( Array ), 'function', ]
[ ( SomeConstructor ), 'function', ]
[ ( new MyBareClass() ), 'mybareclass', ]
[ ( new MyObjectClass() ), 'myobjectclass', ]
[ ( new MyArrayClass() ), 'myarrayclass', ]
[ ( new SomeConstructor() ), 'someconstructor', ]
[ ( new OtherConstructor() ), 'otherconstructor', ]
[ ( null ), 'null', ]
[ ( undefined ), 'undefined', ]
[ ( Object ), 'function', ]
[ ( Array ), 'function', ]
[ ( {} ), 'object', ]
[ ( [] ), 'list', ]
[ ( '42' ), 'text', ]
[ ( 42 ), 'float', ]
[ ( NaN ), 'nan', ]
[ ( Infinity ), 'infinity', ]
[ ( -> await f() ), 'asyncfunction', ]
[ ( -> yield from await f() ), 'asyncgeneratorfunction', ]
[ ( -> yield 42 ), 'generatorfunction', ]
[ ( ( -> yield 42 )() ), 'generator', ]
[ ( /x/ ), 'regex', ]
[ ( new Date() ), 'date', ]
[ ( Set ), 'function', ]
[ ( new Set() ), 'set', ]
[ ( Symbol ), 'function', ]
[ ( Symbol 'abc' ), 'symbol', ]
[ ( Symbol.for 'abc' ), 'symbol', ]
[ ( new Uint8Array [ 42, ] ), 'uint8array', ]
[ ( Buffer.from [ 42, ] ), 'buffer', ]
[ ( 12345678912345678912345n ), 'bigint', ]
[ ( FooObject ), 'foo', ]
[ ( new Promise ( resolve ) -> ), 'promise', ]
[ ( new Number 42 ), 'wrapper', ]
[ ( new String '42' ), 'wrapper', ]
[ ( new Boolean true ), 'wrapper', ]
[ ( new RegExp 'x*' ), 'regex', ] ### NOTE not functionally different ###
[ ( new Function 'a', 'b', 'return a + b' ), 'function', ] ### NOTE not functionally different ###
[ ( [].keys() ), 'arrayiterator', ]
[ ( ( new Set [] ).keys() ), 'setiterator', ]
[ ( ( new Map [] ).keys() ), 'mapiterator', ]
[ ( new Array() ), 'list', ]
[ ( ( 'x' )[ Symbol.iterator ]() ), 'stringiterator', ]
]
#-----------------------------------------------------------------------------------------------------------
type_of_v3 = ( xP... ) ->
js_type_of = ( x ) -> ( ( Object::toString.call x ).slice 8, -1 ).toLowerCase().replace /\s+/g, ''
### TAINT this should be generalized for all Intertype types that split up / rename a JS type: ###
throw new Error "^7746^ expected 1 argument, got #{arity}" unless xP.length is 1
switch R = js_type_of xP...
when 'uint8array'
R = 'buffer' if Buffer.isBuffer xP...
when 'number'
[ x, ] = xP
unless Number.isFinite x
R = if ( Number.isNaN x ) then 'nan' else 'infinity'
when 'regexp' then R = 'regex'
when 'string' then R = 'text'
when 'array' then R = 'list'
when 'arrayiterator' then R = 'listiterator'
when 'stringiterator' then R = 'textiterator'
### Refuse to answer question in case type found is not in specs: ###
# debug 'µ33332', R, ( k for k of @specs )
# throw new Error "µ6623 unknown type #{rpr R}" unless R of @specs
return R
#-----------------------------------------------------------------------------------------------------------
@[ "es6classes type detection devices (prototype)" ] = ( T, done ) ->
INTERTYPE = require '../../../apps/intertype'
{ Intertype, } = INTERTYPE
intertype = new Intertype()
{ isa
validate } = intertype.export()
type_of_v4 = intertype.export().type_of
js_type_of = ( x ) -> ( ( Object::toString.call x ).slice 8, -1 )
{ domenic_denicola_device, mark_miller_device, } = require '../../../apps/intertype/lib/helpers'
#.........................................................................................................
debug()
column_width = 25
#.........................................................................................................
headers = [
'probe'
'typeof'
# 'toString()'
'string_tag'
'miller'
'type_of_v3'
'denicola'
'type_of_v4'
'expected' ]
headers = ( h[ ... column_width ].padEnd column_width for h in headers ).join '|'
echo headers
#.........................................................................................................
for [ probe, matcher, ] in get_probes_and_matchers()
type_of_v4_type = type_of_v4 probe
string_tag = if probe? then probe[ Symbol.toStringTag ] else './.'
# toString = if probe? then probe.toString?() ? './.' else './.'
raw_results = [
rpr probe
typeof probe
# toString
string_tag
mark_miller_device probe
type_of_v3 probe
domenic_denicola_device probe
type_of_v4_type
matcher ]
results = []
last_idx = raw_results.length - 1
for raw_result, idx in raw_results
if isa.text raw_result
raw_result = raw_result.replace /\n/g, '⏎'
lc_result = raw_result.toLowerCase().replace /\s/g, ''
else
raw_result = ''
lc_result = null
if ( idx in [ 0, last_idx, ] )
color = CND.cyan
else
if raw_result is matcher then color = CND.green
else if lc_result is matcher then color = CND.lime
else color = CND.red
results.push color ( raw_result[ ... column_width ].padEnd column_width )
echo results.join '|'
T.eq type_of_v4_type, matcher
# debug rpr ( ( -> yield 42 )() ).constructor
# debug rpr ( ( -> yield 42 )() ).constructor.name
# debug '^338-10^', mmd MyBareClass # Function
# debug '^338-11^', mmd MyObjectClass # Function
# debug '^338-12^', mmd MyArrayClass # Function
# debug '^338-13^', mmd new MyBareClass() # Object
# debug '^338-14^', mmd new MyObjectClass() # Object
# debug '^338-15^', mmd new MyArrayClass() # Array
# debug() #
# debug '^338-16^', ddd MyBareClass # Function
# debug '^338-17^', ddd MyObjectClass # Function
# debug '^338-18^', ddd MyArrayClass # Function
# debug '^338-19^', ddd new MyBareClass() # MyBareClass
# debug '^338-20^', ddd new MyObjectClass() # MyObjectClass
# debug '^338-21^', ddd new MyArrayClass() # MyArrayClass
done()
#-----------------------------------------------------------------------------------------------------------
@[ "_es6classes equals" ] = ( T, done ) ->
intertype = new Intertype()
{ isa
check
equals } = intertype.export()
### TAINT copy more extensive tests from CND, `js_eq`? ###
T.eq ( equals 3, 3 ), true
T.eq ( equals 3, 4 ), false
done() if done?
#-----------------------------------------------------------------------------------------------------------
demo_test_for_generator = ->
GeneratorFunction = ( -> yield 42 ).constructor
Generator = ( ( -> yield 42 )() ).constructor
debug rpr GeneratorFunction.name == 'GeneratorFunction'
debug rpr Generator.name == ''
debug ( -> yield 42 ).constructor is GeneratorFunction
debug ( -> yield 42 ).constructor is Generator
debug ( ( -> yield 42 )() ).constructor is GeneratorFunction
debug ( ( -> yield 42 )() ).constructor is Generator
#-----------------------------------------------------------------------------------------------------------
demo = ->
# ```
# echo( 'helo' );
# echo( rpr(
# ( function*() { yield 42; } ).constructor.name
# ) );
# echo( rpr(
# ( function*() { yield 42; } )().constructor.name
# ) );
# ```
# node -p "require('util').inspect( ( function*() { yield 42; } ).constructor )"
# node -p "require('util').inspect( ( function*() { yield 42; } ).constructor.name )"
# node -p "require('util').inspect( ( function*() { yield 42; } )().constructor )"
# node -p "require('util').inspect( ( function*() { yield 42; } )().constructor.name )"
info rpr ( -> yield 42; ).constructor
info rpr ( -> yield 42; ).constructor.name
info rpr ( -> yield 42; )().constructor
info rpr ( -> yield 42; )().constructor.name
# info rpr NaN.constructor.name
info arrayiterator = [].keys().constructor
info setiterator = ( new Set [] ).keys().constructor
info mapiterator = ( new Map [] ).keys().constructor
info stringiterator = ( 'x' )[ Symbol.iterator ]().constructor
types = new Intertype()
# debug types.all_keys_of Buffer.alloc 10
# debug types.all_keys_of new Uint8Array 10
# class X extends NaN
# class X extends null
# class X extends undefined
# class X extends 1
# class X extends {}
myfunction = ->
class X
class O extends Object
info '^87-1^', rpr ( myfunction:: )
info '^87-2^', rpr ( myfunction:: ).constructor
info '^87-3^', rpr ( myfunction:: ).constructor.name
info '^87-4^', rpr ( X:: )
info '^87-5^', rpr ( X:: ).constructor
info '^87-6^', rpr ( X:: ).constructor.name
info '^87-7^', rpr ( O:: )
info '^87-8^', rpr ( O:: ).constructor
info '^87-9^', rpr ( O:: ).constructor.name
info Object.hasOwnProperty X, 'arguments'
info Object.hasOwnProperty ( -> ), 'arguments'
info Object.hasOwnProperty ( ( x ) -> ), 'arguments'
info Object.hasOwnProperty ( ( -> ):: ), 'arguments'
info Object.hasOwnProperty ( ( ( x ) -> ):: ), 'arguments'
urge Object.getOwnPropertyNames X
urge Object.getOwnPropertyNames ( -> )
info new Array()
############################################################################################################
if module is require.main then do =>
# demo_test_for_generator()
test @
# test @[ "undeclared types cause correct error (loupe breakage fix)" ]
# @[ "undeclared types cause correct error (loupe breakage fix)" ]()
# test @[ "undeclared but implement types can be used" ]
|
[
{
"context": " query =\n id: 'foo'\n jalapId: 'serano'\n\n @cacheKey = @sut._generateCacheKey {que",
"end": 475,
"score": 0.7327059507369995,
"start": 469,
"tag": "NAME",
"value": "serano"
},
{
"context": "per key', ->\n expect(@cacheKey).to.equal '71... | test/datastore-cache-attributes-spec.coffee | octoblu/meshblu-core-datastore | 0 | {describe,beforeEach,it,expect} = global
mongojs = require 'mongojs'
Datastore = require '../src/datastore'
describe 'Datastore cache stuff', ->
beforeEach ->
@sut = new Datastore
database: mongojs('datastore-test')
collection: 'jalapenos'
cacheAttributes: ['id', 'jalapId']
describe '->_generateCacheKey', ->
describe 'when the fields exist', ->
beforeEach ->
query =
id: 'foo'
jalapId: 'serano'
@cacheKey = @sut._generateCacheKey {query}
it 'should generate the proper key', ->
expect(@cacheKey).to.equal '71e52b62d7f35e138983163d679121b5e5123f4d'
describe 'when a field is missing', ->
beforeEach ->
query =
id: 'foo'
@cacheKey = @sut._generateCacheKey {query}
it 'should return null', ->
expect(@cacheKey).to.be.undefined
| 62597 | {describe,beforeEach,it,expect} = global
mongojs = require 'mongojs'
Datastore = require '../src/datastore'
describe 'Datastore cache stuff', ->
beforeEach ->
@sut = new Datastore
database: mongojs('datastore-test')
collection: 'jalapenos'
cacheAttributes: ['id', 'jalapId']
describe '->_generateCacheKey', ->
describe 'when the fields exist', ->
beforeEach ->
query =
id: 'foo'
jalapId: '<NAME>'
@cacheKey = @sut._generateCacheKey {query}
it 'should generate the proper key', ->
expect(@cacheKey).to.equal '7<KEY>e<KEY>2b62d7f<KEY>83<KEY>d<KEY>'
describe 'when a field is missing', ->
beforeEach ->
query =
id: 'foo'
@cacheKey = @sut._generateCacheKey {query}
it 'should return null', ->
expect(@cacheKey).to.be.undefined
| true | {describe,beforeEach,it,expect} = global
mongojs = require 'mongojs'
Datastore = require '../src/datastore'
describe 'Datastore cache stuff', ->
beforeEach ->
@sut = new Datastore
database: mongojs('datastore-test')
collection: 'jalapenos'
cacheAttributes: ['id', 'jalapId']
describe '->_generateCacheKey', ->
describe 'when the fields exist', ->
beforeEach ->
query =
id: 'foo'
jalapId: 'PI:NAME:<NAME>END_PI'
@cacheKey = @sut._generateCacheKey {query}
it 'should generate the proper key', ->
expect(@cacheKey).to.equal '7PI:KEY:<KEY>END_PIePI:KEY:<KEY>END_PI2b62d7fPI:KEY:<KEY>END_PI83PI:KEY:<KEY>END_PIdPI:KEY:<KEY>END_PI'
describe 'when a field is missing', ->
beforeEach ->
query =
id: 'foo'
@cacheKey = @sut._generateCacheKey {query}
it 'should return null', ->
expect(@cacheKey).to.be.undefined
|
[
{
"context": "pt.org/\n\nloadMap = ->\n L.mapbox.accessToken = \"pk.eyJ1Ijoic3BhY2Vib3k2OSIsImEiOiJjaWtydTV5Y3MwNG5ldHptMWQyMG5zM293In0.aRElpBXtyEqNlqft55sRzw\";\n map = L.mapbox.map(\"map-one\", \"mapbox.stree",
"end": 346,
"score": 0.9997254014015198,
"start": 253,
"tag": "KEY",
"val... | app/assets/javascripts/searches.js.coffee | everysum1/realestater | 1 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
loadMap = ->
L.mapbox.accessToken = "pk.eyJ1Ijoic3BhY2Vib3k2OSIsImEiOiJjaWtydTV5Y3MwNG5ldHptMWQyMG5zM293In0.aRElpBXtyEqNlqft55sRzw";
map = L.mapbox.map("map-one", "mapbox.streets", {
scrollWheelZoom: false
}).setView([37.782, -122.421], 13)
# markersLayer = L.featureGroup().addTo(map);
# get JSON object
# on success, parse it and
# hand it over to MapBox for mapping
$.ajax
type: "GET"
dataType: "text"
url: "search.json"
success: (data) ->
geojson = $.parseJSON(data)
map.featureLayer.setGeoJSON(geojson)
# add custom popups to each marker
map.featureLayer.on 'layeradd', (e) ->
marker = e.layer
properties = marker.feature.properties
# create custom popup
popupContent = '<div class="popup">' +
'<h3>' + properties.name + '</h3>' +
'<p>' + properties.address + '</p>' +
'</div>'
# http://leafletjs.com/reference.html#popup
marker.bindPopup popupContent,
closeButton: true
minWidth: 200
# handles a sidebar happy hour click
$('.listing').click (e) ->
current = $(this)
currentlyClickedName = current.find('h2').text()
# opens/closes popup for currently clicked happy hour
map.featureLayer.eachLayer (marker) ->
if marker.feature.properties.name is currentlyClickedName
map.panTo new L.LatLng marker._latlng.lat, marker._latlng.lng
id = marker._leaflet_id
map._layers[id].openPopup()
# markersLayer.on("click", (event) ->
# clickedMarker = event.layer;
# alert
$(document).ready(loadMap)
$(document).on("page:load", loadMap) | 145045 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
loadMap = ->
L.mapbox.accessToken = "<KEY>";
map = L.mapbox.map("map-one", "mapbox.streets", {
scrollWheelZoom: false
}).setView([37.782, -122.421], 13)
# markersLayer = L.featureGroup().addTo(map);
# get JSON object
# on success, parse it and
# hand it over to MapBox for mapping
$.ajax
type: "GET"
dataType: "text"
url: "search.json"
success: (data) ->
geojson = $.parseJSON(data)
map.featureLayer.setGeoJSON(geojson)
# add custom popups to each marker
map.featureLayer.on 'layeradd', (e) ->
marker = e.layer
properties = marker.feature.properties
# create custom popup
popupContent = '<div class="popup">' +
'<h3>' + properties.name + '</h3>' +
'<p>' + properties.address + '</p>' +
'</div>'
# http://leafletjs.com/reference.html#popup
marker.bindPopup popupContent,
closeButton: true
minWidth: 200
# handles a sidebar happy hour click
$('.listing').click (e) ->
current = $(this)
currentlyClickedName = current.find('h2').text()
# opens/closes popup for currently clicked happy hour
map.featureLayer.eachLayer (marker) ->
if marker.feature.properties.name is currentlyClickedName
map.panTo new L.LatLng marker._latlng.lat, marker._latlng.lng
id = marker._leaflet_id
map._layers[id].openPopup()
# markersLayer.on("click", (event) ->
# clickedMarker = event.layer;
# alert
$(document).ready(loadMap)
$(document).on("page:load", loadMap) | true | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
loadMap = ->
L.mapbox.accessToken = "PI:KEY:<KEY>END_PI";
map = L.mapbox.map("map-one", "mapbox.streets", {
scrollWheelZoom: false
}).setView([37.782, -122.421], 13)
# markersLayer = L.featureGroup().addTo(map);
# get JSON object
# on success, parse it and
# hand it over to MapBox for mapping
$.ajax
type: "GET"
dataType: "text"
url: "search.json"
success: (data) ->
geojson = $.parseJSON(data)
map.featureLayer.setGeoJSON(geojson)
# add custom popups to each marker
map.featureLayer.on 'layeradd', (e) ->
marker = e.layer
properties = marker.feature.properties
# create custom popup
popupContent = '<div class="popup">' +
'<h3>' + properties.name + '</h3>' +
'<p>' + properties.address + '</p>' +
'</div>'
# http://leafletjs.com/reference.html#popup
marker.bindPopup popupContent,
closeButton: true
minWidth: 200
# handles a sidebar happy hour click
$('.listing').click (e) ->
current = $(this)
currentlyClickedName = current.find('h2').text()
# opens/closes popup for currently clicked happy hour
map.featureLayer.eachLayer (marker) ->
if marker.feature.properties.name is currentlyClickedName
map.panTo new L.LatLng marker._latlng.lat, marker._latlng.lng
id = marker._leaflet_id
map._layers[id].openPopup()
# markersLayer.on("click", (event) ->
# clickedMarker = event.layer;
# alert
$(document).ready(loadMap)
$(document).on("page:load", loadMap) |
[
{
"context": "###\nCopyright (c) 2014, Groupon\nAll rights reserved.\n\nRedistribution and use in s",
"end": 31,
"score": 0.9952127933502197,
"start": 24,
"tag": "NAME",
"value": "Groupon"
}
] | src/client/controllers/alert-form.coffee | Mefiso/greenscreen | 729 | ###
Copyright (c) 2014, Groupon
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.###
angular.module("GScreen").controller "AlertForm", ($scope, $location, flash, Alert) ->
$scope.maxTextLength = 140
$scope.alert = style: "default", duration: 60
$scope.onFormSubmit = ->
seconds = $scope.alert.duration
$scope.alert.expiresAt = new Date(new Date().getTime() + (seconds * 1000)).toISOString()
Alert.save $scope.alert, ->
flash.message "Your alert has been saved."
$location.url "/"
| 151076 | ###
Copyright (c) 2014, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.###
angular.module("GScreen").controller "AlertForm", ($scope, $location, flash, Alert) ->
$scope.maxTextLength = 140
$scope.alert = style: "default", duration: 60
$scope.onFormSubmit = ->
seconds = $scope.alert.duration
$scope.alert.expiresAt = new Date(new Date().getTime() + (seconds * 1000)).toISOString()
Alert.save $scope.alert, ->
flash.message "Your alert has been saved."
$location.url "/"
| true | ###
Copyright (c) 2014, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.###
angular.module("GScreen").controller "AlertForm", ($scope, $location, flash, Alert) ->
$scope.maxTextLength = 140
$scope.alert = style: "default", duration: 60
$scope.onFormSubmit = ->
seconds = $scope.alert.duration
$scope.alert.expiresAt = new Date(new Date().getTime() + (seconds * 1000)).toISOString()
Alert.save $scope.alert, ->
flash.message "Your alert has been saved."
$location.url "/"
|
[
{
"context": " template\n) ->\n\n ###*\n # @author Raymond de Wit\n # @module App\n # @submodule ",
"end": 427,
"score": 0.9998887777328491,
"start": 413,
"tag": "NAME",
"value": "Raymond de Wit"
}
] | generators/demo/templates/src/views/navigation.coffee | marviq/generator-bat | 3 | 'use strict'
( ( factory ) ->
if typeof exports is 'object'
module.exports = factory(
require( 'backbone' )
require( './navigation.hbs' )
)
else if typeof define is 'function' and define.amd
define( [
'backbone'
'./navigation.hbs'
], factory )
return
)((
Backbone
template
) ->
###*
# @author Raymond de Wit
# @module App
# @submodule Views
###
###*
# Navigation view
#
# @class NavigationView
# @extends Backbone.View
# @constructor
###
class NavigationView extends Backbone.View
###*
# CSS class(es) to set on this view's root DOM element.
#
# @property className
# @type String
# @final
#
# @default 'navigation-view'
###
className: 'navigation-view'
###*
# The compiled handlebars template expander function.
#
# @property template
# @type Function
# @protected
# @final
###
template: template
###*
# @method render
#
# @chainable
###
render: () ->
## Expand the handlebars template into this view's container element.
##
@$el.html( @template( @renderData() ) )
# Set reference to the navbar
#
@$navBar = @$el.find( '.navbar-nav' )
## This method is chainable.
##
return @
###*
# Collect and return all data needed to expand the handlebars `@template` with
#
# @method renderData
# @protected
#
# @return {Object}
###
renderData: () ->
return {}
###*
# Set the activeMenuItem based on the url passed.
#
# @method setActiveMenuItem
#
# @param {String} url Url excluding the hash belonging to the menuitem
###
setActiveMenuItem: ( url ) ->
@$navBar.find( '.active' ).removeClass( 'active' )
@$navBar.find( "a[href='##{url}']" ).closest( 'li' ).addClass( 'active' )
return
)
| 958 | 'use strict'
( ( factory ) ->
if typeof exports is 'object'
module.exports = factory(
require( 'backbone' )
require( './navigation.hbs' )
)
else if typeof define is 'function' and define.amd
define( [
'backbone'
'./navigation.hbs'
], factory )
return
)((
Backbone
template
) ->
###*
# @author <NAME>
# @module App
# @submodule Views
###
###*
# Navigation view
#
# @class NavigationView
# @extends Backbone.View
# @constructor
###
class NavigationView extends Backbone.View
###*
# CSS class(es) to set on this view's root DOM element.
#
# @property className
# @type String
# @final
#
# @default 'navigation-view'
###
className: 'navigation-view'
###*
# The compiled handlebars template expander function.
#
# @property template
# @type Function
# @protected
# @final
###
template: template
###*
# @method render
#
# @chainable
###
render: () ->
## Expand the handlebars template into this view's container element.
##
@$el.html( @template( @renderData() ) )
# Set reference to the navbar
#
@$navBar = @$el.find( '.navbar-nav' )
## This method is chainable.
##
return @
###*
# Collect and return all data needed to expand the handlebars `@template` with
#
# @method renderData
# @protected
#
# @return {Object}
###
renderData: () ->
return {}
###*
# Set the activeMenuItem based on the url passed.
#
# @method setActiveMenuItem
#
# @param {String} url Url excluding the hash belonging to the menuitem
###
setActiveMenuItem: ( url ) ->
@$navBar.find( '.active' ).removeClass( 'active' )
@$navBar.find( "a[href='##{url}']" ).closest( 'li' ).addClass( 'active' )
return
)
| true | 'use strict'
( ( factory ) ->
if typeof exports is 'object'
module.exports = factory(
require( 'backbone' )
require( './navigation.hbs' )
)
else if typeof define is 'function' and define.amd
define( [
'backbone'
'./navigation.hbs'
], factory )
return
)((
Backbone
template
) ->
###*
# @author PI:NAME:<NAME>END_PI
# @module App
# @submodule Views
###
###*
# Navigation view
#
# @class NavigationView
# @extends Backbone.View
# @constructor
###
class NavigationView extends Backbone.View
###*
# CSS class(es) to set on this view's root DOM element.
#
# @property className
# @type String
# @final
#
# @default 'navigation-view'
###
className: 'navigation-view'
###*
# The compiled handlebars template expander function.
#
# @property template
# @type Function
# @protected
# @final
###
template: template
###*
# @method render
#
# @chainable
###
render: () ->
## Expand the handlebars template into this view's container element.
##
@$el.html( @template( @renderData() ) )
# Set reference to the navbar
#
@$navBar = @$el.find( '.navbar-nav' )
## This method is chainable.
##
return @
###*
# Collect and return all data needed to expand the handlebars `@template` with
#
# @method renderData
# @protected
#
# @return {Object}
###
renderData: () ->
return {}
###*
# Set the activeMenuItem based on the url passed.
#
# @method setActiveMenuItem
#
# @param {String} url Url excluding the hash belonging to the menuitem
###
setActiveMenuItem: ( url ) ->
@$navBar.find( '.active' ).removeClass( 'active' )
@$navBar.find( "a[href='##{url}']" ).closest( 'li' ).addClass( 'active' )
return
)
|
[
{
"context": "key: 'quotes'\npatterns: [\n {\n match: '^(?: {0,3})(>){1}(?:",
"end": 12,
"score": 0.8969787359237671,
"start": 6,
"tag": "KEY",
"value": "quotes"
}
] | grammars/repositories/blocks/quotes.cson | doc22940/language-markdown | 138 | key: 'quotes'
patterns: [
{
match: '^(?: {0,3})(>){1}(?: ){0,1}(.*)$'
name: 'quote.markup.md'
captures:
1: { name: 'punctuation.md' }
2:
patterns: [
{ include: '#blocks' }
{ include: '#inlines-in-blocks' }
]
}
]
| 86790 | key: '<KEY>'
patterns: [
{
match: '^(?: {0,3})(>){1}(?: ){0,1}(.*)$'
name: 'quote.markup.md'
captures:
1: { name: 'punctuation.md' }
2:
patterns: [
{ include: '#blocks' }
{ include: '#inlines-in-blocks' }
]
}
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
{
match: '^(?: {0,3})(>){1}(?: ){0,1}(.*)$'
name: 'quote.markup.md'
captures:
1: { name: 'punctuation.md' }
2:
patterns: [
{ include: '#blocks' }
{ include: '#inlines-in-blocks' }
]
}
]
|
[
{
"context": "# angular-image-dimensions\n# (c) 2016 Scott Lanning\n# Licensed MIT\n\n'use strict'\n\n# Directive for dis",
"end": 51,
"score": 0.9998656511306763,
"start": 38,
"tag": "NAME",
"value": "Scott Lanning"
}
] | src/angular-image-dimensions.coffee | slanningGH/angular-image-size | 3 | # angular-image-dimensions
# (c) 2016 Scott Lanning
# Licensed MIT
'use strict'
# Directive for displaying image dimensions
((root, factory) ->
# Node / CommonJS
if typeof module is 'object' and module.exports
module.exports = factory require 'angular'
# AMD. Register as an anonymous module.
else if typeof define is 'function' and define.amd
define ['angular'], factory
# Browser globals
else
factory angular
) this, (angular) ->
# expose module
'ngImageDimensions': angular.module('ngImageDimensions', []).directive 'imageDimensions', ->
# limit to attribute
restrict: 'A'
# isolate scope
scope: true
# controller for logic
controller: ['$scope', '$element', '$attrs', ($scope, element, attribute) ->
# get image element
image = element.find 'img'
# on load
image.bind 'load', ->
# image
img = image[0]
# img width and height
imgWidth = img.width
imgHeight = img.height
# img natural width and height
imgNaturalWidth = img.naturalWidth
imgNaturalHeight = img.naturalHeight
# set width in scope
$scope.width = imgWidth
# set height in scope
$scope.height = imgHeight
# set dimensions object
$scope.dimensions = "#{imgWidth} x #{imgHeight}"
# set width in scope
$scope.naturalWidth = imgNaturalWidth
# set height in scope
$scope.naturalHeight = imgNaturalHeight
# set naturalDimensions Object
$scope.naturalDimensions = "#{img.naturalWidth} x #{img.naturalHeight}"
# digest
$scope.$apply()
] | 125454 | # angular-image-dimensions
# (c) 2016 <NAME>
# Licensed MIT
'use strict'
# Directive for displaying image dimensions
((root, factory) ->
# Node / CommonJS
if typeof module is 'object' and module.exports
module.exports = factory require 'angular'
# AMD. Register as an anonymous module.
else if typeof define is 'function' and define.amd
define ['angular'], factory
# Browser globals
else
factory angular
) this, (angular) ->
# expose module
'ngImageDimensions': angular.module('ngImageDimensions', []).directive 'imageDimensions', ->
# limit to attribute
restrict: 'A'
# isolate scope
scope: true
# controller for logic
controller: ['$scope', '$element', '$attrs', ($scope, element, attribute) ->
# get image element
image = element.find 'img'
# on load
image.bind 'load', ->
# image
img = image[0]
# img width and height
imgWidth = img.width
imgHeight = img.height
# img natural width and height
imgNaturalWidth = img.naturalWidth
imgNaturalHeight = img.naturalHeight
# set width in scope
$scope.width = imgWidth
# set height in scope
$scope.height = imgHeight
# set dimensions object
$scope.dimensions = "#{imgWidth} x #{imgHeight}"
# set width in scope
$scope.naturalWidth = imgNaturalWidth
# set height in scope
$scope.naturalHeight = imgNaturalHeight
# set naturalDimensions Object
$scope.naturalDimensions = "#{img.naturalWidth} x #{img.naturalHeight}"
# digest
$scope.$apply()
] | true | # angular-image-dimensions
# (c) 2016 PI:NAME:<NAME>END_PI
# Licensed MIT
'use strict'
# Directive for displaying image dimensions
((root, factory) ->
# Node / CommonJS
if typeof module is 'object' and module.exports
module.exports = factory require 'angular'
# AMD. Register as an anonymous module.
else if typeof define is 'function' and define.amd
define ['angular'], factory
# Browser globals
else
factory angular
) this, (angular) ->
# expose module
'ngImageDimensions': angular.module('ngImageDimensions', []).directive 'imageDimensions', ->
# limit to attribute
restrict: 'A'
# isolate scope
scope: true
# controller for logic
controller: ['$scope', '$element', '$attrs', ($scope, element, attribute) ->
# get image element
image = element.find 'img'
# on load
image.bind 'load', ->
# image
img = image[0]
# img width and height
imgWidth = img.width
imgHeight = img.height
# img natural width and height
imgNaturalWidth = img.naturalWidth
imgNaturalHeight = img.naturalHeight
# set width in scope
$scope.width = imgWidth
# set height in scope
$scope.height = imgHeight
# set dimensions object
$scope.dimensions = "#{imgWidth} x #{imgHeight}"
# set width in scope
$scope.naturalWidth = imgNaturalWidth
# set height in scope
$scope.naturalHeight = imgNaturalHeight
# set naturalDimensions Object
$scope.naturalDimensions = "#{img.naturalWidth} x #{img.naturalHeight}"
# digest
$scope.$apply()
] |
[
{
"context": "../src/models/swarmbot'\n\nMOCK_FIREBASE_ADDRESS = '127.0.1' # strange host name needed by testing framework\n",
"end": 644,
"score": 0.9996833801269531,
"start": 637,
"tag": "IP_ADDRESS",
"value": "127.0.1"
},
{
"context": "irebaseio.test\"\n }\n {\n port: 5000\n ... | test/helpers/test-helper.coffee | citizencode/swarmbot | 21 | global.Promise = require 'bluebird'
{ defaults, any } = require 'lodash'
{json, log, p, pjson} = require 'lightsaber'
chai = require 'chai'
chaiAsPromised = require("chai-as-promised")
chai.should()
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use(sinonChai)
chai.use(chaiAsPromised)
FirebaseServer = require('firebase-server')
Mitm = require("mitm")
nock = require 'nock'
global.App = require '../../src/app'
ColuInfo = require '../../src/services/colu-info'
Project = require '../../src/models/project'
User = require '../../src/models/user'
swarmbot = require '../../src/models/swarmbot'
MOCK_FIREBASE_ADDRESS = '127.0.1' # strange host name needed by testing framework
process.env.FIREBASE_URL = "ws://#{MOCK_FIREBASE_ADDRESS}:5000"
ALLOWED_HOSTS = [
{
port: 443
host: "fakeserver.firebaseio.test"
}
{
port: 5000
host: "127.0.1"
}
]
before ->
@firebaseServer = new FirebaseServer 5000, MOCK_FIREBASE_ADDRESS,
beforeEach (done)->
ColuInfo.prototype.makeRequest.restore?()
ColuInfo.prototype.getAssetInfo.restore?()
sinon.stub(ColuInfo.prototype, 'getAssetInfo').returns Promise.resolve {holders: [
{address: "some bitcoin address", amount: 123}
{address: "some project address", amount: 555}
]}
ColuInfo.prototype.balances.restore?()
sinon.stub(ColuInfo.prototype, 'balances').returns Promise.resolve [
{
name: 'FinTechHacks'
assetId: 'xyz123'
balance: 456
}
]
sinon.stub(swarmbot, 'colu').returns Promise.resolve
on: ->
init: ->
sendAsset: (x, cb)-> cb(null, {txid: 1234})
issueAsset: ->
nock.cleanAll()
@mitm = Mitm()
@mitm.on "connect", (socket, opts)->
allowed = any ALLOWED_HOSTS, (allowedHost)->
allowedHost.host is opts.host and allowedHost.port is Number(opts.port)
if allowed
socket.bypass()
else
throw new Error """Call to external service from test suite!
#{ json host: opts.host, port: opts.port }"""
swarmbot.firebase().remove done
afterEach ->
@mitm.disable()
@firebaseServer.getValue()
.then (data)=> debug "Firebase data: #{pjson data}"
swarmbot.colu.restore?()
after ->
@firebaseServer.close()
class TestHelper
@USER_ID = "slack:1234"
@createUser: (args = {})=>
defaults args, {
name: "some user id"
currentProject: "some project id"
state: 'projects#show'
stateData: {}
btcAddress: 'some bitcoin address'
}
new User(args).save()
@createProject: (args = {})=>
defaults args, {
projectOwner: "some user id"
name: "some project id"
tasksUrl: 'http://example.com'
coluAssetAddress: "some project address"
}
new Project(args).save()
@createRewardType: (project, args = {})=>
defaults args, {
name: 'random reward'
suggestedAmount: '888'
}
project.createRewardType args
@message = (input, props={})->
@parts = []
defaults props, {
parts: @parts
match: [null, input]
send: (reply)=> throw new Error "deprecated, use pmReply"
message:
user: {}
robot: App.robot
}
module.exports = TestHelper
| 68084 | global.Promise = require 'bluebird'
{ defaults, any } = require 'lodash'
{json, log, p, pjson} = require 'lightsaber'
chai = require 'chai'
chaiAsPromised = require("chai-as-promised")
chai.should()
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use(sinonChai)
chai.use(chaiAsPromised)
FirebaseServer = require('firebase-server')
Mitm = require("mitm")
nock = require 'nock'
global.App = require '../../src/app'
ColuInfo = require '../../src/services/colu-info'
Project = require '../../src/models/project'
User = require '../../src/models/user'
swarmbot = require '../../src/models/swarmbot'
MOCK_FIREBASE_ADDRESS = '127.0.1' # strange host name needed by testing framework
process.env.FIREBASE_URL = "ws://#{MOCK_FIREBASE_ADDRESS}:5000"
ALLOWED_HOSTS = [
{
port: 443
host: "fakeserver.firebaseio.test"
}
{
port: 5000
host: "127.0.1"
}
]
before ->
@firebaseServer = new FirebaseServer 5000, MOCK_FIREBASE_ADDRESS,
beforeEach (done)->
ColuInfo.prototype.makeRequest.restore?()
ColuInfo.prototype.getAssetInfo.restore?()
sinon.stub(ColuInfo.prototype, 'getAssetInfo').returns Promise.resolve {holders: [
{address: "some bitcoin address", amount: 123}
{address: "some project address", amount: 555}
]}
ColuInfo.prototype.balances.restore?()
sinon.stub(ColuInfo.prototype, 'balances').returns Promise.resolve [
{
name: 'FinTechHacks'
assetId: 'xyz123'
balance: 456
}
]
sinon.stub(swarmbot, 'colu').returns Promise.resolve
on: ->
init: ->
sendAsset: (x, cb)-> cb(null, {txid: 1234})
issueAsset: ->
nock.cleanAll()
@mitm = Mitm()
@mitm.on "connect", (socket, opts)->
allowed = any ALLOWED_HOSTS, (allowedHost)->
allowedHost.host is opts.host and allowedHost.port is Number(opts.port)
if allowed
socket.bypass()
else
throw new Error """Call to external service from test suite!
#{ json host: opts.host, port: opts.port }"""
swarmbot.firebase().remove done
afterEach ->
@mitm.disable()
@firebaseServer.getValue()
.then (data)=> debug "Firebase data: #{pjson data}"
swarmbot.colu.restore?()
after ->
@firebaseServer.close()
class TestHelper
@USER_ID = "slack:1234"
@createUser: (args = {})=>
defaults args, {
name: "<NAME> user <NAME>"
currentProject: "some project id"
state: 'projects#show'
stateData: {}
btcAddress: 'some bitcoin address'
}
new User(args).save()
@createProject: (args = {})=>
defaults args, {
projectOwner: "some user id"
name: "some project id"
tasksUrl: 'http://example.com'
coluAssetAddress: "some project address"
}
new Project(args).save()
@createRewardType: (project, args = {})=>
defaults args, {
name: 'random reward'
suggestedAmount: '888'
}
project.createRewardType args
@message = (input, props={})->
@parts = []
defaults props, {
parts: @parts
match: [null, input]
send: (reply)=> throw new Error "deprecated, use pmReply"
message:
user: {}
robot: App.robot
}
module.exports = TestHelper
| true | global.Promise = require 'bluebird'
{ defaults, any } = require 'lodash'
{json, log, p, pjson} = require 'lightsaber'
chai = require 'chai'
chaiAsPromised = require("chai-as-promised")
chai.should()
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
chai.use(sinonChai)
chai.use(chaiAsPromised)
FirebaseServer = require('firebase-server')
Mitm = require("mitm")
nock = require 'nock'
global.App = require '../../src/app'
ColuInfo = require '../../src/services/colu-info'
Project = require '../../src/models/project'
User = require '../../src/models/user'
swarmbot = require '../../src/models/swarmbot'
MOCK_FIREBASE_ADDRESS = '127.0.1' # strange host name needed by testing framework
process.env.FIREBASE_URL = "ws://#{MOCK_FIREBASE_ADDRESS}:5000"
ALLOWED_HOSTS = [
{
port: 443
host: "fakeserver.firebaseio.test"
}
{
port: 5000
host: "127.0.1"
}
]
before ->
@firebaseServer = new FirebaseServer 5000, MOCK_FIREBASE_ADDRESS,
beforeEach (done)->
ColuInfo.prototype.makeRequest.restore?()
ColuInfo.prototype.getAssetInfo.restore?()
sinon.stub(ColuInfo.prototype, 'getAssetInfo').returns Promise.resolve {holders: [
{address: "some bitcoin address", amount: 123}
{address: "some project address", amount: 555}
]}
ColuInfo.prototype.balances.restore?()
sinon.stub(ColuInfo.prototype, 'balances').returns Promise.resolve [
{
name: 'FinTechHacks'
assetId: 'xyz123'
balance: 456
}
]
sinon.stub(swarmbot, 'colu').returns Promise.resolve
on: ->
init: ->
sendAsset: (x, cb)-> cb(null, {txid: 1234})
issueAsset: ->
nock.cleanAll()
@mitm = Mitm()
@mitm.on "connect", (socket, opts)->
allowed = any ALLOWED_HOSTS, (allowedHost)->
allowedHost.host is opts.host and allowedHost.port is Number(opts.port)
if allowed
socket.bypass()
else
throw new Error """Call to external service from test suite!
#{ json host: opts.host, port: opts.port }"""
swarmbot.firebase().remove done
afterEach ->
@mitm.disable()
@firebaseServer.getValue()
.then (data)=> debug "Firebase data: #{pjson data}"
swarmbot.colu.restore?()
after ->
@firebaseServer.close()
class TestHelper
@USER_ID = "slack:1234"
@createUser: (args = {})=>
defaults args, {
name: "PI:NAME:<NAME>END_PI user PI:NAME:<NAME>END_PI"
currentProject: "some project id"
state: 'projects#show'
stateData: {}
btcAddress: 'some bitcoin address'
}
new User(args).save()
@createProject: (args = {})=>
defaults args, {
projectOwner: "some user id"
name: "some project id"
tasksUrl: 'http://example.com'
coluAssetAddress: "some project address"
}
new Project(args).save()
@createRewardType: (project, args = {})=>
defaults args, {
name: 'random reward'
suggestedAmount: '888'
}
project.createRewardType args
@message = (input, props={})->
@parts = []
defaults props, {
parts: @parts
match: [null, input]
send: (reply)=> throw new Error "deprecated, use pmReply"
message:
user: {}
robot: App.robot
}
module.exports = TestHelper
|
[
{
"context": " is part of the taiga-contrib-fan package.\n#\n# (c) Simon Leblanc <contact@leblanc-simon.eu>\n#\n# For the full copyr",
"end": 79,
"score": 0.9998677372932434,
"start": 66,
"tag": "NAME",
"value": "Simon Leblanc"
},
{
"context": "taiga-contrib-fan package.\n#\n# (c) Si... | front/taiga-contrib-fan/coffee/fan.coffee | leblanc-simon/taiga-contrib-fan | 0 | ###
# This file is part of the taiga-contrib-fan package.
#
# (c) Simon Leblanc <contact@leblanc-simon.eu>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# File: fan.coffee
###
template = """
<section class="fan-container" ng-if="projects.length">
<header><h1 class="title-bar">{{ 'FAVORITE_PROJECTS' | translate }}</h1></header>
<div class="home-project" ng-repeat="project in projects">
<div class="project-card-inner" tg-nav="project:project=project.slug">
<div class="project-card-header">
<a href="#" tg-nav="project:project=project.slug" class="project-card-logo">
<img tg-project-logo-small-src="::project" />
</a>
<h3 class="project-card-name">
<a href="#" tg-nav="project:project=project.slug">{{ project.name }}</a>
</h3>
</div>
<p class="project-card-description">
{{ project.description }}
</p>
</div>
</div>
</section>
"""
available_locales = ["fr", "en"]
FanDirective = ($compile, $http, $urls, $translate) ->
link = ($scope, $el, $attrs) ->
$http.get($urls.resolve("fan")).then (response) ->
$scope.projects = response.data
fanProjects = $compile(template)($scope)
$el.prepend(fanProjects)
return {link:link}
FanConfig = ($translateProvider) ->
available_locales.forEach (locale) ->
$.get('/plugins/taiga-contrib-fan/taiga-contrib-fan-' + locale + '.json').then (data) ->
$translateProvider.translations locale, data
FanRun = ($tgUrls) ->
$tgUrls.update({
"fan": "/fan"
})
module = angular.module('taigaContrib.fan', [])
module
.config(["$translateProvider", FanConfig])
.directive("tgWorkingOn", ["$compile", "$tgHttp", "$tgUrls", "$translate", FanDirective])
.run(["$tgUrls", FanRun])
| 223033 | ###
# This file is part of the taiga-contrib-fan package.
#
# (c) <NAME> <<EMAIL>>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# File: fan.coffee
###
template = """
<section class="fan-container" ng-if="projects.length">
<header><h1 class="title-bar">{{ 'FAVORITE_PROJECTS' | translate }}</h1></header>
<div class="home-project" ng-repeat="project in projects">
<div class="project-card-inner" tg-nav="project:project=project.slug">
<div class="project-card-header">
<a href="#" tg-nav="project:project=project.slug" class="project-card-logo">
<img tg-project-logo-small-src="::project" />
</a>
<h3 class="project-card-name">
<a href="#" tg-nav="project:project=project.slug">{{ project.name }}</a>
</h3>
</div>
<p class="project-card-description">
{{ project.description }}
</p>
</div>
</div>
</section>
"""
available_locales = ["fr", "en"]
FanDirective = ($compile, $http, $urls, $translate) ->
link = ($scope, $el, $attrs) ->
$http.get($urls.resolve("fan")).then (response) ->
$scope.projects = response.data
fanProjects = $compile(template)($scope)
$el.prepend(fanProjects)
return {link:link}
FanConfig = ($translateProvider) ->
available_locales.forEach (locale) ->
$.get('/plugins/taiga-contrib-fan/taiga-contrib-fan-' + locale + '.json').then (data) ->
$translateProvider.translations locale, data
FanRun = ($tgUrls) ->
$tgUrls.update({
"fan": "/fan"
})
module = angular.module('taigaContrib.fan', [])
module
.config(["$translateProvider", FanConfig])
.directive("tgWorkingOn", ["$compile", "$tgHttp", "$tgUrls", "$translate", FanDirective])
.run(["$tgUrls", FanRun])
| true | ###
# This file is part of the taiga-contrib-fan package.
#
# (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# File: fan.coffee
###
template = """
<section class="fan-container" ng-if="projects.length">
<header><h1 class="title-bar">{{ 'FAVORITE_PROJECTS' | translate }}</h1></header>
<div class="home-project" ng-repeat="project in projects">
<div class="project-card-inner" tg-nav="project:project=project.slug">
<div class="project-card-header">
<a href="#" tg-nav="project:project=project.slug" class="project-card-logo">
<img tg-project-logo-small-src="::project" />
</a>
<h3 class="project-card-name">
<a href="#" tg-nav="project:project=project.slug">{{ project.name }}</a>
</h3>
</div>
<p class="project-card-description">
{{ project.description }}
</p>
</div>
</div>
</section>
"""
available_locales = ["fr", "en"]
FanDirective = ($compile, $http, $urls, $translate) ->
link = ($scope, $el, $attrs) ->
$http.get($urls.resolve("fan")).then (response) ->
$scope.projects = response.data
fanProjects = $compile(template)($scope)
$el.prepend(fanProjects)
return {link:link}
FanConfig = ($translateProvider) ->
available_locales.forEach (locale) ->
$.get('/plugins/taiga-contrib-fan/taiga-contrib-fan-' + locale + '.json').then (data) ->
$translateProvider.translations locale, data
FanRun = ($tgUrls) ->
$tgUrls.update({
"fan": "/fan"
})
module = angular.module('taigaContrib.fan', [])
module
.config(["$translateProvider", FanConfig])
.directive("tgWorkingOn", ["$compile", "$tgHttp", "$tgUrls", "$translate", FanDirective])
.run(["$tgUrls", FanRun])
|
[
{
"context": "egKey = new Winreg\n hive: Winreg.HKCU\n key: '\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run'\n\n\nmodule.exports =\n\n ### Public ###\n\n # op",
"end": 181,
"score": 0.9996128082275391,
"start": 129,
"tag": "KEY",
"value": "'\\\\Software\\\\Microso... | src/AutoLaunchWindows.coffee | jurkog/node-auto-launch | 1 | fs = require 'fs'
path = require 'path'
Winreg = require 'winreg'
regKey = new Winreg
hive: Winreg.HKCU
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
module.exports =
### Public ###
# options - {Object}
# :appName - {String}
# :appPath - {String}
# :appArgs - {String}
# :isHiddenOnLaunch - {Boolean}
# Returns a Promise
enable: ({appName, appPath, appArgs, isHiddenOnLaunch}) ->
return new Promise (resolve, reject) ->
pathToAutoLaunchedApp = appPath
args = appArgs
updateDotExe = path.join(path.dirname(process.execPath), '..', 'update.exe')
# If they're using Electron and Squirrel.Windows, point to its Update.exe instead
# Otherwise, we'll auto-launch an old version after the app has updated
if process.versions?.electron? and fs.existsSync updateDotExe
pathToAutoLaunchedApp = updateDotExe
args = " --processStart \"#{path.basename(process.execPath)}\""
args += ' --process-start-args "--hidden"' if isHiddenOnLaunch
else
args += ' --hidden' if isHiddenOnLaunch
regKey.set appName, Winreg.REG_SZ, "#{pathToAutoLaunchedApp}#{args}", (err) ->
return reject(err) if err?
resolve()
# appName - {String}
# Returns a Promise
disable: (appName) ->
return new Promise (resolve, reject) ->
regKey.remove appName, (err) ->
if err?
# The registry key should exist but in case it fails because it doesn't exist, resolve false instead
# rejecting with an error
if err.message.indexOf('The system was unable to find the specified registry key or value') isnt -1
return resolve false
return reject err
resolve()
# appName - {String}
# Returns a Promise which resolves to a {Boolean}
isEnabled: (appName) ->
return new Promise (resolve, reject) ->
regKey.get appName, (err, item) ->
return resolve false if err?
resolve(item?)
| 72229 | fs = require 'fs'
path = require 'path'
Winreg = require 'winreg'
regKey = new Winreg
hive: Winreg.HKCU
key: <KEY>'
module.exports =
### Public ###
# options - {Object}
# :appName - {String}
# :appPath - {String}
# :appArgs - {String}
# :isHiddenOnLaunch - {Boolean}
# Returns a Promise
enable: ({appName, appPath, appArgs, isHiddenOnLaunch}) ->
return new Promise (resolve, reject) ->
pathToAutoLaunchedApp = appPath
args = appArgs
updateDotExe = path.join(path.dirname(process.execPath), '..', 'update.exe')
# If they're using Electron and Squirrel.Windows, point to its Update.exe instead
# Otherwise, we'll auto-launch an old version after the app has updated
if process.versions?.electron? and fs.existsSync updateDotExe
pathToAutoLaunchedApp = updateDotExe
args = " --processStart \"#{path.basename(process.execPath)}\""
args += ' --process-start-args "--hidden"' if isHiddenOnLaunch
else
args += ' --hidden' if isHiddenOnLaunch
regKey.set appName, Winreg.REG_SZ, "#{pathToAutoLaunchedApp}#{args}", (err) ->
return reject(err) if err?
resolve()
# appName - {String}
# Returns a Promise
disable: (appName) ->
return new Promise (resolve, reject) ->
regKey.remove appName, (err) ->
if err?
# The registry key should exist but in case it fails because it doesn't exist, resolve false instead
# rejecting with an error
if err.message.indexOf('The system was unable to find the specified registry key or value') isnt -1
return resolve false
return reject err
resolve()
# appName - {String}
# Returns a Promise which resolves to a {Boolean}
isEnabled: (appName) ->
return new Promise (resolve, reject) ->
regKey.get appName, (err, item) ->
return resolve false if err?
resolve(item?)
| true | fs = require 'fs'
path = require 'path'
Winreg = require 'winreg'
regKey = new Winreg
hive: Winreg.HKCU
key: PI:KEY:<KEY>END_PI'
module.exports =
### Public ###
# options - {Object}
# :appName - {String}
# :appPath - {String}
# :appArgs - {String}
# :isHiddenOnLaunch - {Boolean}
# Returns a Promise
enable: ({appName, appPath, appArgs, isHiddenOnLaunch}) ->
return new Promise (resolve, reject) ->
pathToAutoLaunchedApp = appPath
args = appArgs
updateDotExe = path.join(path.dirname(process.execPath), '..', 'update.exe')
# If they're using Electron and Squirrel.Windows, point to its Update.exe instead
# Otherwise, we'll auto-launch an old version after the app has updated
if process.versions?.electron? and fs.existsSync updateDotExe
pathToAutoLaunchedApp = updateDotExe
args = " --processStart \"#{path.basename(process.execPath)}\""
args += ' --process-start-args "--hidden"' if isHiddenOnLaunch
else
args += ' --hidden' if isHiddenOnLaunch
regKey.set appName, Winreg.REG_SZ, "#{pathToAutoLaunchedApp}#{args}", (err) ->
return reject(err) if err?
resolve()
# appName - {String}
# Returns a Promise
disable: (appName) ->
return new Promise (resolve, reject) ->
regKey.remove appName, (err) ->
if err?
# The registry key should exist but in case it fails because it doesn't exist, resolve false instead
# rejecting with an error
if err.message.indexOf('The system was unable to find the specified registry key or value') isnt -1
return resolve false
return reject err
resolve()
# appName - {String}
# Returns a Promise which resolves to a {Boolean}
isEnabled: (appName) ->
return new Promise (resolve, reject) ->
regKey.get appName, (err, item) ->
return resolve false if err?
resolve(item?)
|
[
{
"context": "herself, itself, yourself', ->\n msg.token('hisself').should.eql 'itself'\n msg.subject.gen",
"end": 3669,
"score": 0.5444697141647339,
"start": 3666,
"tag": "USERNAME",
"value": "his"
},
{
"context": "elf', ->\n msg.token('hisself').should.eql 'its... | plugins/coffeekeep.messaging/test/format.coffee | leonexis/coffeekeep | 0 | should = require 'should'
path = require 'path'
async = require 'async'
should = require 'should'
coffeekeep = require 'coffeekeep'
config = [
'./coffeekeep.log'
'./coffeekeep.model'
'./coffeekeep.storage.memory'
'./coffeekeep.interpreter'
'./coffeekeep.core'
'./coffeekeep.messaging'
]
describe 'coffeekeep.model:base', ->
app = null
log = null
Message = null
before (done) ->
coffeekeep.createApp config, (err, _app) ->
return done err if err?
app = _app
{Message} = app.getService 'messaging'
done null
after ->
app.destroy()
class FakeMob
constructor: (opts={}) ->
for k, v of opts
@[k] = v
get: (key) -> @[key]
describe 'Message', ->
mob1 = mob2 = mob3 = mob4 = msg = null
beforeEach ->
mob1 = new FakeMob
gender: 0
name: 'foo'
mob2 = new FakeMob
gender: 1
name: 'bar'
mob3 = new FakeMob
gender: 2
name: 'baz'
mob4 = new FakeMob
gender: 3
name: 'faz'
msg = new Message
message: ''
observer: mob3
subject: mob1
target: mob2
describe '#token', ->
it 'should support he/she/it', ->
msg.token('he').should.eql 'it'
msg.subject.gender = 1
msg.token('he').should.eql 'he'
msg.subject.gender = 2
msg.token('he').should.eql 'she'
msg.subject.gender = 3
msg.token('he').should.eql 'zhe'
msg.subject = msg.observer
msg.token('he').should.eql 'you'
it 'should support him/her/it', ->
msg.token('him').should.eql 'it'
msg.subject.gender = 1
msg.token('him').should.eql 'him'
msg.subject = msg.observer
msg.token('him').should.eql 'you'
it 'should capitalize the first letter if needed', ->
msg.token('He').should.eql 'It'
it 'should detect ^ as target', ->
msg.token('^he').should.eql 'he'
msg.token('^name').should.eql 'bar'
it 'should support is/are', ->
msg.token('he').should.eql 'it'
msg.token('is').should.eql 'is'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('is').should.eql 'are'
it 'should support has/have', ->
msg.token('he').should.eql 'it'
msg.token('has').should.eql 'has'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('has').should.eql 'have'
it 'should support s/es endings', ->
msg.token('he').should.eql 'it'
msg.token('s').should.eql 's'
msg.token('es').should.eql 'es'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('s').should.eql ''
msg.token('es').should.eql ''
it 'should support name', ->
msg.token('name').should.eql 'foo'
msg.observer = msg.subject
msg.token('name').should.eql 'you'
it "should support name's", ->
msg.token("name's").should.eql "foo's"
msg.observer = msg.subject
msg.token("name's").should.eql 'your'
it 'should support nameself', ->
msg.token('nameself').should.eql 'foo'
msg.observer = msg.subject
msg.token('nameself').should.eql 'yourself'
it 'should support himself, herself, itself, yourself', ->
msg.token('himself').should.eql 'itself'
msg.subject.gender = 1
msg.token('himself').should.eql 'himself'
msg.observer = msg.subject
msg.token('himself').should.eql 'yourself'
it 'should support hisself, herself, itself, yourself', ->
msg.token('hisself').should.eql 'itself'
msg.subject.gender = 1
msg.token('hisself').should.eql 'hisself'
msg.observer = msg.subject
msg.token('hisself').should.eql 'yourself'
describe '#parse', ->
it 'should parse without format tokens', ->
msg.parse('foobar').should.eql ['foobar']
it 'should pass on non-terminated format tokens', ->
msg.parse('foo{bar').should.eql ['foo{bar']
it 'should parse format tokens', ->
msg.parse('foo{bar}').should.eql ['foo', {token: '{', data: 'bar'}]
msg.parse('foo{bar} {baz} ').should.eql [
'foo', {token: '{', data: 'bar'}, ' ',
{token: '{', data: 'baz'}, ' ']
msg.parse("{Name} hit{s} {^name}, killing {^him} while {he} defend{s}
{himself}.").should.eql [
{token:'{', data:'Name'}, ' hit',
{token:'{', data:'s'}, ' ',
{token:'{', data:'^name'}, ', killing ',
{token:'{', data:'^him'}, ' while ',
{token:'{', data:'he'}, ' defend',
{token:'{', data:'s'}, ' ',
{token:'{', data: 'himself'}, '.']
describe '#forObserver', ->
it 'should support specified observer', ->
msg.setMessage "{Name} hit{s} {^name}, killing {^him} while {he}
defend{s} {himself}."
msg.forObserver(msg.observer).should.eql(
'Foo hits bar, killing him while it defends itself.')
msg.forObserver(msg.subject).should.eql(
'You hit bar, killing him while you defend yourself.')
msg.forObserver(msg.target).should.eql(
'Foo hits you, killing you while it defends itself.')
describe '#toString', ->
it 'should use the default observer', ->
msg.setMessage "{Name} hit{s} {^name}"
msg.toString().should.eql 'Foo hits bar'
| 55846 | should = require 'should'
path = require 'path'
async = require 'async'
should = require 'should'
coffeekeep = require 'coffeekeep'
config = [
'./coffeekeep.log'
'./coffeekeep.model'
'./coffeekeep.storage.memory'
'./coffeekeep.interpreter'
'./coffeekeep.core'
'./coffeekeep.messaging'
]
describe 'coffeekeep.model:base', ->
app = null
log = null
Message = null
before (done) ->
coffeekeep.createApp config, (err, _app) ->
return done err if err?
app = _app
{Message} = app.getService 'messaging'
done null
after ->
app.destroy()
class FakeMob
constructor: (opts={}) ->
for k, v of opts
@[k] = v
get: (key) -> @[key]
describe 'Message', ->
mob1 = mob2 = mob3 = mob4 = msg = null
beforeEach ->
mob1 = new FakeMob
gender: 0
name: 'foo'
mob2 = new FakeMob
gender: 1
name: 'bar'
mob3 = new FakeMob
gender: 2
name: 'baz'
mob4 = new FakeMob
gender: 3
name: 'faz'
msg = new Message
message: ''
observer: mob3
subject: mob1
target: mob2
describe '#token', ->
it 'should support he/she/it', ->
msg.token('he').should.eql 'it'
msg.subject.gender = 1
msg.token('he').should.eql 'he'
msg.subject.gender = 2
msg.token('he').should.eql 'she'
msg.subject.gender = 3
msg.token('he').should.eql 'zhe'
msg.subject = msg.observer
msg.token('he').should.eql 'you'
it 'should support him/her/it', ->
msg.token('him').should.eql 'it'
msg.subject.gender = 1
msg.token('him').should.eql 'him'
msg.subject = msg.observer
msg.token('him').should.eql 'you'
it 'should capitalize the first letter if needed', ->
msg.token('He').should.eql 'It'
it 'should detect ^ as target', ->
msg.token('^he').should.eql 'he'
msg.token('^name').should.eql 'bar'
it 'should support is/are', ->
msg.token('he').should.eql 'it'
msg.token('is').should.eql 'is'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('is').should.eql 'are'
it 'should support has/have', ->
msg.token('he').should.eql 'it'
msg.token('has').should.eql 'has'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('has').should.eql 'have'
it 'should support s/es endings', ->
msg.token('he').should.eql 'it'
msg.token('s').should.eql 's'
msg.token('es').should.eql 'es'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('s').should.eql ''
msg.token('es').should.eql ''
it 'should support name', ->
msg.token('name').should.eql 'foo'
msg.observer = msg.subject
msg.token('name').should.eql 'you'
it "should support name's", ->
msg.token("name's").should.eql "foo's"
msg.observer = msg.subject
msg.token("name's").should.eql 'your'
it 'should support nameself', ->
msg.token('nameself').should.eql 'foo'
msg.observer = msg.subject
msg.token('nameself').should.eql 'yourself'
it 'should support himself, herself, itself, yourself', ->
msg.token('himself').should.eql 'itself'
msg.subject.gender = 1
msg.token('himself').should.eql 'himself'
msg.observer = msg.subject
msg.token('himself').should.eql 'yourself'
it 'should support hisself, herself, itself, yourself', ->
msg.token('hisself').should.eql 'itself'
msg.subject.gender = 1
msg.token('hisself').should.eql 'hisself'
msg.observer = msg.subject
msg.token('hisself').should.eql 'yourself'
describe '#parse', ->
it 'should parse without format tokens', ->
msg.parse('foobar').should.eql ['foobar']
it 'should pass on non-terminated format tokens', ->
msg.parse('foo{bar').should.eql ['foo{bar']
it 'should parse format tokens', ->
msg.parse('foo{bar}').should.eql ['foo', {token: '{', data: 'bar'}]
msg.parse('foo{bar} {baz} ').should.eql [
'foo', {token: '{', data: 'bar'}, ' ',
{token: '{', data: 'baz'}, ' ']
msg.parse("{Name} hit{s} {^name}, killing {^him} while {he} defend{s}
{himself}.").should.eql [
{token:'{', data:'Name'}, ' hit',
{token:'{', data:'s'}, ' ',
{token:'{', data:'^name'}, ', killing ',
{token:'{', data:'^him'}, ' while ',
{token:'{', data:'he'}, ' defend',
{token:'{', data:'s'}, ' ',
{token:'{', data: 'him<NAME>'}, '.']
describe '#forObserver', ->
it 'should support specified observer', ->
msg.setMessage "{Name} hit{s} {^name}, killing {^him} while {he}
defend{s} {himself}."
msg.forObserver(msg.observer).should.eql(
'Foo hits bar, killing him while it defends itself.')
msg.forObserver(msg.subject).should.eql(
'You hit bar, killing him while you defend yourself.')
msg.forObserver(msg.target).should.eql(
'Foo hits you, killing you while it defends itself.')
describe '#toString', ->
it 'should use the default observer', ->
msg.setMessage "{Name} hit{s} {^name}"
msg.toString().should.eql 'Foo hits bar'
| true | should = require 'should'
path = require 'path'
async = require 'async'
should = require 'should'
coffeekeep = require 'coffeekeep'
config = [
'./coffeekeep.log'
'./coffeekeep.model'
'./coffeekeep.storage.memory'
'./coffeekeep.interpreter'
'./coffeekeep.core'
'./coffeekeep.messaging'
]
describe 'coffeekeep.model:base', ->
app = null
log = null
Message = null
before (done) ->
coffeekeep.createApp config, (err, _app) ->
return done err if err?
app = _app
{Message} = app.getService 'messaging'
done null
after ->
app.destroy()
class FakeMob
constructor: (opts={}) ->
for k, v of opts
@[k] = v
get: (key) -> @[key]
describe 'Message', ->
mob1 = mob2 = mob3 = mob4 = msg = null
beforeEach ->
mob1 = new FakeMob
gender: 0
name: 'foo'
mob2 = new FakeMob
gender: 1
name: 'bar'
mob3 = new FakeMob
gender: 2
name: 'baz'
mob4 = new FakeMob
gender: 3
name: 'faz'
msg = new Message
message: ''
observer: mob3
subject: mob1
target: mob2
describe '#token', ->
it 'should support he/she/it', ->
msg.token('he').should.eql 'it'
msg.subject.gender = 1
msg.token('he').should.eql 'he'
msg.subject.gender = 2
msg.token('he').should.eql 'she'
msg.subject.gender = 3
msg.token('he').should.eql 'zhe'
msg.subject = msg.observer
msg.token('he').should.eql 'you'
it 'should support him/her/it', ->
msg.token('him').should.eql 'it'
msg.subject.gender = 1
msg.token('him').should.eql 'him'
msg.subject = msg.observer
msg.token('him').should.eql 'you'
it 'should capitalize the first letter if needed', ->
msg.token('He').should.eql 'It'
it 'should detect ^ as target', ->
msg.token('^he').should.eql 'he'
msg.token('^name').should.eql 'bar'
it 'should support is/are', ->
msg.token('he').should.eql 'it'
msg.token('is').should.eql 'is'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('is').should.eql 'are'
it 'should support has/have', ->
msg.token('he').should.eql 'it'
msg.token('has').should.eql 'has'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('has').should.eql 'have'
it 'should support s/es endings', ->
msg.token('he').should.eql 'it'
msg.token('s').should.eql 's'
msg.token('es').should.eql 'es'
msg.observer = msg.subject
msg.token('he').should.eql 'you'
msg.token('s').should.eql ''
msg.token('es').should.eql ''
it 'should support name', ->
msg.token('name').should.eql 'foo'
msg.observer = msg.subject
msg.token('name').should.eql 'you'
it "should support name's", ->
msg.token("name's").should.eql "foo's"
msg.observer = msg.subject
msg.token("name's").should.eql 'your'
it 'should support nameself', ->
msg.token('nameself').should.eql 'foo'
msg.observer = msg.subject
msg.token('nameself').should.eql 'yourself'
it 'should support himself, herself, itself, yourself', ->
msg.token('himself').should.eql 'itself'
msg.subject.gender = 1
msg.token('himself').should.eql 'himself'
msg.observer = msg.subject
msg.token('himself').should.eql 'yourself'
it 'should support hisself, herself, itself, yourself', ->
msg.token('hisself').should.eql 'itself'
msg.subject.gender = 1
msg.token('hisself').should.eql 'hisself'
msg.observer = msg.subject
msg.token('hisself').should.eql 'yourself'
describe '#parse', ->
it 'should parse without format tokens', ->
msg.parse('foobar').should.eql ['foobar']
it 'should pass on non-terminated format tokens', ->
msg.parse('foo{bar').should.eql ['foo{bar']
it 'should parse format tokens', ->
msg.parse('foo{bar}').should.eql ['foo', {token: '{', data: 'bar'}]
msg.parse('foo{bar} {baz} ').should.eql [
'foo', {token: '{', data: 'bar'}, ' ',
{token: '{', data: 'baz'}, ' ']
msg.parse("{Name} hit{s} {^name}, killing {^him} while {he} defend{s}
{himself}.").should.eql [
{token:'{', data:'Name'}, ' hit',
{token:'{', data:'s'}, ' ',
{token:'{', data:'^name'}, ', killing ',
{token:'{', data:'^him'}, ' while ',
{token:'{', data:'he'}, ' defend',
{token:'{', data:'s'}, ' ',
{token:'{', data: 'himPI:NAME:<NAME>END_PI'}, '.']
describe '#forObserver', ->
it 'should support specified observer', ->
msg.setMessage "{Name} hit{s} {^name}, killing {^him} while {he}
defend{s} {himself}."
msg.forObserver(msg.observer).should.eql(
'Foo hits bar, killing him while it defends itself.')
msg.forObserver(msg.subject).should.eql(
'You hit bar, killing him while you defend yourself.')
msg.forObserver(msg.target).should.eql(
'Foo hits you, killing you while it defends itself.')
describe '#toString', ->
it 'should use the default observer', ->
msg.setMessage "{Name} hit{s} {^name}"
msg.toString().should.eql 'Foo hits bar'
|
[
{
"context": "me: ['is invalid']}\n\n unit = new Unit(name: 'Zeratul')\n unit.valid().should.be.true\n unit.er",
"end": 2646,
"score": 0.9995409846305847,
"start": 2639,
"tag": "NAME",
"value": "Zeratul"
},
{
"context": "me: ['is invalid']}\n\n unit = new Unit(nam... | spec/model/validation-spec.coffee | wanbok/mongo-model | 1 | require '../helper'
describe "Model Validation", ->
withMongo()
describe 'CRUD', ->
[Unit, Item, unit, item] = [null, null, null, null]
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
@embedded 'items'
Unit = Tmp.Unit
class Tmp.Item extends Model
Item = Tmp.Item
unit = new Unit()
item = new Item()
unit.items = [item]
itSync 'should not save, update or delete invalid objects', ->
# Create.
unit.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Update.
unit.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Delete.
unit.valid = (args..., callback) -> callback null, false
unit.delete().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.delete().should.be.true
itSync 'should not save, update or delete invalid embedded objects', ->
# Create.
item.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Update.
item.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Delete.
item.valid = (args..., callback) -> callback null, false
unit.delete().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.delete().should.be.true
itSync "should be able to skip validation", ->
unit.valid = (args..., callback) -> callback null, false
unit.save(validate: false).should.be.true
unit.valid = (args..., callback) -> callback null, true
item.valid = (args..., callback) -> callback null, false
unit.save(validate: false).should.be.true
describe "Callbacks", ->
Unit = null
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
Unit = Tmp.Unit
itSync "should support validation callbacks", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.errors().should.eql {name: ['is invalid']}
unit = new Unit(name: 'Zeratul')
unit.valid().should.be.true
unit.errors().should.eql {}
itSync "should not save model with errors", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.errors().should.eql {name: ['is invalid']}
unit = new Unit(name: 'Zeratul')
unit.valid().should.be.true
unit.errors().should.eql {}
itSync "should clear errors before validation", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.name = 'Zeratul'
unit.valid().should.be.true
describe "Special Database Exceptions", ->
Unit = null
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
Unit = Tmp.Unit
itSync "should convert unique index exception to errors", ->
units = $db.collection 'units'
units.ensureIndex {name: 1}, unique: true
Unit.create name: 'Zeratul'
unit = new Unit name: 'Zeratul'
unit.save().should.be.false
unit.errors().should.eql {base: ["not unique value"]} | 166220 | require '../helper'
describe "Model Validation", ->
withMongo()
describe 'CRUD', ->
[Unit, Item, unit, item] = [null, null, null, null]
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
@embedded 'items'
Unit = Tmp.Unit
class Tmp.Item extends Model
Item = Tmp.Item
unit = new Unit()
item = new Item()
unit.items = [item]
itSync 'should not save, update or delete invalid objects', ->
# Create.
unit.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Update.
unit.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Delete.
unit.valid = (args..., callback) -> callback null, false
unit.delete().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.delete().should.be.true
itSync 'should not save, update or delete invalid embedded objects', ->
# Create.
item.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Update.
item.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Delete.
item.valid = (args..., callback) -> callback null, false
unit.delete().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.delete().should.be.true
itSync "should be able to skip validation", ->
unit.valid = (args..., callback) -> callback null, false
unit.save(validate: false).should.be.true
unit.valid = (args..., callback) -> callback null, true
item.valid = (args..., callback) -> callback null, false
unit.save(validate: false).should.be.true
describe "Callbacks", ->
Unit = null
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
Unit = Tmp.Unit
itSync "should support validation callbacks", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.errors().should.eql {name: ['is invalid']}
unit = new Unit(name: '<NAME>')
unit.valid().should.be.true
unit.errors().should.eql {}
itSync "should not save model with errors", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.errors().should.eql {name: ['is invalid']}
unit = new Unit(name: '<NAME>')
unit.valid().should.be.true
unit.errors().should.eql {}
itSync "should clear errors before validation", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.name = '<NAME>'
unit.valid().should.be.true
describe "Special Database Exceptions", ->
Unit = null
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
Unit = Tmp.Unit
itSync "should convert unique index exception to errors", ->
units = $db.collection 'units'
units.ensureIndex {name: 1}, unique: true
Unit.create name: '<NAME>'
unit = new Unit name: '<NAME>'
unit.save().should.be.false
unit.errors().should.eql {base: ["not unique value"]} | true | require '../helper'
describe "Model Validation", ->
withMongo()
describe 'CRUD', ->
[Unit, Item, unit, item] = [null, null, null, null]
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
@embedded 'items'
Unit = Tmp.Unit
class Tmp.Item extends Model
Item = Tmp.Item
unit = new Unit()
item = new Item()
unit.items = [item]
itSync 'should not save, update or delete invalid objects', ->
# Create.
unit.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Update.
unit.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Delete.
unit.valid = (args..., callback) -> callback null, false
unit.delete().should.be.false
unit.valid = (args..., callback) -> callback null, true
unit.delete().should.be.true
itSync 'should not save, update or delete invalid embedded objects', ->
# Create.
item.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Update.
item.valid = (args..., callback) -> callback null, false
unit.save().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.save().should.be.true
# Delete.
item.valid = (args..., callback) -> callback null, false
unit.delete().should.be.false
item.valid = (args..., callback) -> callback null, true
unit.delete().should.be.true
itSync "should be able to skip validation", ->
unit.valid = (args..., callback) -> callback null, false
unit.save(validate: false).should.be.true
unit.valid = (args..., callback) -> callback null, true
item.valid = (args..., callback) -> callback null, false
unit.save(validate: false).should.be.true
describe "Callbacks", ->
Unit = null
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
Unit = Tmp.Unit
itSync "should support validation callbacks", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.errors().should.eql {name: ['is invalid']}
unit = new Unit(name: 'PI:NAME:<NAME>END_PI')
unit.valid().should.be.true
unit.errors().should.eql {}
itSync "should not save model with errors", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.errors().should.eql {name: ['is invalid']}
unit = new Unit(name: 'PI:NAME:<NAME>END_PI')
unit.valid().should.be.true
unit.errors().should.eql {}
itSync "should clear errors before validation", ->
Unit.validate (callback) ->
@errors().add name: 'is invalid' unless /^[a-z]+$/i.test @name
callback null
unit = new Unit(name: '43')
unit.valid().should.be.false
unit.name = 'PI:NAME:<NAME>END_PI'
unit.valid().should.be.true
describe "Special Database Exceptions", ->
Unit = null
beforeEach ->
class Tmp.Unit extends Model
@collection 'units'
Unit = Tmp.Unit
itSync "should convert unique index exception to errors", ->
units = $db.collection 'units'
units.ensureIndex {name: 1}, unique: true
Unit.create name: 'PI:NAME:<NAME>END_PI'
unit = new Unit name: 'PI:NAME:<NAME>END_PI'
unit.save().should.be.false
unit.errors().should.eql {base: ["not unique value"]} |
[
{
"context": "# Copyright © 2013 All rights reserved\n# Author: nhim175@gmail.com\n\nModule = require './module.coffee'\nLogger = requ",
"end": 66,
"score": 0.9999129176139832,
"start": 49,
"tag": "EMAIL",
"value": "nhim175@gmail.com"
}
] | src/lib/bean.coffee | nhim175/scorpionsmasher | 0 | # Copyright © 2013 All rights reserved
# Author: nhim175@gmail.com
Module = require './module.coffee'
Logger = require '../mixins/logger.coffee'
WIDTH = 64
HEIGHT = 108
LEFT_DIRECTION = 0
RIGHT_DIRECTION = 1
class Bean extends Module
@include Logger
logPrefix: 'Bean'
constructor: (game) ->
@game = game
@me = @game.add.sprite @game.world.width/2, 0, 'bean'
@me.animations.add 'leftwalk', ['1'], 6, yes
@me.animations.add 'leftstand', ['2'], 6, yes
@me.animations.add 'rightstand', ['3'], 6, yes
@me.animations.add 'rightwalk', ['4'], 6, yes
@me.animations.add 'die', ['5','6'], 30, no
@me.animations.play 'rightstand'
@me.direction = LEFT_DIRECTION
@game.physics.enable @me, Phaser.Physics.ARCADE
@me.body.collideWorldBounds = true
@me.body.gravity.set 0, 380
@me.body.enable = true
@velocity = 6
standLeft: ->
@me.animations.play 'leftstand'
standRight: ->
@me.animations.play 'rightstand'
moveLeft: ->
@me.x -= @velocity
@me.animations.play 'leftwalk'
@me.direction = LEFT_DIRECTION
moveRight: ->
@me.x += @velocity
@me.animations.play 'rightwalk'
@me.direction = RIGHT_DIRECTION
die: ->
if not @isDead
@me.body.velocity.setTo 20, -350
@me.animations.play 'die'
@isDead = true
update: ->
leftKeyIsDown = @game.input.keyboard.isDown(Phaser.Keyboard.LEFT)
rightKeyIsDown = @game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)
screenIsTouched = @game.input.activePointer.isDown
touchOnLeftScreen = Math.floor(@game.input.activePointer.x/(@game.width/2)) is LEFT_DIRECTION
touchOnRightScreen = Math.floor(@game.input.activePointer.x/(@game.width/2)) is RIGHT_DIRECTION
if not @isDead
if leftKeyIsDown or (screenIsTouched and touchOnLeftScreen)
@moveLeft()
else if rightKeyIsDown or (screenIsTouched and touchOnRightScreen)
@moveRight()
else
if @me.direction is LEFT_DIRECTION then @standLeft() else @standRight()
module.exports = Bean
| 120639 | # Copyright © 2013 All rights reserved
# Author: <EMAIL>
Module = require './module.coffee'
Logger = require '../mixins/logger.coffee'
WIDTH = 64
HEIGHT = 108
LEFT_DIRECTION = 0
RIGHT_DIRECTION = 1
class Bean extends Module
@include Logger
logPrefix: 'Bean'
constructor: (game) ->
@game = game
@me = @game.add.sprite @game.world.width/2, 0, 'bean'
@me.animations.add 'leftwalk', ['1'], 6, yes
@me.animations.add 'leftstand', ['2'], 6, yes
@me.animations.add 'rightstand', ['3'], 6, yes
@me.animations.add 'rightwalk', ['4'], 6, yes
@me.animations.add 'die', ['5','6'], 30, no
@me.animations.play 'rightstand'
@me.direction = LEFT_DIRECTION
@game.physics.enable @me, Phaser.Physics.ARCADE
@me.body.collideWorldBounds = true
@me.body.gravity.set 0, 380
@me.body.enable = true
@velocity = 6
standLeft: ->
@me.animations.play 'leftstand'
standRight: ->
@me.animations.play 'rightstand'
moveLeft: ->
@me.x -= @velocity
@me.animations.play 'leftwalk'
@me.direction = LEFT_DIRECTION
moveRight: ->
@me.x += @velocity
@me.animations.play 'rightwalk'
@me.direction = RIGHT_DIRECTION
die: ->
if not @isDead
@me.body.velocity.setTo 20, -350
@me.animations.play 'die'
@isDead = true
update: ->
leftKeyIsDown = @game.input.keyboard.isDown(Phaser.Keyboard.LEFT)
rightKeyIsDown = @game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)
screenIsTouched = @game.input.activePointer.isDown
touchOnLeftScreen = Math.floor(@game.input.activePointer.x/(@game.width/2)) is LEFT_DIRECTION
touchOnRightScreen = Math.floor(@game.input.activePointer.x/(@game.width/2)) is RIGHT_DIRECTION
if not @isDead
if leftKeyIsDown or (screenIsTouched and touchOnLeftScreen)
@moveLeft()
else if rightKeyIsDown or (screenIsTouched and touchOnRightScreen)
@moveRight()
else
if @me.direction is LEFT_DIRECTION then @standLeft() else @standRight()
module.exports = Bean
| true | # Copyright © 2013 All rights reserved
# Author: PI:EMAIL:<EMAIL>END_PI
Module = require './module.coffee'
Logger = require '../mixins/logger.coffee'
WIDTH = 64
HEIGHT = 108
LEFT_DIRECTION = 0
RIGHT_DIRECTION = 1
class Bean extends Module
@include Logger
logPrefix: 'Bean'
constructor: (game) ->
@game = game
@me = @game.add.sprite @game.world.width/2, 0, 'bean'
@me.animations.add 'leftwalk', ['1'], 6, yes
@me.animations.add 'leftstand', ['2'], 6, yes
@me.animations.add 'rightstand', ['3'], 6, yes
@me.animations.add 'rightwalk', ['4'], 6, yes
@me.animations.add 'die', ['5','6'], 30, no
@me.animations.play 'rightstand'
@me.direction = LEFT_DIRECTION
@game.physics.enable @me, Phaser.Physics.ARCADE
@me.body.collideWorldBounds = true
@me.body.gravity.set 0, 380
@me.body.enable = true
@velocity = 6
standLeft: ->
@me.animations.play 'leftstand'
standRight: ->
@me.animations.play 'rightstand'
moveLeft: ->
@me.x -= @velocity
@me.animations.play 'leftwalk'
@me.direction = LEFT_DIRECTION
moveRight: ->
@me.x += @velocity
@me.animations.play 'rightwalk'
@me.direction = RIGHT_DIRECTION
die: ->
if not @isDead
@me.body.velocity.setTo 20, -350
@me.animations.play 'die'
@isDead = true
update: ->
leftKeyIsDown = @game.input.keyboard.isDown(Phaser.Keyboard.LEFT)
rightKeyIsDown = @game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)
screenIsTouched = @game.input.activePointer.isDown
touchOnLeftScreen = Math.floor(@game.input.activePointer.x/(@game.width/2)) is LEFT_DIRECTION
touchOnRightScreen = Math.floor(@game.input.activePointer.x/(@game.width/2)) is RIGHT_DIRECTION
if not @isDead
if leftKeyIsDown or (screenIsTouched and touchOnLeftScreen)
@moveLeft()
else if rightKeyIsDown or (screenIsTouched and touchOnRightScreen)
@moveRight()
else
if @me.direction is LEFT_DIRECTION then @standLeft() else @standRight()
module.exports = Bean
|
[
{
"context": ")\n\n it 'greets you back', ->\n @room.user.say('alice', '@hubot hello').then =>\n expect(@room.mess",
"end": 410,
"score": 0.5041806101799011,
"start": 405,
"tag": "NAME",
"value": "alice"
},
{
"context": ">\n expect(@room.messages).to.eql [\n ['al... | test/onboarding-test.coffee | contolini/hubot-onboarding | 9 | Helper = require 'hubot-test-helper'
sinon = require 'sinon'
chai = require 'chai'
expect = chai.expect
helper = new Helper('../src/index.coffee')
describe 'onboarding', ->
beforeEach ->
@room = helper.createRoom()
@room.user.isAdmin = true
@room.robot.auth = isAdmin: =>
return @room.user.isAdmin
afterEach ->
@room.destroy()
it 'greets you back', ->
@room.user.say('alice', '@hubot hello').then =>
expect(@room.messages).to.eql [
['alice', '@hubot hello']
['hubot', 'Hi alice! I\'m Hubot, T&I\'s automated assistant. Quick question: Are you a new CFPB employee?']
]
xit 'ignores you if you\'re not an admin', ->
@room.user.isAdmin = false
@room.user.say('alice', 'orly').then =>
expect(@room.messages).to.eql [
['alice', 'orly'],
['hubot', 'Sorry, only admins can do that.']
]
xit 'adds items', ->
@room.user.say('alice', '@hubot add foo to the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot add foo to the thing']
['hubot', 'Alright, I added foo to the thing.']
]
xit 'fails to remove items if you\'re not an admin', ->
@room.user.isAdmin = false
@room.user.say('alice', '@hubot remove foo from the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot remove foo from the thing']
['hubot', 'Sorry, only admins can remove stuff.']
]
xit 'removes items', ->
@room.user.say('alice', '@hubot remove foo from the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot remove foo from the thing']
['hubot', 'Okay, I removed foo from the thing.']
]
| 36952 | Helper = require 'hubot-test-helper'
sinon = require 'sinon'
chai = require 'chai'
expect = chai.expect
helper = new Helper('../src/index.coffee')
describe 'onboarding', ->
beforeEach ->
@room = helper.createRoom()
@room.user.isAdmin = true
@room.robot.auth = isAdmin: =>
return @room.user.isAdmin
afterEach ->
@room.destroy()
it 'greets you back', ->
@room.user.say('<NAME>', '@hubot hello').then =>
expect(@room.messages).to.eql [
['alice', '@hubot hello']
['hubot', 'Hi <NAME>! I\'m Hubot, T&I\'s automated assistant. Quick question: Are you a new CFPB employee?']
]
xit 'ignores you if you\'re not an admin', ->
@room.user.isAdmin = false
@room.user.say('<NAME>', 'orly').then =>
expect(@room.messages).to.eql [
['alice', 'orly'],
['hubot', 'Sorry, only admins can do that.']
]
xit 'adds items', ->
@room.user.say('<NAME>', '@hubot add foo to the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot add foo to the thing']
['hubot', 'Alright, I added foo to the thing.']
]
xit 'fails to remove items if you\'re not an admin', ->
@room.user.isAdmin = false
@room.user.say('alice', '@hubot remove foo from the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot remove foo from the thing']
['hubot', 'Sorry, only admins can remove stuff.']
]
xit 'removes items', ->
@room.user.say('alice', '@hubot remove foo from the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot remove foo from the thing']
['hubot', 'Okay, I removed foo from the thing.']
]
| true | Helper = require 'hubot-test-helper'
sinon = require 'sinon'
chai = require 'chai'
expect = chai.expect
helper = new Helper('../src/index.coffee')
describe 'onboarding', ->
beforeEach ->
@room = helper.createRoom()
@room.user.isAdmin = true
@room.robot.auth = isAdmin: =>
return @room.user.isAdmin
afterEach ->
@room.destroy()
it 'greets you back', ->
@room.user.say('PI:NAME:<NAME>END_PI', '@hubot hello').then =>
expect(@room.messages).to.eql [
['alice', '@hubot hello']
['hubot', 'Hi PI:NAME:<NAME>END_PI! I\'m Hubot, T&I\'s automated assistant. Quick question: Are you a new CFPB employee?']
]
xit 'ignores you if you\'re not an admin', ->
@room.user.isAdmin = false
@room.user.say('PI:NAME:<NAME>END_PI', 'orly').then =>
expect(@room.messages).to.eql [
['alice', 'orly'],
['hubot', 'Sorry, only admins can do that.']
]
xit 'adds items', ->
@room.user.say('PI:NAME:<NAME>END_PI', '@hubot add foo to the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot add foo to the thing']
['hubot', 'Alright, I added foo to the thing.']
]
xit 'fails to remove items if you\'re not an admin', ->
@room.user.isAdmin = false
@room.user.say('alice', '@hubot remove foo from the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot remove foo from the thing']
['hubot', 'Sorry, only admins can remove stuff.']
]
xit 'removes items', ->
@room.user.say('alice', '@hubot remove foo from the thing').then =>
expect(@room.messages).to.eql [
['alice', '@hubot remove foo from the thing']
['hubot', 'Okay, I removed foo from the thing.']
]
|
[
{
"context": "eate()\n @pane = new KDTabPaneView\n name: 'Koding'\n @instance = new KDTabView\n\n afterEach ->\n ",
"end": 340,
"score": 0.7329018712043762,
"start": 334,
"tag": "NAME",
"value": "Koding"
}
] | test/components/tabs/tabview.coffee | awsapps/kd | 62 | should = require 'should'
sinon = require 'sinon'
shouldSinon = require 'should-sinon'
KDTabView = require '../../../lib/components/tabs/tabview'
KDTabPaneView = require '../../../lib/components/tabs/tabpaneview'
describe 'KDTabView', ->
beforeEach ->
@sinon = sinon.sandbox.create()
@pane = new KDTabPaneView
name: 'Koding'
@instance = new KDTabView
afterEach ->
@instance.destroy()
@sinon.restore()
it 'exists', ->
KDTabView.should.exist
describe 'constructor', ->
it 'should instantiate without any errors', ->
@instance.should.exist
describe 'addPane', ->
it 'should add a pane view', ->
@instance.addPane @pane
@instance.panes.length.should.equal 1
it 'should not add a non-pane view', ->
@instance.addPane({}, no).should.equal no
@instance.panes.length.should.equal 0
describe 'removePaneByName', ->
it 'should remove pane by name', ->
@instance.addPane @pane
@instance.removePaneByName('Koding').length.should.equal 0
describe 'getActivePaneIndex', ->
it 'should get active pane index', ->
@instance.addPane @pane
@instance.getActivePaneIndex().should.equal 0
describe 'showPaneByIndex', ->
it 'should show pane by index', ->
@instance.addPane @pane
@instance.showPane = @sinon.stub()
@instance.showPaneByIndex 0
@instance.showPane.should.calledOnce()
describe 'showPaneByName', ->
it 'should show pane by name', ->
@instance.addPane @pane
@instance.showPane = @sinon.stub()
@instance.showPaneByName 'Koding'
@instance.showPane.should.calledOnce()
| 113369 | should = require 'should'
sinon = require 'sinon'
shouldSinon = require 'should-sinon'
KDTabView = require '../../../lib/components/tabs/tabview'
KDTabPaneView = require '../../../lib/components/tabs/tabpaneview'
describe 'KDTabView', ->
beforeEach ->
@sinon = sinon.sandbox.create()
@pane = new KDTabPaneView
name: '<NAME>'
@instance = new KDTabView
afterEach ->
@instance.destroy()
@sinon.restore()
it 'exists', ->
KDTabView.should.exist
describe 'constructor', ->
it 'should instantiate without any errors', ->
@instance.should.exist
describe 'addPane', ->
it 'should add a pane view', ->
@instance.addPane @pane
@instance.panes.length.should.equal 1
it 'should not add a non-pane view', ->
@instance.addPane({}, no).should.equal no
@instance.panes.length.should.equal 0
describe 'removePaneByName', ->
it 'should remove pane by name', ->
@instance.addPane @pane
@instance.removePaneByName('Koding').length.should.equal 0
describe 'getActivePaneIndex', ->
it 'should get active pane index', ->
@instance.addPane @pane
@instance.getActivePaneIndex().should.equal 0
describe 'showPaneByIndex', ->
it 'should show pane by index', ->
@instance.addPane @pane
@instance.showPane = @sinon.stub()
@instance.showPaneByIndex 0
@instance.showPane.should.calledOnce()
describe 'showPaneByName', ->
it 'should show pane by name', ->
@instance.addPane @pane
@instance.showPane = @sinon.stub()
@instance.showPaneByName 'Koding'
@instance.showPane.should.calledOnce()
| true | should = require 'should'
sinon = require 'sinon'
shouldSinon = require 'should-sinon'
KDTabView = require '../../../lib/components/tabs/tabview'
KDTabPaneView = require '../../../lib/components/tabs/tabpaneview'
describe 'KDTabView', ->
beforeEach ->
@sinon = sinon.sandbox.create()
@pane = new KDTabPaneView
name: 'PI:NAME:<NAME>END_PI'
@instance = new KDTabView
afterEach ->
@instance.destroy()
@sinon.restore()
it 'exists', ->
KDTabView.should.exist
describe 'constructor', ->
it 'should instantiate without any errors', ->
@instance.should.exist
describe 'addPane', ->
it 'should add a pane view', ->
@instance.addPane @pane
@instance.panes.length.should.equal 1
it 'should not add a non-pane view', ->
@instance.addPane({}, no).should.equal no
@instance.panes.length.should.equal 0
describe 'removePaneByName', ->
it 'should remove pane by name', ->
@instance.addPane @pane
@instance.removePaneByName('Koding').length.should.equal 0
describe 'getActivePaneIndex', ->
it 'should get active pane index', ->
@instance.addPane @pane
@instance.getActivePaneIndex().should.equal 0
describe 'showPaneByIndex', ->
it 'should show pane by index', ->
@instance.addPane @pane
@instance.showPane = @sinon.stub()
@instance.showPaneByIndex 0
@instance.showPane.should.calledOnce()
describe 'showPaneByName', ->
it 'should show pane by name', ->
@instance.addPane @pane
@instance.showPane = @sinon.stub()
@instance.showPaneByName 'Koding'
@instance.showPane.should.calledOnce()
|
[
{
"context": "ser = process.env.HUBOT_JIRA_USER\njira_password = process.env.HUBOT_JIRA_PASSWORD\npod_ip = process.env.MY_POD_IP",
"end": 1532,
"score": 0.9840198755264282,
"start": 1521,
"tag": "PASSWORD",
"value": "process.env"
},
{
"context": ".env.HUBOT_JIRA_USER\njira_password ... | scripts/jira/scripts-hipchat/jira-create.coffee | akash1233/OnBot_Demo | 4 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Set of bot commands
1. Create Issue: create jira issue in <project> with summary <summary> description <description> and issue type <issue_type>
2. Assign Issue: assign jira issue <Project_id> to <user>
3. Add Comment: add comment <comment> to jira issue <project_id>
4. Update Summary: update summary of issue <project_id> as <summary>
5. Status Change: change status of issue <project_id> to <status>
6. Edit Issue: edit jira issue <project_id> with description <desc> and comment <comment>
7. Status to Switch: upcoming status of issue <project_id>
Environment Variable Required
1. HUBOT_JIRA_URL
2. HUBOT_JIRA_USER
3. HUBOT_JIRA_PASSWORD
4. HUBOT_NAME
###
jira_url = process.env.HUBOT_JIRA_URL
jira_user = process.env.HUBOT_JIRA_USER
jira_password = process.env.HUBOT_JIRA_PASSWORD
pod_ip = process.env.MY_POD_IP
botname = process.env.HUBOT_NAME
# Load Dependencies
eindex = require('./index')
request = require('request')
create_issue = require('./create_issue.js');
edit_issue = require('./edit_issue.js');
edit_desc_issue = require('./edit_desc_issue.js');
summary_issue = require('./summary_issue.js');
update_issue = require('./update_issue.js');
close_issue = require('./close_issue.js');
assign_issue = require('./assign_issue.js');
status_issue = require('./status_issue.js');
transition_issue = require('./transition_issue.js');
readjson = require ('./readjson.js');
generate_id = require('./mongoConnt');
flag_close = '1';
module.exports = (robot) ->
a = []
flag = 0
robot.respond /create jira issue in (.*) with summary (.*) description (.*) and issue type (.*)/i, (msg) ->
message = msg.match[0]
Proj_Key = msg.match[1]
summary = msg.match[2]
description = msg.match[3]
issue_type = msg.match[4]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiracreateissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiracreateissue",Proj_Key:Proj_Key,summary:summary,description:description,issue_type:issue_type}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create jira issue in '+Proj_Key+' of issue type '+issue_type+'\n approve or reject the request'
robot.messageRoom(stdout.jiracreateissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiracreateissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_issue.create_issue jira_url, jira_user, jira_password , Proj_Key, summary, description, issue_type, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira Issue Created Successfully With ID : '.concat(Proj_Key);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Jira Issue Created Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiracreateissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for the creation of Jira issue';
# Approved Message, send to the user chat room
robot.messageRoom data_http.userid, dt;
Proj_Key = request.body.Proj_Key;
summary = request.body.summary;
description = request.body.description;
issue_type = request.body.issue_type;
# Call from create_issue file for issue creation
create_issue.create_issue jira_url, jira_user, jira_password , Proj_Key, summary, description, issue_type, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira Issue Created Successfully With ID : '.concat(Proj_Key);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'create jira issue in '+ Proj_Key + ' with summary '+ summary + ' description '+ description + ' and issue type '+ issue_type;
actionmsg = 'Jira Issue Created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for the creation of Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create issue.';
robot.respond /assign jira issue (.*) to (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
assignee = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraassignissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraassignissue",assignee:assignee,Jir_ticket:Jir_ticket}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Assign jira issue of project '+Jir_ticket+' to '+assignee+'\n approve or reject the request'
robot.messageRoom(stdout.jiraassignissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraassignissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
assign_issue.assign_issue jira_url, jira_user, jira_password , Jir_ticket, assignee, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira ticket is assigned to: '.concat(assignee);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
msg.send finalmsg;
actionmsg = 'Jira Issue Created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraassignissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' to assign Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
assignee = request.body.assignee;
# Call from assign_issue file to assign issue
assign_issue.assign_issue jira_url, jira_user, jira_password , Jir_ticket, assignee, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira ticket is assigned to: '.concat(assignee);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = "Jira Issue Assigned";
actionmsg = 'Jira ticket assigned';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is approved by '+data_http.approver+' to assign Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to assign task to assignee.';
robot.respond /edit jira issue (.*) with description (.*) and comment (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
description = msg.match[2]
comment = msg.match[3]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraeditissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraeditissue",Jir_ticket:Jir_ticket,description:description,comment:comment}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Edit jira issue of project '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraeditissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraeditissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# Call from edit_desc_issue file to edit description as well as comment
edit_desc_issue.edit_desc_issue jira_url, jira_user, jira_password , Jir_ticket, description, comment, (error, stdout, stderr) ->
if stdout
finalmsg = 'Description and Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Description and Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraeditissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for editing Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
comment = request.body.comment;
description = request.body.description;
edit_desc_issue.edit_desc_issue jira_url, jira_user, jira_password , Jir_ticket, description, comment, (error, stdout, stderr) ->
if stdout
finalmsg = 'Description and Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = 'edit jira issue '+ Jir_ticket + 'with description '+ description + 'and comment '+ comment;
actionmsg = 'Description and Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for editing Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to edit the issue.';
robot.respond /add comment (.*) to jira issue (.*)/i, (res) ->
message = msg.match[0]
Jir_ticket = res.match[2]
comment = res.match[1]
user = res.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraaddcomment.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:res.message.user.name,userid:res.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraaddcomment",Jir_ticket:Jir_ticket,comment:comment}
message='Ticket Id : '+tckid+'\n Raised By: '+res.message.user.name+'\n Command: Add comment to jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraaddcomment.adminid, message);
res.send 'Your request is waiting for approval by '+stdout.jiraaddcomment.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from edit_issue file for editing
edit_issue.edit_issue jira_url, jira_user, jira_password , comment, Jir_ticket, (error, stdout, stderr) ->
if stdout
finalmsg = 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
res.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
res.send stderr;
else if error
setTimeout (->eindex.passData error),1000
res.send error;
#Approval Workflow
robot.router.post '/jiraaddcomment', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == 'Approved'
dt='Your request is approved by '+data_http.approver+' to add comment to Jira issue';
robot.messageRoom data_http.userid, dt;
comment = request.body.comment;
Jir_ticket= request.body.Jir_ticket
edit_issue.edit_issue jira_url, jira_user, jira_password , comment, Jir_ticket, (error, stdout, stderr) ->
if stdout
finalmsg = 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
message = 'add comment '+ comment + 'to jira issue '+ Jir_ticket;
actionmsg = 'Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
#Rejection Handled
else
dt='Your request is rejected by '+data_http.approver+' to add comment to Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to add comment.';
robot.respond /update summary of issue (.*) as (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
summary = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraupdatesummary.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraupdatesummary",Jir_ticket:Jir_ticket,summary:summary}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Update summary of jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraupdatesummary.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraupdatesummary.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from summary_issue file to update or change summary of issue
summary_issue.summary_issue jira_url, jira_user, jira_password , Jir_ticket, summary, (error, stdout, stderr) ->
if stdout
finalmsg = 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Summary Updated Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraupdatesummary', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for updating the Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
summary = request.body.summary;
summary_issue.summary_issue jira_url, jira_user, jira_password , Jir_ticket, summary, (error, stdout, stderr) ->
if stdout
finalmsg = 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
message = 'update summary of issue '+ Jir_ticket + 'as '+ summary;
actionmsg = 'Summary Updated Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for updating the Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to update summary.';
robot.respond /upcoming status of issue (.*)/i, (msg) ->
Jir_ticket = msg.match[1]
# call from status_issue file to know the upcoming status
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
msg.send "Can't get status."
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
msg.send 'You Can Switch To These Status'
for i in[0...length]
msg.send (a[i].name)
# Change the status of issue
robot.respond /change status of issue (.*) to (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
status = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jirachangestatus.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jirachangestatus",Jir_ticket:Jir_ticket,status:status}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Change status of jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jirachangestatus.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jirachangestatus.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from status_issue file to know the upcoming status
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
msg.send "Can't go to status.You might not have permission."
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
for i in [0...length]
if (status == a[i].name)
flag = 1
status = a[i].id
# call from transition_issue file to switch the status from existing to new status given by status_issue file
transition_issue.transition_issue jira_url, jira_user, jira_password , Jir_ticket, status, (error, stdout, stderr) ->
if (error)
setTimeout (->eindex.passData error),1000
msg.send "Status of Jira ticket cannot be changed."
else
finalmsg = "Status Changed to #{a[i].name}"
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Status Changed';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
break
else
flag = 0
if (flag == 0)
msg.send 'You Can Only Switch To The Following Status'
for i in[0...length]
msg.send (a[i].name)
#Approval Workflow
robot.router.post '/jirachangestatus', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' to change the status of Jira issue';
robot.messageRoom data_http.userid, dt;
console.log(request.body.status)
Jir_ticket = request.body.Jir_ticket;
status = request.body.status;
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
robot.messageRoom data_http.userid, "Can't go to status.You might not have permission."
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
for i in [0...length]
if (status == a[i].name)
flag = 1
status = a[i].id
transition_issue.transition_issue jira_url, jira_user, jira_password , Jir_ticket, status, (error, stdout, stderr) ->
console.log(status);
if (error)
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, "Status of Jira ticket cannot be changed."
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if stdout
finalmsg = "Status Changed to #{a[i].name}"
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, "Status Changed to #{a[i].name}"
message = 'change status of issue '+ Jir_ticket + 'to '+ status ;
actionmsg = 'Status Changed';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
break
else
flag = 0
if (flag == 0)
robot.messageRoom data_http.userid,'You Can Only Switch To The Following Status'
for i in[0...length]
robot.messageRoom data_http.userid, (a[i].name)
else
dt='Your request is rejected by '+data_http.approver+' to change the status of Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to change status.';
| 146829 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Set of bot commands
1. Create Issue: create jira issue in <project> with summary <summary> description <description> and issue type <issue_type>
2. Assign Issue: assign jira issue <Project_id> to <user>
3. Add Comment: add comment <comment> to jira issue <project_id>
4. Update Summary: update summary of issue <project_id> as <summary>
5. Status Change: change status of issue <project_id> to <status>
6. Edit Issue: edit jira issue <project_id> with description <desc> and comment <comment>
7. Status to Switch: upcoming status of issue <project_id>
Environment Variable Required
1. HUBOT_JIRA_URL
2. HUBOT_JIRA_USER
3. HUBOT_JIRA_PASSWORD
4. HUBOT_NAME
###
jira_url = process.env.HUBOT_JIRA_URL
jira_user = process.env.HUBOT_JIRA_USER
jira_password = <PASSWORD>.<PASSWORD>
pod_ip = process.env.MY_POD_IP
botname = process.env.HUBOT_NAME
# Load Dependencies
eindex = require('./index')
request = require('request')
create_issue = require('./create_issue.js');
edit_issue = require('./edit_issue.js');
edit_desc_issue = require('./edit_desc_issue.js');
summary_issue = require('./summary_issue.js');
update_issue = require('./update_issue.js');
close_issue = require('./close_issue.js');
assign_issue = require('./assign_issue.js');
status_issue = require('./status_issue.js');
transition_issue = require('./transition_issue.js');
readjson = require ('./readjson.js');
generate_id = require('./mongoConnt');
flag_close = '1';
module.exports = (robot) ->
a = []
flag = 0
robot.respond /create jira issue in (.*) with summary (.*) description (.*) and issue type (.*)/i, (msg) ->
message = msg.match[0]
Proj_Key = msg.match[1]
summary = msg.match[2]
description = msg.match[3]
issue_type = msg.match[4]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiracreateissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiracreateissue",Proj_Key:Proj_Key,summary:summary,description:description,issue_type:issue_type}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create jira issue in '+Proj_Key+' of issue type '+issue_type+'\n approve or reject the request'
robot.messageRoom(stdout.jiracreateissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiracreateissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_issue.create_issue jira_url, jira_user, jira_password , Proj_Key, summary, description, issue_type, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira Issue Created Successfully With ID : '.concat(Proj_Key);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Jira Issue Created Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiracreateissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for the creation of Jira issue';
# Approved Message, send to the user chat room
robot.messageRoom data_http.userid, dt;
Proj_Key = request.body.Proj_Key;
summary = request.body.summary;
description = request.body.description;
issue_type = request.body.issue_type;
# Call from create_issue file for issue creation
create_issue.create_issue jira_url, jira_user, jira_password , Proj_Key, summary, description, issue_type, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira Issue Created Successfully With ID : '.concat(Proj_Key);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'create jira issue in '+ Proj_Key + ' with summary '+ summary + ' description '+ description + ' and issue type '+ issue_type;
actionmsg = 'Jira Issue Created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for the creation of Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create issue.';
robot.respond /assign jira issue (.*) to (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
assignee = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraassignissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraassignissue",assignee:assignee,Jir_ticket:Jir_ticket}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Assign jira issue of project '+Jir_ticket+' to '+assignee+'\n approve or reject the request'
robot.messageRoom(stdout.jiraassignissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraassignissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
assign_issue.assign_issue jira_url, jira_user, jira_password , Jir_ticket, assignee, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira ticket is assigned to: '.concat(assignee);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
msg.send finalmsg;
actionmsg = 'Jira Issue Created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraassignissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' to assign Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
assignee = request.body.assignee;
# Call from assign_issue file to assign issue
assign_issue.assign_issue jira_url, jira_user, jira_password , Jir_ticket, assignee, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira ticket is assigned to: '.concat(assignee);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = "Jira Issue Assigned";
actionmsg = 'Jira ticket assigned';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is approved by '+data_http.approver+' to assign Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to assign task to assignee.';
robot.respond /edit jira issue (.*) with description (.*) and comment (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
description = msg.match[2]
comment = msg.match[3]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraeditissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraeditissue",Jir_ticket:Jir_ticket,description:description,comment:comment}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Edit jira issue of project '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraeditissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraeditissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# Call from edit_desc_issue file to edit description as well as comment
edit_desc_issue.edit_desc_issue jira_url, jira_user, jira_password , Jir_ticket, description, comment, (error, stdout, stderr) ->
if stdout
finalmsg = 'Description and Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Description and Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraeditissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for editing Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
comment = request.body.comment;
description = request.body.description;
edit_desc_issue.edit_desc_issue jira_url, jira_user, jira_password , Jir_ticket, description, comment, (error, stdout, stderr) ->
if stdout
finalmsg = 'Description and Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = 'edit jira issue '+ Jir_ticket + 'with description '+ description + 'and comment '+ comment;
actionmsg = 'Description and Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for editing Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to edit the issue.';
robot.respond /add comment (.*) to jira issue (.*)/i, (res) ->
message = msg.match[0]
Jir_ticket = res.match[2]
comment = res.match[1]
user = res.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraaddcomment.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:res.message.user.name,userid:res.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraaddcomment",Jir_ticket:Jir_ticket,comment:comment}
message='Ticket Id : '+tckid+'\n Raised By: '+res.message.user.name+'\n Command: Add comment to jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraaddcomment.adminid, message);
res.send 'Your request is waiting for approval by '+stdout.jiraaddcomment.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from edit_issue file for editing
edit_issue.edit_issue jira_url, jira_user, jira_password , comment, Jir_ticket, (error, stdout, stderr) ->
if stdout
finalmsg = 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
res.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
res.send stderr;
else if error
setTimeout (->eindex.passData error),1000
res.send error;
#Approval Workflow
robot.router.post '/jiraaddcomment', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == 'Approved'
dt='Your request is approved by '+data_http.approver+' to add comment to Jira issue';
robot.messageRoom data_http.userid, dt;
comment = request.body.comment;
Jir_ticket= request.body.Jir_ticket
edit_issue.edit_issue jira_url, jira_user, jira_password , comment, Jir_ticket, (error, stdout, stderr) ->
if stdout
finalmsg = 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
message = 'add comment '+ comment + 'to jira issue '+ Jir_ticket;
actionmsg = 'Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
#Rejection Handled
else
dt='Your request is rejected by '+data_http.approver+' to add comment to Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to add comment.';
robot.respond /update summary of issue (.*) as (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
summary = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraupdatesummary.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraupdatesummary",Jir_ticket:Jir_ticket,summary:summary}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Update summary of jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraupdatesummary.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraupdatesummary.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from summary_issue file to update or change summary of issue
summary_issue.summary_issue jira_url, jira_user, jira_password , Jir_ticket, summary, (error, stdout, stderr) ->
if stdout
finalmsg = 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Summary Updated Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraupdatesummary', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for updating the Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
summary = request.body.summary;
summary_issue.summary_issue jira_url, jira_user, jira_password , Jir_ticket, summary, (error, stdout, stderr) ->
if stdout
finalmsg = 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
message = 'update summary of issue '+ Jir_ticket + 'as '+ summary;
actionmsg = 'Summary Updated Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for updating the Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to update summary.';
robot.respond /upcoming status of issue (.*)/i, (msg) ->
Jir_ticket = msg.match[1]
# call from status_issue file to know the upcoming status
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
msg.send "Can't get status."
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
msg.send 'You Can Switch To These Status'
for i in[0...length]
msg.send (a[i].name)
# Change the status of issue
robot.respond /change status of issue (.*) to (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
status = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jirachangestatus.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jirachangestatus",Jir_ticket:Jir_ticket,status:status}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Change status of jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jirachangestatus.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jirachangestatus.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from status_issue file to know the upcoming status
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
msg.send "Can't go to status.You might not have permission."
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
for i in [0...length]
if (status == a[i].name)
flag = 1
status = a[i].id
# call from transition_issue file to switch the status from existing to new status given by status_issue file
transition_issue.transition_issue jira_url, jira_user, jira_password , Jir_ticket, status, (error, stdout, stderr) ->
if (error)
setTimeout (->eindex.passData error),1000
msg.send "Status of Jira ticket cannot be changed."
else
finalmsg = "Status Changed to #{a[i].name}"
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Status Changed';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
break
else
flag = 0
if (flag == 0)
msg.send 'You Can Only Switch To The Following Status'
for i in[0...length]
msg.send (a[i].name)
#Approval Workflow
robot.router.post '/jirachangestatus', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' to change the status of Jira issue';
robot.messageRoom data_http.userid, dt;
console.log(request.body.status)
Jir_ticket = request.body.Jir_ticket;
status = request.body.status;
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
robot.messageRoom data_http.userid, "Can't go to status.You might not have permission."
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
for i in [0...length]
if (status == a[i].name)
flag = 1
status = a[i].id
transition_issue.transition_issue jira_url, jira_user, jira_password , Jir_ticket, status, (error, stdout, stderr) ->
console.log(status);
if (error)
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, "Status of Jira ticket cannot be changed."
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if stdout
finalmsg = "Status Changed to #{a[i].name}"
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, "Status Changed to #{a[i].name}"
message = 'change status of issue '+ Jir_ticket + 'to '+ status ;
actionmsg = 'Status Changed';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
break
else
flag = 0
if (flag == 0)
robot.messageRoom data_http.userid,'You Can Only Switch To The Following Status'
for i in[0...length]
robot.messageRoom data_http.userid, (a[i].name)
else
dt='Your request is rejected by '+data_http.approver+' to change the status of Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to change status.';
| true | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Set of bot commands
1. Create Issue: create jira issue in <project> with summary <summary> description <description> and issue type <issue_type>
2. Assign Issue: assign jira issue <Project_id> to <user>
3. Add Comment: add comment <comment> to jira issue <project_id>
4. Update Summary: update summary of issue <project_id> as <summary>
5. Status Change: change status of issue <project_id> to <status>
6. Edit Issue: edit jira issue <project_id> with description <desc> and comment <comment>
7. Status to Switch: upcoming status of issue <project_id>
Environment Variable Required
1. HUBOT_JIRA_URL
2. HUBOT_JIRA_USER
3. HUBOT_JIRA_PASSWORD
4. HUBOT_NAME
###
jira_url = process.env.HUBOT_JIRA_URL
jira_user = process.env.HUBOT_JIRA_USER
jira_password = PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI
pod_ip = process.env.MY_POD_IP
botname = process.env.HUBOT_NAME
# Load Dependencies
eindex = require('./index')
request = require('request')
create_issue = require('./create_issue.js');
edit_issue = require('./edit_issue.js');
edit_desc_issue = require('./edit_desc_issue.js');
summary_issue = require('./summary_issue.js');
update_issue = require('./update_issue.js');
close_issue = require('./close_issue.js');
assign_issue = require('./assign_issue.js');
status_issue = require('./status_issue.js');
transition_issue = require('./transition_issue.js');
readjson = require ('./readjson.js');
generate_id = require('./mongoConnt');
flag_close = '1';
module.exports = (robot) ->
a = []
flag = 0
robot.respond /create jira issue in (.*) with summary (.*) description (.*) and issue type (.*)/i, (msg) ->
message = msg.match[0]
Proj_Key = msg.match[1]
summary = msg.match[2]
description = msg.match[3]
issue_type = msg.match[4]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiracreateissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiracreateissue",Proj_Key:Proj_Key,summary:summary,description:description,issue_type:issue_type}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Create jira issue in '+Proj_Key+' of issue type '+issue_type+'\n approve or reject the request'
robot.messageRoom(stdout.jiracreateissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiracreateissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_issue.create_issue jira_url, jira_user, jira_password , Proj_Key, summary, description, issue_type, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira Issue Created Successfully With ID : '.concat(Proj_Key);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Jira Issue Created Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiracreateissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for the creation of Jira issue';
# Approved Message, send to the user chat room
robot.messageRoom data_http.userid, dt;
Proj_Key = request.body.Proj_Key;
summary = request.body.summary;
description = request.body.description;
issue_type = request.body.issue_type;
# Call from create_issue file for issue creation
create_issue.create_issue jira_url, jira_user, jira_password , Proj_Key, summary, description, issue_type, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira Issue Created Successfully With ID : '.concat(Proj_Key);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
# Send data to elastic search for wall notification
message = 'create jira issue in '+ Proj_Key + ' with summary '+ summary + ' description '+ description + ' and issue type '+ issue_type;
actionmsg = 'Jira Issue Created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for the creation of Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to create issue.';
robot.respond /assign jira issue (.*) to (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
assignee = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraassignissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraassignissue",assignee:assignee,Jir_ticket:Jir_ticket}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Assign jira issue of project '+Jir_ticket+' to '+assignee+'\n approve or reject the request'
robot.messageRoom(stdout.jiraassignissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraassignissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
assign_issue.assign_issue jira_url, jira_user, jira_password , Jir_ticket, assignee, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira ticket is assigned to: '.concat(assignee);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
msg.send finalmsg;
actionmsg = 'Jira Issue Created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraassignissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' to assign Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
assignee = request.body.assignee;
# Call from assign_issue file to assign issue
assign_issue.assign_issue jira_url, jira_user, jira_password , Jir_ticket, assignee, (error, stdout, stderr) ->
if stdout
finalmsg = 'Jira ticket is assigned to: '.concat(assignee);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = "Jira Issue Assigned";
actionmsg = 'Jira ticket assigned';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is approved by '+data_http.approver+' to assign Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to assign task to assignee.';
robot.respond /edit jira issue (.*) with description (.*) and comment (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
description = msg.match[2]
comment = msg.match[3]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraeditissue.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraeditissue",Jir_ticket:Jir_ticket,description:description,comment:comment}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Edit jira issue of project '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraeditissue.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraeditissue.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# Call from edit_desc_issue file to edit description as well as comment
edit_desc_issue.edit_desc_issue jira_url, jira_user, jira_password , Jir_ticket, description, comment, (error, stdout, stderr) ->
if stdout
finalmsg = 'Description and Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Description and Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraeditissue', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for editing Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
comment = request.body.comment;
description = request.body.description;
edit_desc_issue.edit_desc_issue jira_url, jira_user, jira_password , Jir_ticket, description, comment, (error, stdout, stderr) ->
if stdout
finalmsg = 'Description and Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, finalmsg;
message = 'edit jira issue '+ Jir_ticket + 'with description '+ description + 'and comment '+ comment;
actionmsg = 'Description and Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for editing Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to edit the issue.';
robot.respond /add comment (.*) to jira issue (.*)/i, (res) ->
message = msg.match[0]
Jir_ticket = res.match[2]
comment = res.match[1]
user = res.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraaddcomment.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:res.message.user.name,userid:res.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraaddcomment",Jir_ticket:Jir_ticket,comment:comment}
message='Ticket Id : '+tckid+'\n Raised By: '+res.message.user.name+'\n Command: Add comment to jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraaddcomment.adminid, message);
res.send 'Your request is waiting for approval by '+stdout.jiraaddcomment.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from edit_issue file for editing
edit_issue.edit_issue jira_url, jira_user, jira_password , comment, Jir_ticket, (error, stdout, stderr) ->
if stdout
finalmsg = 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
res.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
res.send stderr;
else if error
setTimeout (->eindex.passData error),1000
res.send error;
#Approval Workflow
robot.router.post '/jiraaddcomment', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
console.log(data_http)
if data_http.action == 'Approved'
dt='Your request is approved by '+data_http.approver+' to add comment to Jira issue';
robot.messageRoom data_http.userid, dt;
comment = request.body.comment;
Jir_ticket= request.body.Jir_ticket
edit_issue.edit_issue jira_url, jira_user, jira_password , comment, Jir_ticket, (error, stdout, stderr) ->
if stdout
finalmsg = 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, 'Comment Posted Successfully To Jira Ticket : '.concat(Jir_ticket);
message = 'add comment '+ comment + 'to jira issue '+ Jir_ticket;
actionmsg = 'Comment Posted Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
#Rejection Handled
else
dt='Your request is rejected by '+data_http.approver+' to add comment to Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to add comment.';
robot.respond /update summary of issue (.*) as (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
summary = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jiraupdatesummary.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jiraupdatesummary",Jir_ticket:Jir_ticket,summary:summary}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Update summary of jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jiraupdatesummary.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jiraupdatesummary.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from summary_issue file to update or change summary of issue
summary_issue.summary_issue jira_url, jira_user, jira_password , Jir_ticket, summary, (error, stdout, stderr) ->
if stdout
finalmsg = 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Summary Updated Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/jiraupdatesummary', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' for updating the Jira issue';
robot.messageRoom data_http.userid, dt;
Jir_ticket = request.body.Jir_ticket;
summary = request.body.summary;
summary_issue.summary_issue jira_url, jira_user, jira_password , Jir_ticket, summary, (error, stdout, stderr) ->
if stdout
finalmsg = 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, 'Summary Updated Successfully To Jira Ticket : '.concat(Jir_ticket);
message = 'update summary of issue '+ Jir_ticket + 'as '+ summary;
actionmsg = 'Summary Updated Successfully';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if error
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt='Your request is rejected by '+data_http.approver+' for updating the Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to update summary.';
robot.respond /upcoming status of issue (.*)/i, (msg) ->
Jir_ticket = msg.match[1]
# call from status_issue file to know the upcoming status
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
msg.send "Can't get status."
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
msg.send 'You Can Switch To These Status'
for i in[0...length]
msg.send (a[i].name)
# Change the status of issue
robot.respond /change status of issue (.*) to (.*)/i, (msg) ->
message = msg.match[0]
Jir_ticket = msg.match[1]
status = msg.match[2]
user = msg.message.user.name
# Reading workflow.json file for approval process
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.jirachangestatus.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:msg.message.user.reply_to,podIp:process.env.MY_POD_IP,"callback_id":"jirachangestatus",Jir_ticket:Jir_ticket,status:status}
message='Ticket Id : '+tckid+'\n Raised By: '+msg.message.user.name+'\n Command: Change status of jira issue '+Jir_ticket+'\n approve or reject the request'
robot.messageRoom(stdout.jirachangestatus.adminid, message);
msg.send 'Your request is waiting for approval by '+stdout.jirachangestatus.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
# call from status_issue file to know the upcoming status
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
msg.send "Can't go to status.You might not have permission."
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
for i in [0...length]
if (status == a[i].name)
flag = 1
status = a[i].id
# call from transition_issue file to switch the status from existing to new status given by status_issue file
transition_issue.transition_issue jira_url, jira_user, jira_password , Jir_ticket, status, (error, stdout, stderr) ->
if (error)
setTimeout (->eindex.passData error),1000
msg.send "Status of Jira ticket cannot be changed."
else
finalmsg = "Status Changed to #{a[i].name}"
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Status Changed';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
break
else
flag = 0
if (flag == 0)
msg.send 'You Can Only Switch To The Following Status'
for i in[0...length]
msg.send (a[i].name)
#Approval Workflow
robot.router.post '/jirachangestatus', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
if data_http.action == "Approved"
dt='Your request is approved by '+data_http.approver+' to change the status of Jira issue';
robot.messageRoom data_http.userid, dt;
console.log(request.body.status)
Jir_ticket = request.body.Jir_ticket;
status = request.body.status;
status_issue.status_issue jira_url, jira_user, jira_password , Jir_ticket, (error, stdout, stderr) ->
response = stdout
if error
robot.messageRoom data_http.userid, "Can't go to status.You might not have permission."
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if stdout
length = response.body.transitions.length
for i in[0...length]
a[i] = {"name":response.body.transitions[i].name,"id":response.body.transitions[i].id}
for i in [0...length]
if (status == a[i].name)
flag = 1
status = a[i].id
transition_issue.transition_issue jira_url, jira_user, jira_password , Jir_ticket, status, (error, stdout, stderr) ->
console.log(status);
if (error)
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, "Status of Jira ticket cannot be changed."
else if stderr
setTimeout (->eindex.passData stderr),1000
robot.messageRoom data_http.userid, stderr;
else if stdout
finalmsg = "Status Changed to #{a[i].name}"
setTimeout (->eindex.passData finalmsg),1000
robot.messageRoom data_http.userid, "Status Changed to #{a[i].name}"
message = 'change status of issue '+ Jir_ticket + 'to '+ status ;
actionmsg = 'Status Changed';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
break
else
flag = 0
if (flag == 0)
robot.messageRoom data_http.userid,'You Can Only Switch To The Following Status'
for i in[0...length]
robot.messageRoom data_http.userid, (a[i].name)
else
dt='Your request is rejected by '+data_http.approver+' to change the status of Jira issue';
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
robot.messageRoom data_http.userid, 'Sorry, You are not authorized to change status.';
|
[
{
"context": "collection.add(collection.parse({id: 'b4', name: 'John', number: '555-555-5558', date: new Date(1940, 10",
"end": 1540,
"score": 0.9998425245285034,
"start": 1536,
"tag": "NAME",
"value": "John"
},
{
"context": ")\n\n # get\n assert.equal(view_model.name(), 'John'... | test/spec/ecosystem/backbone-modelref.tests.coffee | metacommunications/knockback | 160 | root = if window? then window else global
assert = assert or require?('chai').assert
describe 'Knockback.js with Backbone.ModelRef.js @backbone-modelref', ->
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, Backbone, ko} = kb
root.Backbone?.ModelRef or= require?('backbone-modelref')
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!Backbone, 'Backbone')
assert.ok(!!Backbone.ModelRef, 'Backbone.ModelRef')
assert.ok(!!kb, 'kb')
done()
return unless root.Backbone?.ModelRef
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
it 'Standard use case: just enough to get the picture', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
ContactViewModel = (model) ->
@_auto = kb.viewModel(model, {keys: {
name: {key:'name'}
number: {key:'number'}
date: {key:'date'}
}}, this)
return
collection = new Contacts()
model_ref = new Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
assert.equal(view_model.name(), null, "Is that what we want to convey?")
collection.add(collection.parse({id: 'b4', name: 'John', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'John', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
assert.equal(view_model.date().toString(), new Date(1940, 10, 9).toString(), "John's birthdate matches")
# set from the view model
assert.equal(model.get('name'), 'John', "Name not changed")
assert.equal(view_model.name(), 'John', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'Yoko', number: '818-818-8181'})
assert.equal(view_model.name(), 'Yoko', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "John's birthdate")
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'Standard use case with kb.ViewModels', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {requires: ['name', 'number', 'date']})
collection = new Contacts()
model_ref = new Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
assert.equal(view_model.name(), null, "Is that what we want to convey?")
collection.add(collection.parse({id: 'b4', name: 'John', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'John', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "John's birthdate matches")
# set from the view model
assert.equal(model.get('name'), 'John', "Name not changed")
assert.equal(view_model.name(), 'John', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'Yoko', number: '818-818-8181'})
assert.equal(view_model.name(), 'Yoko', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "John's birthdate")
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'CLEANUP', -> delete Backbone.ModeRef
| 144747 | root = if window? then window else global
assert = assert or require?('chai').assert
describe 'Knockback.js with Backbone.ModelRef.js @backbone-modelref', ->
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, Backbone, ko} = kb
root.Backbone?.ModelRef or= require?('backbone-modelref')
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!Backbone, 'Backbone')
assert.ok(!!Backbone.ModelRef, 'Backbone.ModelRef')
assert.ok(!!kb, 'kb')
done()
return unless root.Backbone?.ModelRef
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
it 'Standard use case: just enough to get the picture', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
ContactViewModel = (model) ->
@_auto = kb.viewModel(model, {keys: {
name: {key:'name'}
number: {key:'number'}
date: {key:'date'}
}}, this)
return
collection = new Contacts()
model_ref = new Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
assert.equal(view_model.name(), null, "Is that what we want to convey?")
collection.add(collection.parse({id: 'b4', name: '<NAME>', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), '<NAME>', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
assert.equal(view_model.date().toString(), new Date(1940, 10, 9).toString(), "<NAME>'s birthdate matches")
# set from the view model
assert.equal(model.get('name'), '<NAME>', "Name not changed")
assert.equal(view_model.name(), '<NAME>', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: '<NAME>', number: '818-818-8181'})
assert.equal(view_model.name(), '<NAME>', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "John's birthdate")
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'Standard use case with kb.ViewModels', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {requires: ['name', 'number', 'date']})
collection = new Contacts()
model_ref = new Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
assert.equal(view_model.name(), null, "Is that what we want to convey?")
collection.add(collection.parse({id: 'b4', name: '<NAME>', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), '<NAME>', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "<NAME>'s birthdate matches")
# set from the view model
assert.equal(model.get('name'), '<NAME>', "Name not changed")
assert.equal(view_model.name(), '<NAME>', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: '<NAME>', number: '818-818-8181'})
assert.equal(view_model.name(), '<NAME>', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "<NAME>'s birthdate")
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'CLEANUP', -> delete Backbone.ModeRef
| true | root = if window? then window else global
assert = assert or require?('chai').assert
describe 'Knockback.js with Backbone.ModelRef.js @backbone-modelref', ->
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, Backbone, ko} = kb
root.Backbone?.ModelRef or= require?('backbone-modelref')
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!Backbone, 'Backbone')
assert.ok(!!Backbone.ModelRef, 'Backbone.ModelRef')
assert.ok(!!kb, 'kb')
done()
return unless root.Backbone?.ModelRef
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
it 'Standard use case: just enough to get the picture', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
ContactViewModel = (model) ->
@_auto = kb.viewModel(model, {keys: {
name: {key:'name'}
number: {key:'number'}
date: {key:'date'}
}}, this)
return
collection = new Contacts()
model_ref = new Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
assert.equal(view_model.name(), null, "Is that what we want to convey?")
collection.add(collection.parse({id: 'b4', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
assert.equal(view_model.date().toString(), new Date(1940, 10, 9).toString(), "PI:NAME:<NAME>END_PI's birthdate matches")
# set from the view model
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "Name not changed")
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: '818-818-8181'})
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "John's birthdate")
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'Standard use case with kb.ViewModels', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {requires: ['name', 'number', 'date']})
collection = new Contacts()
model_ref = new Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
assert.equal(view_model.name(), null, "Is that what we want to convey?")
collection.add(collection.parse({id: 'b4', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "PI:NAME:<NAME>END_PI's birthdate matches")
# set from the view model
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "Name not changed")
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: '818-818-8181'})
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
assert.equal(view_model.date().toString(), (new Date(1940, 10, 9)).toString(), "PI:NAME:<NAME>END_PI's birthdate")
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'CLEANUP', -> delete Backbone.ModeRef
|
[
{
"context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @",
"end": 33,
"score": 0.9998968243598938,
"start": 17,
"tag": "NAME",
"value": "Abdelhakim RAFIK"
},
{
"context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki... | src/app/models/user.coffee | AbdelhakimRafik/Project | 1 | ###
* @author Abdelhakim RAFIK
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 Abdelhakim RAFIK
* @date June 2021
###
bcrypt = require 'bcrypt'
config = require '../../config'
###
User model
###
module.exports = (sequelize, DataTypes) ->
# define the model
User = sequelize.define 'User',
firstName:
type: DataTypes.STRING
allowNull: false
lastName:
type: DataTypes.STRING
allowNull: false
email:
type: DataTypes.STRING
allowNull: false
validate:
isEmail: true
password:
type: DataTypes.STRING
allowNull: false
validate:
min: 5
phone:
type: DataTypes.STRING 10
validate:
is: /^0[567][0-9]{8}$/
city:
type: DataTypes.STRING
validate:
isAlpha: true
country:
type: DataTypes.STRING
validate:
isAlpha: true
role:
allowNull: false
type: DataTypes.STRING 6
defaultValue: 'guest'
validate:
isIn: [['admin', 'author', 'guest']]
createdAt:
allowNull: false
type: DataTypes.DATE
updatedAt:
allowNull: false
type: DataTypes.DATE
,
hooks:
beforeCreate: (user) ->
# hash user password
user.password = bcrypt.hashSync user.password, config.bcrypt.salt
return
beforeBulkUpdate: (user) ->
# if changing password
if user.attributes.password
# hash user password
user.attributes.password = bcrypt.hashSync user.attributes.password, config.bcrypt.salt
return
# add password verify function to User proto
User.prototype.passwordVerify = (password) ->
# check given password with current user password
return bcrypt.compareSync password, @password
# return user Model
return User | 142640 | ###
* @author <NAME>
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 <NAME>
* @date June 2021
###
bcrypt = require 'bcrypt'
config = require '../../config'
###
User model
###
module.exports = (sequelize, DataTypes) ->
# define the model
User = sequelize.define 'User',
firstName:
type: DataTypes.STRING
allowNull: false
lastName:
type: DataTypes.STRING
allowNull: false
email:
type: DataTypes.STRING
allowNull: false
validate:
isEmail: true
password:
type: DataTypes.STRING
allowNull: false
validate:
min: 5
phone:
type: DataTypes.STRING 10
validate:
is: /^0[567][0-9]{8}$/
city:
type: DataTypes.STRING
validate:
isAlpha: true
country:
type: DataTypes.STRING
validate:
isAlpha: true
role:
allowNull: false
type: DataTypes.STRING 6
defaultValue: 'guest'
validate:
isIn: [['admin', 'author', 'guest']]
createdAt:
allowNull: false
type: DataTypes.DATE
updatedAt:
allowNull: false
type: DataTypes.DATE
,
hooks:
beforeCreate: (user) ->
# hash user password
user.password = bcrypt.hashSync user.password, config.bcrypt.salt
return
beforeBulkUpdate: (user) ->
# if changing password
if user.attributes.password
# hash user password
user.attributes.password = bcrypt.hashSync user.attributes.password, config.bcrypt.salt
return
# add password verify function to User proto
User.prototype.passwordVerify = (password) ->
# check given password with current user password
return bcrypt.compareSync password, @password
# return user Model
return User | true | ###
* @author PI:NAME:<NAME>END_PI
* @version v1.0.1
* @license MIT License
* @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI
* @date June 2021
###
bcrypt = require 'bcrypt'
config = require '../../config'
###
User model
###
module.exports = (sequelize, DataTypes) ->
# define the model
User = sequelize.define 'User',
firstName:
type: DataTypes.STRING
allowNull: false
lastName:
type: DataTypes.STRING
allowNull: false
email:
type: DataTypes.STRING
allowNull: false
validate:
isEmail: true
password:
type: DataTypes.STRING
allowNull: false
validate:
min: 5
phone:
type: DataTypes.STRING 10
validate:
is: /^0[567][0-9]{8}$/
city:
type: DataTypes.STRING
validate:
isAlpha: true
country:
type: DataTypes.STRING
validate:
isAlpha: true
role:
allowNull: false
type: DataTypes.STRING 6
defaultValue: 'guest'
validate:
isIn: [['admin', 'author', 'guest']]
createdAt:
allowNull: false
type: DataTypes.DATE
updatedAt:
allowNull: false
type: DataTypes.DATE
,
hooks:
beforeCreate: (user) ->
# hash user password
user.password = bcrypt.hashSync user.password, config.bcrypt.salt
return
beforeBulkUpdate: (user) ->
# if changing password
if user.attributes.password
# hash user password
user.attributes.password = bcrypt.hashSync user.attributes.password, config.bcrypt.salt
return
# add password verify function to User proto
User.prototype.passwordVerify = (password) ->
# check given password with current user password
return bcrypt.compareSync password, @password
# return user Model
return User |
[
{
"context": "eParser()\n app.use express.session(\n secret: \"2433804vsdfnoeignlsd\"\n key: \"ignorethis\"\n cookie:\n path: \"/",
"end": 413,
"score": 0.9961597323417664,
"start": 393,
"tag": "KEY",
"value": "2433804vsdfnoeignlsd"
},
{
"context": "ion(\n secret: \... | nodejs/cookbooks/challenge/aux/webapp/app.coffee | mitre-cyber-academy/2012-web-d | 0 | express = require("express")
routes = require("./routes")
http = require("http")
app = express()
app.configure ->
app.set "port", process.env.PORT or 3000
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.favicon()
app.use express.logger("dev")
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.session(
secret: "2433804vsdfnoeignlsd"
key: "ignorethis"
cookie:
path: "/chat"
httpOnly: true
)
app.use express.methodOverride()
app.use app.router
app.use express.static(__dirname + "/public")
app.configure "development", ->
app.use express.errorHandler()
app.get "/", routes.index
app.get "/chat", routes.chat
app.post "/chat/msg", routes.chat_msg
app.get "/chat/msg", routes.chat_get_msg
app.post "/chat/nick", routes.chat_nick
app.post "/chat/sub", routes.chat_subject
app.get "/resources/flag", routes.flag
app.get "/resources", routes.resources
http.createServer(app).listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
| 178707 | express = require("express")
routes = require("./routes")
http = require("http")
app = express()
app.configure ->
app.set "port", process.env.PORT or 3000
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.favicon()
app.use express.logger("dev")
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.session(
secret: "<KEY>"
key: "<KEY>"
cookie:
path: "/chat"
httpOnly: true
)
app.use express.methodOverride()
app.use app.router
app.use express.static(__dirname + "/public")
app.configure "development", ->
app.use express.errorHandler()
app.get "/", routes.index
app.get "/chat", routes.chat
app.post "/chat/msg", routes.chat_msg
app.get "/chat/msg", routes.chat_get_msg
app.post "/chat/nick", routes.chat_nick
app.post "/chat/sub", routes.chat_subject
app.get "/resources/flag", routes.flag
app.get "/resources", routes.resources
http.createServer(app).listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
| true | express = require("express")
routes = require("./routes")
http = require("http")
app = express()
app.configure ->
app.set "port", process.env.PORT or 3000
app.set "views", __dirname + "/views"
app.set "view engine", "jade"
app.use express.favicon()
app.use express.logger("dev")
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.session(
secret: "PI:KEY:<KEY>END_PI"
key: "PI:KEY:<KEY>END_PI"
cookie:
path: "/chat"
httpOnly: true
)
app.use express.methodOverride()
app.use app.router
app.use express.static(__dirname + "/public")
app.configure "development", ->
app.use express.errorHandler()
app.get "/", routes.index
app.get "/chat", routes.chat
app.post "/chat/msg", routes.chat_msg
app.get "/chat/msg", routes.chat_get_msg
app.post "/chat/nick", routes.chat_nick
app.post "/chat/sub", routes.chat_subject
app.get "/resources/flag", routes.flag
app.get "/resources", routes.resources
http.createServer(app).listen app.get("port"), ->
console.log "Express server listening on port " + app.get("port")
|
[
{
"context": " \r\n for user in Users\r\n if user.name is player\r\n person = user\r\n break\r\n\r\n whil",
"end": 1389,
"score": 0.825956404209137,
"start": 1383,
"tag": "USERNAME",
"value": "player"
},
{
"context": " msgObj\r\n )\r\n\r\n han... | CoffeeScript/src/KBot-CAH.coffee | Maw-Fox/KBot | 0 | do ->
KBot.Cah.users = []
KBot.Cah.hands = []
KBot.Cah.Round =
number: NaN
phase: "select"
hands: []
card: null
judge: 0
channel: null
KBot.Cah.used = []
KBot.Cah.inPlay = false
KBot.Cah.print = (msg, msgObj, qHandle) ->
if KBot.waitFor and not qHandle
return KBot.queue.push ->
KBot.Cah.print msg, msgObj, true
KBot.waitFor = true
if msgObj.to.type is "channel"
FList.Chat.printMessage
msg: "[b]K-CAH[/b]: #{msg}"
to: FList.Chat.TabBar.getTabFromId "channel", KBot.Cah.Round.channel
from: FList.Chat.identity
type: "chat"
FList.Connection.send "MSG " + JSON.stringify
"channel": KBot.Cah.Round.channel
"message": "[b]K-CAH[/b]: #{msg}"
else
FList.Connection.send "PRI " + JSON.stringify
"recipient": msgObj.to.id
"message": "[b]K-CAH[/b]: #{msg}"
KBot.Cmds.cah = do ->
Cmd = KBot.Cmds
Cah = KBot.Cah
Users = Cah.users
Round = Cah.Round
Phase = Round.phase
Hands = Round.hands
Chat = FList.Chat
BLACK_CARDS = Cah.Cards.BLACK_CARDS
WHITE_CARDS = Cah.Cards.WHITE_CARDS
createHand = (player) ->
msgObj =
to:
id: player
type: "user"
sendString = "Your hand for this round is:\n"
for user in Users
if user.name is player
person = user
break
while person.hand.length < 8
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
person.hand.push card
Cah.used.push card
for card, n in person.hand
sendString += "#{n}) #{card}\n"
Cah.print sendString, msgObj
newRound = ->
Round.phase = "select"
Round.number++
Round.judge++
Round.judge = if Round.judge is Users.length then 0 else Round.judge
Round.hands = []
for user, key in Users
sendString = "Your hand for this round is:\n"
while user.hand.length < 8
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
user.hand.push card
Cah.used.push card
for card, n in user.hand
sendString += "#{n}) #{card}\n"
if key is Round.judge
sendString += "\n[b]You are the current judge.[/b]"
msgObj =
to:
id: user.name
type: "user"
Cah.print sendString, msgObj
black = BLACK_CARDS[~~(Math.random() * BLACK_CARDS.length)]
Round.card =
text: black.card
pick: black.pick
msgObj =
to:
type: "channel"
Cah.print(
"Judge: #{Users[Round.judge].name}\nRound [b]#{Round.number}[/b]\n" +
"Pick: #{Round.card.pick}\n" +
"Black Card: #{Round.card.text}"
, msgObj
)
gameInit = ->
Cah.used = []
for user, key in Users
user.hand = []
sendString = "Your hand for this round is:\n"
for n in [0...8]
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
Cah.used.push card
user.hand.push card
sendString += "#{n}) #{card}\n"
sendString = sendString.slice 0, sendString.length - 1
if key is Round.judge
sendString += "\n[b]You are the current judge.[/b]"
msgObj =
to:
id: user.name
type: "user"
Cah.print sendString, msgObj
black = BLACK_CARDS[~~(Math.random() * BLACK_CARDS.length)]
Round.card =
text: black.card
pick: black.pick
msgObj =
to:
type: "channel"
Cah.print(
"Judge: #{Users[Round.judge].name}\nPick: #{Round.card.pick}\n" +
"Black Card: #{Round.card.text}"
, msgObj
)
getPlayers = ->
players = []
players.push pObj.name for pObj in Users
return players
select = (cards, player) ->
isValid = false
isJudge = false
msgObj =
to:
type:"channel"
for user in Users
if user.name is player
pObj = user
isValid = true
isJudge = (Users[Round.judge].name is player)
break
if isJudge and Round.phase is "judge"
unless Round.hands[cards[0]]
return Cah.print(
"You cannot select a hand that doesn't exist.",
msgObj
)
for user in Users
if user.name is Round.hands[cards[0]].name
winner = user
winner.score += 1
Cah.print(
"#{winner.name} has won the round and has a total" +
" of [b]#{winner.score}[/b] points.",
msgObj
)
return newRound()
if Round.phase is "select" and isJudge
return Cah.print(
"You are this round's judge.",
msgObj
)
if Round.phase is "judge"
return Cah.print(
"You are not the judge.",
msgObj
)
unless isValid
return Cah.print(
"Cannot select when not in game.",
msgObj
)
if Phase is "judge"
return Cah.print(
"Cannot select within judgement phase.",
msgObj
)
unless Cah.inPlay
return Cah.print(
"Cannot select when a game is not active.",
msgObj
)
for hand in Round.hands
if hand.name is player
return Cah.print(
"You have already submitted your hand.",
msgObj
)
if cards.length isnt Round.card.pick
return Cah.print(
"Invalid card selection where the current card's pick number " +
"is #{Round.card.pick} and you selected #{cards.length}.",
msgObj
)
hand = {
name: player
cards: []
}
for card, val in cards
unless pObj.hand[card]
return Cah.print(
"Invalid selection: #{val}.",
msgObj
)
hand.cards.push pObj.hand[card]
for card, val in hand.cards
pObj.hand.splice pObj.hand.indexOf(card), 1
Cah.used.splice Cah.used.indexOf(card), 1
Round.hands.push hand
console.log Round.hands, hand
Cah.print "#{player} has submitted their hand.", msgObj
if Round.hands.length is Users.length - 1
Round.phase = "judge"
msg = "#{Users[Round.judge].name} please select a card combo:\n"
Round.hands = Round.hands.sort(
->
return ~~(Math.random() * 2)
)
for hand, key in Round.hands
msg += "#{key}) #{hand.cards.join ", "}\n"
msg = msg.slice 0, msg.length - 1
Cah.print msg, msgObj
funcs =
quit: (x, player, msgObj) ->
for user, key in Users
if user.name is player
uKey = key
break
msgObj =
to:
type:"channel"
for card in Users[uKey].hand
Cah.used.splice Cah.used.indexOf(card), 1
Users.splice uKey, 1
unless Cah.inPlay
return Cah.print "#{player} has left the game.", msgObj
if Users.length < 3 and Cah.inPlay
Cah.inPlay = false
Cah.used = []
Round.judge = 0
Round.number = 0
Round.card = null
Round.channel = null
return Cah.print(
"#{player} has left the game. Game cannot continue with " +
"less than 3 players. Reseting.",
msgObj
)
if Round.phase = "judge" and Round.judge is uKey
Cah.print(
"#{player} has left the game, and due to being the judge, the " +
"round must be reset.",
msgObj
)
return newRound()
Cah.print "#{player} has left the game.", msgObj
for hand, key in Round.hands
if hand.name is player
Round.hands.splice key, 1
break
if Round.hands.length is Users.length
Round.phase = "judge"
msg = "#{Users[Round.judge].name} please select a card combo:\n"
Round.hands = Round.hands.sort(
->
return ~~(Math.random() * 2)
)
for hand, key in Round.hands
msg += "#{key}) #{hand.hand.join ", "}\n"
msg = msg.slice 0, msg.length - 1
Cah.print msg, msgObj
join: (x, player, msgObj) ->
for user in Users
if user.name is player
return Cah.print "You are already in the game.", msgObj
pObj = {
name: player
score: 0
hand: []
}
Cah.users.push pObj
Round.channel = msgObj.to.id
if Cah.inPlay
createHand player
return Cah.print "#{player} has joined the game in progress.", msgObj
return Cah.print(
"#{player} has joined the game. Current players waiting to " +
"play: #{getPlayers().join(", ")}",
msgObj
)
start: (x, y, msgObj) ->
unless Users.length > 2
return Cah.print(
"You require at least three players to begin a game."
"play: #{getPlayers().join(", ")}",
msgObj
)
Cah.print "ROUND 1, FIGHT!", msgObj
Round.judge = ~~(Math.random() * Users.length)
Round.number = 1
Round.phase = "select"
Cah.inPlay = true
gameInit msgObj
# Main CAH handler
cah = (msg, msgObj) ->
msg = msg
.trim()
.replace new RegExp("/ +/", "g")
cmd = msg.split(" ")[0]
if msg.split(",").length > 1
msg = msg.split ","
msg[key] = parseInt(card, 10) for card, key in msg
select(msg, msgObj.from, msgObj)
return
unless isNaN parseInt(msg)
msg = [parseInt(msg, 10)]
select(msg, msgObj.from)
return
unless funcs[cmd]
return Cah.print "Wat?", msgObj
funcs[cmd] msg, msgObj.from, msgObj
return
return cah | 88990 | do ->
KBot.Cah.users = []
KBot.Cah.hands = []
KBot.Cah.Round =
number: NaN
phase: "select"
hands: []
card: null
judge: 0
channel: null
KBot.Cah.used = []
KBot.Cah.inPlay = false
KBot.Cah.print = (msg, msgObj, qHandle) ->
if KBot.waitFor and not qHandle
return KBot.queue.push ->
KBot.Cah.print msg, msgObj, true
KBot.waitFor = true
if msgObj.to.type is "channel"
FList.Chat.printMessage
msg: "[b]K-CAH[/b]: #{msg}"
to: FList.Chat.TabBar.getTabFromId "channel", KBot.Cah.Round.channel
from: FList.Chat.identity
type: "chat"
FList.Connection.send "MSG " + JSON.stringify
"channel": KBot.Cah.Round.channel
"message": "[b]K-CAH[/b]: #{msg}"
else
FList.Connection.send "PRI " + JSON.stringify
"recipient": msgObj.to.id
"message": "[b]K-CAH[/b]: #{msg}"
KBot.Cmds.cah = do ->
Cmd = KBot.Cmds
Cah = KBot.Cah
Users = Cah.users
Round = Cah.Round
Phase = Round.phase
Hands = Round.hands
Chat = FList.Chat
BLACK_CARDS = Cah.Cards.BLACK_CARDS
WHITE_CARDS = Cah.Cards.WHITE_CARDS
createHand = (player) ->
msgObj =
to:
id: player
type: "user"
sendString = "Your hand for this round is:\n"
for user in Users
if user.name is player
person = user
break
while person.hand.length < 8
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
person.hand.push card
Cah.used.push card
for card, n in person.hand
sendString += "#{n}) #{card}\n"
Cah.print sendString, msgObj
newRound = ->
Round.phase = "select"
Round.number++
Round.judge++
Round.judge = if Round.judge is Users.length then 0 else Round.judge
Round.hands = []
for user, key in Users
sendString = "Your hand for this round is:\n"
while user.hand.length < 8
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
user.hand.push card
Cah.used.push card
for card, n in user.hand
sendString += "#{n}) #{card}\n"
if key is Round.judge
sendString += "\n[b]You are the current judge.[/b]"
msgObj =
to:
id: user.name
type: "user"
Cah.print sendString, msgObj
black = BLACK_CARDS[~~(Math.random() * BLACK_CARDS.length)]
Round.card =
text: black.card
pick: black.pick
msgObj =
to:
type: "channel"
Cah.print(
"Judge: #{Users[Round.judge].name}\nRound [b]#{Round.number}[/b]\n" +
"Pick: #{Round.card.pick}\n" +
"Black Card: #{Round.card.text}"
, msgObj
)
gameInit = ->
Cah.used = []
for user, key in Users
user.hand = []
sendString = "Your hand for this round is:\n"
for n in [0...8]
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
Cah.used.push card
user.hand.push card
sendString += "#{n}) #{card}\n"
sendString = sendString.slice 0, sendString.length - 1
if key is Round.judge
sendString += "\n[b]You are the current judge.[/b]"
msgObj =
to:
id: user.name
type: "user"
Cah.print sendString, msgObj
black = BLACK_CARDS[~~(Math.random() * BLACK_CARDS.length)]
Round.card =
text: black.card
pick: black.pick
msgObj =
to:
type: "channel"
Cah.print(
"Judge: #{Users[Round.judge].name}\nPick: #{Round.card.pick}\n" +
"Black Card: #{Round.card.text}"
, msgObj
)
getPlayers = ->
players = []
players.push pObj.name for pObj in Users
return players
select = (cards, player) ->
isValid = false
isJudge = false
msgObj =
to:
type:"channel"
for user in Users
if user.name is player
pObj = user
isValid = true
isJudge = (Users[Round.judge].name is player)
break
if isJudge and Round.phase is "judge"
unless Round.hands[cards[0]]
return Cah.print(
"You cannot select a hand that doesn't exist.",
msgObj
)
for user in Users
if user.name is Round.hands[cards[0]].name
winner = user
winner.score += 1
Cah.print(
"#{winner.name} has won the round and has a total" +
" of [b]#{winner.score}[/b] points.",
msgObj
)
return newRound()
if Round.phase is "select" and isJudge
return Cah.print(
"You are this round's judge.",
msgObj
)
if Round.phase is "judge"
return Cah.print(
"You are not the judge.",
msgObj
)
unless isValid
return Cah.print(
"Cannot select when not in game.",
msgObj
)
if Phase is "judge"
return Cah.print(
"Cannot select within judgement phase.",
msgObj
)
unless Cah.inPlay
return Cah.print(
"Cannot select when a game is not active.",
msgObj
)
for hand in Round.hands
if hand.name is player
return Cah.print(
"You have already submitted your hand.",
msgObj
)
if cards.length isnt Round.card.pick
return Cah.print(
"Invalid card selection where the current card's pick number " +
"is #{Round.card.pick} and you selected #{cards.length}.",
msgObj
)
hand = {
name: <NAME>
cards: []
}
for card, val in cards
unless pObj.hand[card]
return Cah.print(
"Invalid selection: #{val}.",
msgObj
)
hand.cards.push pObj.hand[card]
for card, val in hand.cards
pObj.hand.splice pObj.hand.indexOf(card), 1
Cah.used.splice Cah.used.indexOf(card), 1
Round.hands.push hand
console.log Round.hands, hand
Cah.print "#{player} has submitted their hand.", msgObj
if Round.hands.length is Users.length - 1
Round.phase = "judge"
msg = "#{Users[Round.judge].name} please select a card combo:\n"
Round.hands = Round.hands.sort(
->
return ~~(Math.random() * 2)
)
for hand, key in Round.hands
msg += "#{key}) #{hand.cards.join ", "}\n"
msg = msg.slice 0, msg.length - 1
Cah.print msg, msgObj
funcs =
quit: (x, player, msgObj) ->
for user, key in Users
if user.name is player
uKey = key
break
msgObj =
to:
type:"channel"
for card in Users[uKey].hand
Cah.used.splice Cah.used.indexOf(card), 1
Users.splice uKey, 1
unless Cah.inPlay
return Cah.print "#{player} has left the game.", msgObj
if Users.length < 3 and Cah.inPlay
Cah.inPlay = false
Cah.used = []
Round.judge = 0
Round.number = 0
Round.card = null
Round.channel = null
return Cah.print(
"#{player} has left the game. Game cannot continue with " +
"less than 3 players. Reseting.",
msgObj
)
if Round.phase = "judge" and Round.judge is uKey
Cah.print(
"#{player} has left the game, and due to being the judge, the " +
"round must be reset.",
msgObj
)
return newRound()
Cah.print "#{player} has left the game.", msgObj
for hand, key in Round.hands
if hand.name is player
Round.hands.splice key, 1
break
if Round.hands.length is Users.length
Round.phase = "judge"
msg = "#{Users[Round.judge].name} please select a card combo:\n"
Round.hands = Round.hands.sort(
->
return ~~(Math.random() * 2)
)
for hand, key in Round.hands
msg += "#{key}) #{hand.hand.join ", "}\n"
msg = msg.slice 0, msg.length - 1
Cah.print msg, msgObj
join: (x, player, msgObj) ->
for user in Users
if user.name is <NAME>
return Cah.print "You are already in the game.", msgObj
pObj = {
name: <NAME>
score: 0
hand: []
}
Cah.users.push pObj
Round.channel = msgObj.to.id
if Cah.inPlay
createHand player
return Cah.print "#{player} has joined the game in progress.", msgObj
return Cah.print(
"#{player} has joined the game. Current players waiting to " +
"play: #{getPlayers().join(", ")}",
msgObj
)
start: (x, y, msgObj) ->
unless Users.length > 2
return Cah.print(
"You require at least three players to begin a game."
"play: #{getPlayers().join(", ")}",
msgObj
)
Cah.print "ROUND 1, FIGHT!", msgObj
Round.judge = ~~(Math.random() * Users.length)
Round.number = 1
Round.phase = "select"
Cah.inPlay = true
gameInit msgObj
# Main CAH handler
cah = (msg, msgObj) ->
msg = msg
.trim()
.replace new RegExp("/ +/", "g")
cmd = msg.split(" ")[0]
if msg.split(",").length > 1
msg = msg.split ","
msg[key] = parseInt(card, 10) for card, key in msg
select(msg, msgObj.from, msgObj)
return
unless isNaN parseInt(msg)
msg = [parseInt(msg, 10)]
select(msg, msgObj.from)
return
unless funcs[cmd]
return Cah.print "Wat?", msgObj
funcs[cmd] msg, msgObj.from, msgObj
return
return cah | true | do ->
KBot.Cah.users = []
KBot.Cah.hands = []
KBot.Cah.Round =
number: NaN
phase: "select"
hands: []
card: null
judge: 0
channel: null
KBot.Cah.used = []
KBot.Cah.inPlay = false
KBot.Cah.print = (msg, msgObj, qHandle) ->
if KBot.waitFor and not qHandle
return KBot.queue.push ->
KBot.Cah.print msg, msgObj, true
KBot.waitFor = true
if msgObj.to.type is "channel"
FList.Chat.printMessage
msg: "[b]K-CAH[/b]: #{msg}"
to: FList.Chat.TabBar.getTabFromId "channel", KBot.Cah.Round.channel
from: FList.Chat.identity
type: "chat"
FList.Connection.send "MSG " + JSON.stringify
"channel": KBot.Cah.Round.channel
"message": "[b]K-CAH[/b]: #{msg}"
else
FList.Connection.send "PRI " + JSON.stringify
"recipient": msgObj.to.id
"message": "[b]K-CAH[/b]: #{msg}"
KBot.Cmds.cah = do ->
Cmd = KBot.Cmds
Cah = KBot.Cah
Users = Cah.users
Round = Cah.Round
Phase = Round.phase
Hands = Round.hands
Chat = FList.Chat
BLACK_CARDS = Cah.Cards.BLACK_CARDS
WHITE_CARDS = Cah.Cards.WHITE_CARDS
createHand = (player) ->
msgObj =
to:
id: player
type: "user"
sendString = "Your hand for this round is:\n"
for user in Users
if user.name is player
person = user
break
while person.hand.length < 8
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
person.hand.push card
Cah.used.push card
for card, n in person.hand
sendString += "#{n}) #{card}\n"
Cah.print sendString, msgObj
newRound = ->
Round.phase = "select"
Round.number++
Round.judge++
Round.judge = if Round.judge is Users.length then 0 else Round.judge
Round.hands = []
for user, key in Users
sendString = "Your hand for this round is:\n"
while user.hand.length < 8
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
user.hand.push card
Cah.used.push card
for card, n in user.hand
sendString += "#{n}) #{card}\n"
if key is Round.judge
sendString += "\n[b]You are the current judge.[/b]"
msgObj =
to:
id: user.name
type: "user"
Cah.print sendString, msgObj
black = BLACK_CARDS[~~(Math.random() * BLACK_CARDS.length)]
Round.card =
text: black.card
pick: black.pick
msgObj =
to:
type: "channel"
Cah.print(
"Judge: #{Users[Round.judge].name}\nRound [b]#{Round.number}[/b]\n" +
"Pick: #{Round.card.pick}\n" +
"Black Card: #{Round.card.text}"
, msgObj
)
gameInit = ->
Cah.used = []
for user, key in Users
user.hand = []
sendString = "Your hand for this round is:\n"
for n in [0...8]
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
while Cah.used.indexOf(card) isnt -1
card = WHITE_CARDS[~~(Math.random() * WHITE_CARDS.length)]
Cah.used.push card
user.hand.push card
sendString += "#{n}) #{card}\n"
sendString = sendString.slice 0, sendString.length - 1
if key is Round.judge
sendString += "\n[b]You are the current judge.[/b]"
msgObj =
to:
id: user.name
type: "user"
Cah.print sendString, msgObj
black = BLACK_CARDS[~~(Math.random() * BLACK_CARDS.length)]
Round.card =
text: black.card
pick: black.pick
msgObj =
to:
type: "channel"
Cah.print(
"Judge: #{Users[Round.judge].name}\nPick: #{Round.card.pick}\n" +
"Black Card: #{Round.card.text}"
, msgObj
)
getPlayers = ->
players = []
players.push pObj.name for pObj in Users
return players
select = (cards, player) ->
isValid = false
isJudge = false
msgObj =
to:
type:"channel"
for user in Users
if user.name is player
pObj = user
isValid = true
isJudge = (Users[Round.judge].name is player)
break
if isJudge and Round.phase is "judge"
unless Round.hands[cards[0]]
return Cah.print(
"You cannot select a hand that doesn't exist.",
msgObj
)
for user in Users
if user.name is Round.hands[cards[0]].name
winner = user
winner.score += 1
Cah.print(
"#{winner.name} has won the round and has a total" +
" of [b]#{winner.score}[/b] points.",
msgObj
)
return newRound()
if Round.phase is "select" and isJudge
return Cah.print(
"You are this round's judge.",
msgObj
)
if Round.phase is "judge"
return Cah.print(
"You are not the judge.",
msgObj
)
unless isValid
return Cah.print(
"Cannot select when not in game.",
msgObj
)
if Phase is "judge"
return Cah.print(
"Cannot select within judgement phase.",
msgObj
)
unless Cah.inPlay
return Cah.print(
"Cannot select when a game is not active.",
msgObj
)
for hand in Round.hands
if hand.name is player
return Cah.print(
"You have already submitted your hand.",
msgObj
)
if cards.length isnt Round.card.pick
return Cah.print(
"Invalid card selection where the current card's pick number " +
"is #{Round.card.pick} and you selected #{cards.length}.",
msgObj
)
hand = {
name: PI:NAME:<NAME>END_PI
cards: []
}
for card, val in cards
unless pObj.hand[card]
return Cah.print(
"Invalid selection: #{val}.",
msgObj
)
hand.cards.push pObj.hand[card]
for card, val in hand.cards
pObj.hand.splice pObj.hand.indexOf(card), 1
Cah.used.splice Cah.used.indexOf(card), 1
Round.hands.push hand
console.log Round.hands, hand
Cah.print "#{player} has submitted their hand.", msgObj
if Round.hands.length is Users.length - 1
Round.phase = "judge"
msg = "#{Users[Round.judge].name} please select a card combo:\n"
Round.hands = Round.hands.sort(
->
return ~~(Math.random() * 2)
)
for hand, key in Round.hands
msg += "#{key}) #{hand.cards.join ", "}\n"
msg = msg.slice 0, msg.length - 1
Cah.print msg, msgObj
funcs =
quit: (x, player, msgObj) ->
for user, key in Users
if user.name is player
uKey = key
break
msgObj =
to:
type:"channel"
for card in Users[uKey].hand
Cah.used.splice Cah.used.indexOf(card), 1
Users.splice uKey, 1
unless Cah.inPlay
return Cah.print "#{player} has left the game.", msgObj
if Users.length < 3 and Cah.inPlay
Cah.inPlay = false
Cah.used = []
Round.judge = 0
Round.number = 0
Round.card = null
Round.channel = null
return Cah.print(
"#{player} has left the game. Game cannot continue with " +
"less than 3 players. Reseting.",
msgObj
)
if Round.phase = "judge" and Round.judge is uKey
Cah.print(
"#{player} has left the game, and due to being the judge, the " +
"round must be reset.",
msgObj
)
return newRound()
Cah.print "#{player} has left the game.", msgObj
for hand, key in Round.hands
if hand.name is player
Round.hands.splice key, 1
break
if Round.hands.length is Users.length
Round.phase = "judge"
msg = "#{Users[Round.judge].name} please select a card combo:\n"
Round.hands = Round.hands.sort(
->
return ~~(Math.random() * 2)
)
for hand, key in Round.hands
msg += "#{key}) #{hand.hand.join ", "}\n"
msg = msg.slice 0, msg.length - 1
Cah.print msg, msgObj
join: (x, player, msgObj) ->
for user in Users
if user.name is PI:NAME:<NAME>END_PI
return Cah.print "You are already in the game.", msgObj
pObj = {
name: PI:NAME:<NAME>END_PI
score: 0
hand: []
}
Cah.users.push pObj
Round.channel = msgObj.to.id
if Cah.inPlay
createHand player
return Cah.print "#{player} has joined the game in progress.", msgObj
return Cah.print(
"#{player} has joined the game. Current players waiting to " +
"play: #{getPlayers().join(", ")}",
msgObj
)
start: (x, y, msgObj) ->
unless Users.length > 2
return Cah.print(
"You require at least three players to begin a game."
"play: #{getPlayers().join(", ")}",
msgObj
)
Cah.print "ROUND 1, FIGHT!", msgObj
Round.judge = ~~(Math.random() * Users.length)
Round.number = 1
Round.phase = "select"
Cah.inPlay = true
gameInit msgObj
# Main CAH handler
cah = (msg, msgObj) ->
msg = msg
.trim()
.replace new RegExp("/ +/", "g")
cmd = msg.split(" ")[0]
if msg.split(",").length > 1
msg = msg.split ","
msg[key] = parseInt(card, 10) for card, key in msg
select(msg, msgObj.from, msgObj)
return
unless isNaN parseInt(msg)
msg = [parseInt(msg, 10)]
select(msg, msgObj.from)
return
unless funcs[cmd]
return Cah.print "Wat?", msgObj
funcs[cmd] msg, msgObj.from, msgObj
return
return cah |
[
{
"context": "###\nThe MIT License (MIT)\n\nCopyright (c) 2013 Tim Düsterhus\n\nPermission is hereby granted, free of charge, to",
"end": 59,
"score": 0.9998579025268555,
"start": 46,
"tag": "NAME",
"value": "Tim Düsterhus"
},
{
"context": "ile: false\n\t\t\n\t\t(validator [ 'company... | test/index.coffee | taylor987jack/qmail-aliasfilter-js | 1 | ###
The MIT License (MIT)
Copyright (c) 2013 Tim Düsterhus
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.
###
should = require 'should'
validator = require '../validator'
getRandomString = -> Math.random().toString(36).substring 2
describe 'validator', ->
it 'should return true on exact match', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'mymail-company.test@example.com' ], config).should.be.true
(validator [ 'example.com' ], [ 'mymail-example.com@example.com' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ random ], [ "mymail-#{random}@example.com" ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'mymail-company.test@example.com' ], config).should.be.true
(validator [ 'example.com' ], [ 'mymail-example.com@example.com' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ random ], [ "mymail-#{random}@example.com" ], config).should.be.true
it 'should return false on invalid exact match', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mail.company.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'example.net' ], [ 'mymail-example.com@example.com' ], config).should.be.false
random = "#{do getRandomString}.test"
random2 = "#{do getRandomString}.example"
(validator [ random ], [ "mymail-#{random2}@example.com" ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mail.company.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'example.net' ], [ 'mymail-example.com@example.com' ], config).should.be.false
random = "#{do getRandomString}.test"
random2 = "#{do getRandomString}.example"
(validator [ random ], [ "mymail-#{random2}@example.com" ], config).should.be.false
it 'should return true for any subdomain of a valid domain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.company.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.true
(validator [ 'mailer.example.com' ], [ 'mymail-.example.com@example.com' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ "#{do getRandomString}.#{random}" ], [ "mymail-.#{random}@example.com" ], config).should.be.true
config.validIfNotFound = true
(validator [ 'mail.company.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.true
(validator [ 'mailer.example.com' ], [ 'mymail-.example.com@example.com' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ "#{do getRandomString}.#{random}" ], [ "mymail-.#{random}@example.com" ], config).should.be.true
it 'should return false for any subdomain of an invalid domain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'mymail-example.com@example.com' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'mymail-.example.com@example.com' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mail.mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'mymail-example.com@example.com' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'mymail-.example.com@example.com' ], config).should.be.false
it 'should return false w/o subdomain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-.example.com@example.com' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'mymail-.company.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-.example.com@example.com' ], config).should.be.false
it 'should return true for any tld of a valid domain when valid domain ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'mymail-company.@example.com' ], config).should.be.true
(validator [ 'mail.company.test' ], [ 'mymail-mail.company.@example.com' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'mymail-company.@example.com' ], config).should.be.true
(validator [ 'mail.company.test' ], [ 'mymail-mail.company.@example.com' ], config).should.be.true
it 'should return false for any tld of an invalid domain when valid domain ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test' ], [ 'mymail-company.@example.com' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'mymail-mail.company.@example.com' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mycompany.test' ], [ 'mymail-company.@example.com' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'mymail-mail.company.@example.com' ], config).should.be.false
it 'should return true for any subdomain and tld of a valid domain when valid domain starts and ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.company.test' ], [ 'mymail-.company.@example.com' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'mymail-.company.@example.com' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'mail.company.test' ], [ 'mymail-.company.@example.com' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'mymail-.company.@example.com' ], config).should.be.true
it 'should return true for any subdomain and tld of an invalid domain when valid domain starts and ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.mycompany.test' ], [ 'mymail-.company.@example.com' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'mymail-.company.@example.com' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mail.mycompany.test' ], [ 'mymail-.company.@example.com' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'mymail-.company.@example.com' ], config).should.be.false
it 'should return true if at least one recipient matches and multipleToHandling is "validateOne"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-company.test@example.com' ], config).should.be.true
(validator [ 'example.com' ], [ 'mymail-example.com@example.com', 'mymail-.com@example.com' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-company.test@example.com' ], config).should.be.true
(validator [ 'example.com' ], [ 'mymail-example.com@example.com', 'mymail-.com@example.com' ], config).should.be.true
it 'should return false if no recipient (of multiple) matches', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-othercompany.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-example.org@example.com', 'mymail-example.net@example.com' ], config).should.be.false
config.multipleToHandling = "validateAll"
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-othercompany.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-example.org@example.com', 'mymail-example.net@example.com' ], config).should.be.false
config.validIfNotFound = true
config.multipleToHandling = "validateOne"
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-othercompany.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-example.org@example.com', 'mymail-example.net@example.com' ], config).should.be.false
config.multipleToHandling = "validateAll"
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-othercompany.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-example.org@example.com', 'mymail-example.net@example.com' ], config).should.be.false
it 'should return true if all recipients match and multipleToHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'mymail-.test@example.com', 'mymail-company.test@example.com' ], config).should.be.true
(validator [ 'example.com' ], [ 'mymail-example.com@example.com', 'mymail-.com@example.com' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'mymail-.test@example.com', 'mymail-company.test@example.com' ], config).should.be.true
(validator [ 'example.com' ], [ 'mymail-example.com@example.com', 'mymail-.com@example.com' ], config).should.be.true
it 'should return false if not all recipients match and multipleToHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-example.com@example.com', 'mymail-example.net@example.com' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'mymail-mycompany.test@example.com', 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'mymail-example.com@example.com', 'mymail-example.net@example.com' ], config).should.be.false
it 'should return false if mymail was not found and validIfNotFound is false', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'othermail@example.com' ], config).should.be.false
(validator [ 'example.com' ], [ 'othermail-example.com@example.com' ], config).should.be.false
it 'should return true if mymail was not found and validIfNotFound is true', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: true
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'othermail@example.com' ], config).should.be.true
(validator [ 'example.com' ], [ 'othermail-example.com@example.com' ], config).should.be.true
it 'should throw an error if the capturing group is missing', ->
(->
config =
mymail: /^mymail-.*@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
validator [ 'company.test' ], [ 'mymail-company.test@example.com' ], config
).should.throw()
it 'should return true if at least one of the senders match and multipleFromHandling is "validateOne"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateOne"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.com' ], [ 'mymail-company.test@example.com' ], config).should.be.true
(validator [ 'company.test', 'example.com' ], [ 'mymail-example.com@example.com' ], config).should.be.true
it 'should return false if at none of the senders match and multipleFromHandling is "validateOne" or "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateOne"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test', 'example.com' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'company.test', 'example.net' ], [ 'mymail-example.com@example.com' ], config).should.be.false
config.multipleFromHandling = "validateAll"
(validator [ 'mycompany.test', 'example.com' ], [ 'mymail-company.test@example.com' ], config).should.be.false
(validator [ 'company.test', 'example.net' ], [ 'mymail-example.com@example.com' ], config).should.be.false
it 'should return true if all of the senders match and multipleFromHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateAll"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.test' ], [ 'mymail-.test@example.com' ], config).should.be.true
it 'should return false if at least one of the senders does match and multipleFromHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateAll"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.com' ], [ 'mymail-company.test@example.com' ], config).should.be.false
| 115704 | ###
The MIT License (MIT)
Copyright (c) 2013 <NAME>
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.
###
should = require 'should'
validator = require '../validator'
getRandomString = -> Math.random().toString(36).substring 2
describe 'validator', ->
it 'should return true on exact match', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'example.com' ], [ '<EMAIL>' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ random ], [ "<EMAIL>" ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'example.com' ], [ '<EMAIL>' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ random ], [ "<EMAIL>" ], config).should.be.true
it 'should return false on invalid exact match', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'example.net' ], [ '<EMAIL>' ], config).should.be.false
random = "#{do getRandomString}.test"
random2 = "#{do getRandomString}.example"
(validator [ random ], [ "<EMAIL>" ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'example.net' ], [ '<EMAIL>' ], config).should.be.false
random = "#{do getRandomString}.test"
random2 = "#{do getRandomString}.example"
(validator [ random ], [ "<EMAIL>" ], config).should.be.false
it 'should return true for any subdomain of a valid domain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mailer.example.com' ], [ '<EMAIL>' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ "#{do getRandomString}.#{random}" ], [ "<EMAIL>" ], config).should.be.true
config.validIfNotFound = true
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mailer.example.com' ], [ '<EMAIL>' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ "#{do getRandomString}.#{random}" ], [ "<EMAIL>" ], config).should.be.true
it 'should return false for any subdomain of an invalid domain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'mymail-<EMAIL>' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ '<EMAIL>' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ '<EMAIL>' ], config).should.be.false
it 'should return false w/o subdomain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>' ], config).should.be.false
it 'should return true for any tld of a valid domain when valid domain ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
it 'should return false for any tld of an invalid domain when valid domain ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
it 'should return true for any subdomain and tld of a valid domain when valid domain starts and ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ '<EMAIL>' ], config).should.be.true
it 'should return true for any subdomain and tld of an invalid domain when valid domain starts and ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ '<EMAIL>' ], config).should.be.false
it 'should return true if at least one recipient matches and multipleToHandling is "validateOne"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
it 'should return false if no recipient (of multiple) matches', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
config.multipleToHandling = "validateAll"
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
config.validIfNotFound = true
config.multipleToHandling = "validateOne"
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
config.multipleToHandling = "validateAll"
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
(validator [ '<EMAIL>' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
it 'should return true if all recipients match and multipleToHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.true
it 'should return false if not all recipients match and multipleToHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'company.test' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>', '<EMAIL>' ], config).should.be.false
it 'should return false if mymail was not found and validIfNotFound is false', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'example.com' ], [ '<EMAIL>' ], config).should.be.false
it 'should return true if mymail was not found and validIfNotFound is true', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: true
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'example.com' ], [ '<EMAIL>' ], config).should.be.true
it 'should throw an error if the capturing group is missing', ->
(->
config =
mymail: /^mymail-.*@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
validator [ 'company.test' ], [ '<EMAIL>' ], config
).should.throw()
it 'should return true if at least one of the senders match and multipleFromHandling is "validateOne"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateOne"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.com' ], [ '<EMAIL>' ], config).should.be.true
(validator [ 'company.test', 'example.com' ], [ '<EMAIL>' ], config).should.be.true
it 'should return false if at none of the senders match and multipleFromHandling is "validateOne" or "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateOne"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test', 'example.com' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'company.test', 'example.net' ], [ '<EMAIL>' ], config).should.be.false
config.multipleFromHandling = "validateAll"
(validator [ 'mycompany.test', 'example.com' ], [ '<EMAIL>' ], config).should.be.false
(validator [ 'company.test', 'example.net' ], [ '<EMAIL>' ], config).should.be.false
it 'should return true if all of the senders match and multipleFromHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateAll"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.test' ], [ '<EMAIL>' ], config).should.be.true
it 'should return false if at least one of the senders does match and multipleFromHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateAll"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.com' ], [ '<EMAIL>' ], config).should.be.false
| true | ###
The MIT License (MIT)
Copyright (c) 2013 PI:NAME:<NAME>END_PI
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.
###
should = require 'should'
validator = require '../validator'
getRandomString = -> Math.random().toString(36).substring 2
describe 'validator', ->
it 'should return true on exact match', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ random ], [ "PI:EMAIL:<EMAIL>END_PI" ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ random ], [ "PI:EMAIL:<EMAIL>END_PI" ], config).should.be.true
it 'should return false on invalid exact match', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.net' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
random = "#{do getRandomString}.test"
random2 = "#{do getRandomString}.example"
(validator [ random ], [ "PI:EMAIL:<EMAIL>END_PI" ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.net' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
random = "#{do getRandomString}.test"
random2 = "#{do getRandomString}.example"
(validator [ random ], [ "PI:EMAIL:<EMAIL>END_PI" ], config).should.be.false
it 'should return true for any subdomain of a valid domain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mailer.example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ "#{do getRandomString}.#{random}" ], [ "PI:EMAIL:<EMAIL>END_PI" ], config).should.be.true
config.validIfNotFound = true
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mailer.example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
random = "#{do getRandomString}.test"
(validator [ "#{do getRandomString}.#{random}" ], [ "PI:EMAIL:<EMAIL>END_PI" ], config).should.be.true
it 'should return false for any subdomain of an invalid domain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'mymail-PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mailer.example.net' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return false w/o subdomain when valid domain starts with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return true for any tld of a valid domain when valid domain ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
it 'should return false for any tld of an invalid domain when valid domain ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return true for any subdomain and tld of a valid domain when valid domain starts and ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'mx5.mail.company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
it 'should return true for any subdomain and tld of an invalid domain when valid domain starts and ends with a dot', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'mx5.mail.mycompany.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return true if at least one recipient matches and multipleToHandling is "validateOne"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
it 'should return false if no recipient (of multiple) matches', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.multipleToHandling = "validateAll"
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.validIfNotFound = true
config.multipleToHandling = "validateOne"
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.multipleToHandling = "validateAll"
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'PI:EMAIL:<EMAIL>END_PI' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return true if all recipients match and multipleToHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
it 'should return false if not all recipients match and multipleToHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.validIfNotFound = true
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return false if mymail was not found and validIfNotFound is false', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return true if mymail was not found and validIfNotFound is true', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: true
multipleFromHandling: "drop"
multipleToHandling: "validateAll"
logFile: false
(validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
it 'should throw an error if the capturing group is missing', ->
(->
config =
mymail: /^mymail-.*@/
validIfNotFound: false
multipleFromHandling: "drop"
multipleToHandling: "validateOne"
logFile: false
validator [ 'company.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config
).should.throw()
it 'should return true if at least one of the senders match and multipleFromHandling is "validateOne"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateOne"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
(validator [ 'company.test', 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
it 'should return false if at none of the senders match and multipleFromHandling is "validateOne" or "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateOne"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'mycompany.test', 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'company.test', 'example.net' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
config.multipleFromHandling = "validateAll"
(validator [ 'mycompany.test', 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
(validator [ 'company.test', 'example.net' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
it 'should return true if all of the senders match and multipleFromHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateAll"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.test' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.true
it 'should return false if at least one of the senders does match and multipleFromHandling is "validateAll"', ->
config =
mymail: /^mymail-(.*)@/
validIfNotFound: false
multipleFromHandling: "validateAll"
multipleToHandling: "validateOne"
logFile: false
(validator [ 'company.test', 'example.com' ], [ 'PI:EMAIL:<EMAIL>END_PI' ], config).should.be.false
|
[
{
"context": " transportMethod: 'SMTP'\n auth:\n user: user\n pass: pass\n ndx.gmail =\n send: (ctx, ",
"end": 746,
"score": 0.9749056696891785,
"start": 742,
"tag": "USERNAME",
"value": "user"
},
{
"context": "SMTP'\n auth:\n user: user\n pa... | src/index.coffee | ndxbxrme/ndx-gmail | 0 | 'use strict'
mailer = require 'express-mailer'
module.exports = (ndx) ->
user = process.env.GMAIL_USER or ndx.settings.GMAIL_USER
pass = process.env.GMAIL_PASS or ndx.settings.GMAIL_PASS
fillTemplate = (template, data) ->
template.replace /\{\{(.+?)\}\}/g, (all, match) ->
evalInContext = (str, context) ->
(new Function("with(this) {return #{str}}"))
.call context
evalInContext match, data
callbacks =
send: []
error: []
safeCallback = (name, obj) ->
for cb in callbacks[name]
cb obj
if user and pass
mailer.extend ndx.app,
from: user
host: 'smtp.gmail.com'
secureConnection: false
port: 465
transportMethod: 'SMTP'
auth:
user: user
pass: pass
ndx.gmail =
send: (ctx, cb) ->
if user and pass
console.log 'sending', user, pass
if process.env.GMAIL_OVERRIDE
ctx.to = process.env.GMAIL_OVERRIDE
console.log 'to', ctx.to
if not process.env.GMAIL_DISABLE
console.log 'i want to send'
ndx.app.mailer.send ctx.template,
to: ctx.to
subject: fillTemplate ctx.subject, ctx
context: ctx
, (err, res) ->
console.log err, res
if err
safeCallback 'error', err
else
safeCallback 'send', res
cb? err, res
else
console.log 'sending email disabled'
else
console.log 'missing gmail info'
cb? 'no user' | 92549 | 'use strict'
mailer = require 'express-mailer'
module.exports = (ndx) ->
user = process.env.GMAIL_USER or ndx.settings.GMAIL_USER
pass = process.env.GMAIL_PASS or ndx.settings.GMAIL_PASS
fillTemplate = (template, data) ->
template.replace /\{\{(.+?)\}\}/g, (all, match) ->
evalInContext = (str, context) ->
(new Function("with(this) {return #{str}}"))
.call context
evalInContext match, data
callbacks =
send: []
error: []
safeCallback = (name, obj) ->
for cb in callbacks[name]
cb obj
if user and pass
mailer.extend ndx.app,
from: user
host: 'smtp.gmail.com'
secureConnection: false
port: 465
transportMethod: 'SMTP'
auth:
user: user
pass: <PASSWORD>
ndx.gmail =
send: (ctx, cb) ->
if user and pass
console.log 'sending', user, pass
if process.env.GMAIL_OVERRIDE
ctx.to = process.env.GMAIL_OVERRIDE
console.log 'to', ctx.to
if not process.env.GMAIL_DISABLE
console.log 'i want to send'
ndx.app.mailer.send ctx.template,
to: ctx.to
subject: fillTemplate ctx.subject, ctx
context: ctx
, (err, res) ->
console.log err, res
if err
safeCallback 'error', err
else
safeCallback 'send', res
cb? err, res
else
console.log 'sending email disabled'
else
console.log 'missing gmail info'
cb? 'no user' | true | 'use strict'
mailer = require 'express-mailer'
module.exports = (ndx) ->
user = process.env.GMAIL_USER or ndx.settings.GMAIL_USER
pass = process.env.GMAIL_PASS or ndx.settings.GMAIL_PASS
fillTemplate = (template, data) ->
template.replace /\{\{(.+?)\}\}/g, (all, match) ->
evalInContext = (str, context) ->
(new Function("with(this) {return #{str}}"))
.call context
evalInContext match, data
callbacks =
send: []
error: []
safeCallback = (name, obj) ->
for cb in callbacks[name]
cb obj
if user and pass
mailer.extend ndx.app,
from: user
host: 'smtp.gmail.com'
secureConnection: false
port: 465
transportMethod: 'SMTP'
auth:
user: user
pass: PI:PASSWORD:<PASSWORD>END_PI
ndx.gmail =
send: (ctx, cb) ->
if user and pass
console.log 'sending', user, pass
if process.env.GMAIL_OVERRIDE
ctx.to = process.env.GMAIL_OVERRIDE
console.log 'to', ctx.to
if not process.env.GMAIL_DISABLE
console.log 'i want to send'
ndx.app.mailer.send ctx.template,
to: ctx.to
subject: fillTemplate ctx.subject, ctx
context: ctx
, (err, res) ->
console.log err, res
if err
safeCallback 'error', err
else
safeCallback 'send', res
cb? err, res
else
console.log 'sending email disabled'
else
console.log 'missing gmail info'
cb? 'no user' |
[
{
"context": " `up.util.isBlank()`:\n\n ```\n foo = new Account('foo@foo.com')\n bar = new Account('')\n\n console.log(up.util.",
"end": 11184,
"score": 0.9998363256454468,
"start": 11173,
"tag": "EMAIL",
"value": "foo@foo.com"
},
{
"context": "sBlank.key\n @experimental\n ###\... | lib/assets/javascripts/unpoly/util.coffee | pfw/unpoly | 0 | ###**
Utility functions
=================
The `up.util` module contains functions to facilitate the work with basic JavaScript
values like lists, strings or functions.
You will recognize many functions form other utility libraries like [Lodash](https://lodash.com/).
While feature parity with Lodash is not a goal of `up.util`, you might find it sufficient
to not include another library in your asset bundle.
@module up.util
###
up.util = do ->
###**
A function that does nothing.
@function up.util.noop
@experimental
###
noop = (->)
###**
A function that returns a resolved promise.
@function up.util.asyncNoop
@internal
###
asyncNoop = -> Promise.resolve()
###**
Ensures that the given function can only be called a single time.
Subsequent calls will return the return value of the first call.
Note that this is a simple implementation that
doesn't distinguish between argument lists.
@function up.util.memoize
@internal
###
memoize = (func) ->
cachedValue = undefined
cached = false
(args...) ->
if cached
return cachedValue
else
cached = true
return cachedValue = func.apply(this, args)
###**
Returns if the given port is the default port for the given protocol.
@function up.util.isStandardPort
@internal
###
isStandardPort = (protocol, port) ->
port = port.toString()
((port == "" || port == "80") && protocol == 'http:') || (port == "443" && protocol == 'https:')
NORMALIZE_URL_DEFAULTS = {
host: 'cross-domain'
stripTrailingSlash: false
search: true
hash: false
}
###**
Normalizes the given URL or path.
@function up.util.normalizeURL
@param {boolean} [options.host='cross-domain']
Whether to include protocol, hostname and port in the normalized URL.
By default the host is only included if it differ's from the page's hostname.
@param {boolean} [options.hash=false]
Whether to include an `#hash` anchor in the normalized URL
@param {boolean} [options.search=true]
Whether to include a `?query` string in the normalized URL
@param {boolean} [options.stripTrailingSlash=false]
Whether to strip a trailing slash from the pathname
@return {string}
The normalized URL.
@internal
###
normalizeURL = (urlOrAnchor, options) ->
options = newOptions(options, NORMALIZE_URL_DEFAULTS)
parts = parseURL(urlOrAnchor)
normalized = ''
if options.host == 'cross-domain'
options.host = isCrossOrigin(parts)
if options.host
normalized += parts.protocol + "//" + parts.hostname
# Once we drop IE11 we can just use { host }, which contains port and hostname
# and also handles standard ports.
# See https://developer.mozilla.org/en-US/docs/Web/API/URL/host
unless isStandardPort(parts.protocol, parts.port)
normalized += ":#{parts.port}"
pathname = parts.pathname
if options.stripTrailingSlash
pathname = pathname.replace(/\/$/, '')
normalized += pathname
if options.search
normalized += parts.search
if options.hash
normalized += parts.hash
normalized
urlWithoutHost = (url) ->
normalizeURL(url, host: false)
matchURLs = (leftURL, rightURL) ->
return normalizeURL(leftURL) == normalizeURL(rightURL)
# We're calling isCrossOrigin() a lot.
# Accessing location.protocol and location.hostname every time
# is much slower than comparing cached strings.
# https://jsben.ch/kBATt
APP_PROTOCOL = location.protocol
APP_HOSTNAME = location.hostname
isCrossOrigin = (urlOrAnchor) ->
# If the given URL does not contain a hostname we know it cannot be cross-origin.
# In that case we don't need to parse the URL.
if isString(urlOrAnchor) && urlOrAnchor.indexOf('//') == -1
return false
parts = parseURL(urlOrAnchor)
return APP_HOSTNAME != parts.hostname || APP_PROTOCOL != parts.protocol
###**
Parses the given URL into components such as hostname and path.
If the given URL is not fully qualified, it is assumed to be relative
to the current page.
\#\#\# Example
```js
let parsed = up.util.parseURL('/path?foo=value')
parsed.pathname // => '/path'
parsed.search // => '/?foo=value'
parsed.hash // => ''
```
@function up.util.parseURL
@return {Object}
The parsed URL as an object with
`protocol`, `hostname`, `port`, `pathname`, `search` and `hash`
properties.
@stable
###
parseURL = (urlOrLink) ->
if isJQuery(urlOrLink)
# In case someone passed us a $link, unwrap it
link = up.element.get(urlOrLink)
else if urlOrLink.pathname
# If we are handed a parsed URL, just return it
link = urlOrLink
else
link = document.createElement('a')
link.href = urlOrLink
# In IE11 the #hostname and #port properties of unqualified URLs are empty strings.
# We can fix this by setting the link's { href } on the link itself.
unless link.hostname
link.href = link.href
# Some IEs don't include a leading slash in the #pathname property.
# We have confirmed this in IE11 and earlier.
unless link.pathname[0] == '/'
# Only copy the link into an object when we need to (to change a property).
# Note that we're parsing a lot of URLs for [up-active].
link = pick(link, ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash'])
link.pathname = '/' + link.pathname
link
###**
@function up.util.normalizeMethod
@internal
###
normalizeMethod = (method) ->
if method
method.toUpperCase()
else
'GET'
###**
@function up.util.methodAllowsPayload
@internal
###
methodAllowsPayload = (method) ->
method != 'GET' && method != 'HEAD'
# Remove with IE11
assignPolyfill = (target, sources...) ->
for source in sources
for own key, value of source
target[key] = value
target
###**
Merge the own properties of one or more `sources` into the `target` object.
@function up.util.assign
@param {Object} target
@param {Array<Object>} sources...
@stable
###
assign = Object.assign || assignPolyfill
# Remove with IE11
valuesPolyfill = (object) ->
value for key, value of object
###**
Returns an array of values of the given object.
@function up.util.values
@param {Object} object
@return {Array<string>}
@stable
###
objectValues = Object.values || valuesPolyfill
iteratee = (block) ->
if isString(block)
(item) -> item[block]
else
block
###**
Translate all items in an array to new array of items.
@function up.util.map
@param {Array} array
@param {Function(element, index): any|String} block
A function that will be called with each element and (optional) iteration index.
You can also pass a property name as a String,
which will be collected from each item in the array.
@return {Array}
A new array containing the result of each function call.
@stable
###
map = (array, block) ->
return [] if array.length == 0
block = iteratee(block)
for item, index in array
block(item, index)
###**
@function up.util.mapObject
@internal
###
mapObject = (array, pairer) ->
merger = (object, pair) ->
object[pair[0]] = pair[1]
return object
map(array, pairer).reduce(merger, {})
###**
Calls the given function for each element (and, optional, index)
of the given array.
@function up.util.each
@param {Array} array
@param {Function(element, index)} block
A function that will be called with each element and (optional) iteration index.
@stable
###
each = map # note that the native Array.forEach is very slow (https://jsperf.com/fast-array-foreach)
eachIterator = (iterator, callback) ->
while (entry = iterator.next()) && !entry.done
callback(entry.value)
###**
Calls the given function for the given number of times.
@function up.util.times
@param {number} count
@param {Function()} block
@stable
###
times = (count, block) ->
block(iteration) for iteration in [0..(count - 1)]
###**
Returns whether the given argument is `null`.
@function up.util.isNull
@param object
@return {boolean}
@stable
###
isNull = (object) ->
object == null
###**
Returns whether the given argument is `undefined`.
@function up.util.isUndefined
@param object
@return {boolean}
@stable
###
isUndefined = (object) ->
object == undefined
###**
Returns whether the given argument is not `undefined`.
@function up.util.isDefined
@param object
@return {boolean}
@stable
###
isDefined = (object) ->
!isUndefined(object)
###**
Returns whether the given argument is either `undefined` or `null`.
Note that empty strings or zero are *not* considered to be "missing".
For the opposite of `up.util.isMissing()` see [`up.util.isGiven()`](/up.util.isGiven).
@function up.util.isMissing
@param object
@return {boolean}
@stable
###
isMissing = (object) ->
isUndefined(object) || isNull(object)
###**
Returns whether the given argument is neither `undefined` nor `null`.
Note that empty strings or zero *are* considered to be "given".
For the opposite of `up.util.isGiven()` see [`up.util.isMissing()`](/up.util.isMissing).
@function up.util.isGiven
@param object
@return {boolean}
@stable
###
isGiven = (object) ->
!isMissing(object)
# isNan = (object) ->
# isNumber(value) && value != +value
###**
Return whether the given argument is considered to be blank.
By default, this function returns `true` for:
- `undefined`
- `null`
- Empty strings
- Empty arrays
- A plain object without own enumerable properties
All other arguments return `false`.
To check implement blank-ness checks for user-defined classes,
see `up.util.isBlank.key`.
@function up.util.isBlank
@param value
The value is to check.
@return {boolean}
Whether the value is blank.
@stable
###
isBlank = (value) ->
if isMissing(value)
return true
if isObject(value) && value[isBlank.key]
return value[isBlank.key]()
if isString(value) || isList(value)
return value.length == 0
if isOptions(value)
return Object.keys(value).length == 0
return false
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.isBlank()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.isBlank()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.isBlank.key]() {
return up.util.isBlank(this.email)
}
}
```
Note that the protocol method is not actually named `'up.util.isBlank.key'`.
Instead it is named after the *value* of the `up.util.isBlank.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.isBlank()`:
```
foo = new Account('foo@foo.com')
bar = new Account('')
console.log(up.util.isBlank(foo)) // prints false
console.log(up.util.isBlank(bar)) // prints true
```
@property up.util.isBlank.key
@experimental
###
isBlank.key = 'up.util.isBlank'
###**
Returns the given argument if the argument is [present](/up.util.isPresent),
otherwise returns `undefined`.
@function up.util.presence
@param value
@param {Function(value): boolean} [tester=up.util.isPresent]
The function that will be used to test whether the argument is present.
@return {any|undefined}
@stable
###
presence = (value, tester = isPresent) ->
if tester(value) then value else undefined
###**
Returns whether the given argument is not [blank](/up.util.isBlank).
@function up.util.isPresent
@param object
@return {boolean}
@stable
###
isPresent = (object) ->
!isBlank(object)
###**
Returns whether the given argument is a function.
@function up.util.isFunction
@param object
@return {boolean}
@stable
###
isFunction = (object) ->
typeof(object) == 'function'
###**
Returns whether the given argument is a string.
@function up.util.isString
@param object
@return {boolean}
@stable
###
isString = (object) ->
typeof(object) == 'string' || object instanceof String
###**
Returns whether the given argument is a boolean value.
@function up.util.isBoolean
@param object
@return {boolean}
@stable
###
isBoolean = (object) ->
typeof(object) == 'boolean' || object instanceof Boolean
###**
Returns whether the given argument is a number.
Note that this will check the argument's *type*.
It will return `false` for a string like `"123"`.
@function up.util.isNumber
@param object
@return {boolean}
@stable
###
isNumber = (object) ->
typeof(object) == 'number' || object instanceof Number
###**
Returns whether the given argument is an options hash,
Differently from [`up.util.isObject()`], this returns false for
functions, jQuery collections, promises, `FormData` instances and arrays.
@function up.util.isOptions
@param object
@return {boolean}
@internal
###
isOptions = (object) ->
typeof(object) == 'object' && !isNull(object) && (isUndefined(object.constructor) || object.constructor == Object)
###**
Returns whether the given argument is an object.
This also returns `true` for functions, which may behave like objects in JavaScript.
@function up.util.isObject
@param object
@return {boolean}
@stable
###
isObject = (object) ->
typeOfResult = typeof(object)
(typeOfResult == 'object' && !isNull(object)) || typeOfResult == 'function'
###**
Returns whether the given argument is a [DOM element](https://developer.mozilla.org/de/docs/Web/API/Element).
@function up.util.isElement
@param object
@return {boolean}
@stable
###
isElement = (object) ->
object instanceof Element
###**
Returns whether the given argument is a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).
@function up.util.isRegExp
@param object
@return {boolean}
@internal
###
isRegExp = (object) ->
object instanceof RegExp
###**
Returns whether the given argument is a [jQuery collection](https://learn.jquery.com/using-jquery-core/jquery-object/).
@function up.util.isJQuery
@param object
@return {boolean}
@stable
###
isJQuery = (object) ->
# We cannot do `object instanceof jQuery` since window.jQuery might not be set
!!object?.jquery
###**
@function up.util.isElementish
@param object
@return {boolean}
@internal
###
isElementish = (object) ->
!!(object && (object.addEventListener || object[0]?.addEventListener))
###**
Returns whether the given argument is an object with a `then` method.
@function up.util.isPromise
@param object
@return {boolean}
@stable
###
isPromise = (object) ->
isObject(object) && isFunction(object.then)
###**
Returns whether the given argument is an array.
@function up.util.isArray
@param object
@return {boolean}
@stable
###
# https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
isArray = Array.isArray
###**
Returns whether the given argument is a `FormData` instance.
Always returns `false` in browsers that don't support `FormData`.
@function up.util.isFormData
@param object
@return {boolean}
@internal
###
isFormData = (object) ->
object instanceof FormData
###**
Converts the given [array-like value](/up.util.isList) into an array.
If the given value is already an array, it is returned unchanged.
@function up.util.toArray
@param object
@return {Array}
@stable
###
toArray = (value) ->
if isArray(value)
value
else
copyArrayLike(value)
###**
Returns whether the given argument is an array-like value.
Return true for `Array`, a
[`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList),
the [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
or a jQuery collection.
Use [`up.util.isArray()`](/up.util.isArray) to test whether a value is an actual `Array`.
@function up.util.isList
@param value
@return {boolean}
@stable
###
isList = (value) ->
isArray(value) ||
isNodeList(value) ||
isArguments(value) ||
isJQuery(value) ||
isHTMLCollection(value)
###**
Returns whether the given value is a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList).
`NodeLists` are array-like objects returned by [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll).
@function up.util.isNodeList
@param value
@return {boolean}
@internal
###
isNodeList = (value) ->
value instanceof NodeList
isHTMLCollection = (value) ->
value instanceof HTMLCollection
###**
Returns whether the given value is an [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments).
@function up.util.isArguments
@param value
@return {boolean}
@internal
###
isArguments = (value) ->
Object.prototype.toString.call(value) == '[object Arguments]'
nullToUndefined = (value) ->
if isNull(value)
return undefined
else
return value
###**
Returns the given value if it is [array-like](/up.util.isList), otherwise
returns an array with the given value as its only element.
\#\#\# Example
```js
up.util.wrapList([1, 2, 3]) // => [1, 2, 3]
up.util.wrapList('foo') // => ['foo']
```
@function up.util.wrapList
@param {any} value
@return {Array|NodeList|jQuery}
@experimental
###
wrapList = (value) ->
if isList(value)
value
else if isMissing(value)
[]
else
[value]
###**
Returns a shallow copy of the given value.
\#\#\# Copying protocol
- By default `up.util.copy()` can copy [array-like values](/up.util.isList),
plain objects and `Date` instances.
- Array-like objects are copied into new arrays.
- Unsupported types of values are returned unchanged.
- To make the copying protocol work with user-defined class,
see `up.util.copy.key`.
- Immutable objects, like strings or numbers, do not need to be copied.
@function up.util.copy
@param {any} object
@return {any}
@stable
###
copy = (value) ->
if isObject(value) && value[copy.key]
value = value[copy.key]()
else if isList(value)
value = copyArrayLike(value)
# copied = true
else if isOptions(value)
value = assign({}, value)
# copied = true
# if copied && deep
# for k, v of value
# value[k] = copy(v, true)
value
copyArrayLike = (arrayLike) ->
Array.prototype.slice.call(arrayLike)
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.copy()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.copy()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.copy.key]() {
return new Account(this.email)
}
}
```
Note that the protocol method is not actually named `'up.util.copy.key'`.
Instead it is named after the *value* of the `up.util.copy.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.copy()`:
```
original = new User('foo@foo.com')
copy = up.util.copy(original)
console.log(copy.email) // prints 'foo@foo.com'
original.email = 'bar@bar.com' // change the original
console.log(copy.email) // still prints 'foo@foo.com'
```
@property up.util.copy.key
@param {string} key
@experimental
###
copy.key = 'up.util.copy'
# Implement up.util.copy protocol for Date
Date.prototype[copy.key] = -> new Date(+@)
# ###**
# Returns a deep copy of the given array or object.
#
# @function up.util.deepCopy
# @param {Object|Array} object
# @return {Object|Array}
# @internal
# ###
# deepCopy = (object) ->
# copy(object, true)
###**
Creates a new object by merging together the properties from the given objects.
@function up.util.merge
@param {Array<Object>} sources...
@return Object
@stable
###
merge = (sources...) ->
assign({}, sources...)
###**
@function up.util.mergeDefined
@param {Array<Object>} sources...
@return Object
@internal
###
mergeDefined = (sources...) ->
result = {}
for source in sources
if source
for key, value of source
if isDefined(value)
result[key] = value
result
# ###**
# Creates a new object by recursively merging together the properties from the given objects.
#
# @function up.util.deepMerge
# @param {Array<Object>} ...sources
# @return Object
#
# @internal
# ###
# deepMerge = (sources...) ->
# deepAssign({}, sources...)
#
# ###**
# @function up.util.deepAssign
# @param {Array<Object>} ...sources
# @return Object
# ###
# deepAssign = (target, sources...) ->
# for source in sources
# for key, newValue of source
# if isOptions(newValue)
# oldValue = target[key]
# if isOptions(oldValue)
# newValue = deepMerge(oldValue, newValue)
# target[key] = newValue
# target
###**
Creates an options hash from the given argument and some defaults.
The semantics of this function are confusing.
We want to get rid of this in the future.
@function up.util.options
@param {Object} object
@param {Object} [defaults]
@return {Object}
@internal
###
newOptions = (object, defaults) ->
if defaults
merge(defaults, object)
else if object
copy(object)
else
{}
parseArgIntoOptions = (args, argKey) ->
options = extractOptions(args)
if isDefined(args[0])
options = copy(options)
options[argKey] = args[0]
options
###**
Passes each element in the given [array-like value](/up.util.isList) to the given function.
Returns the first element for which the function returns a truthy value.
If no object matches, returns `undefined`.
@function up.util.find
@param {List<T>} list
@param {Function(value): boolean} tester
@return {T|undefined}
@stable
###
findInList = (list, tester) ->
tester = iteratee(tester)
match = undefined
for element in list
if tester(element)
match = element
break
match
###**
Returns whether the given function returns a truthy value
for any element in the given [array-like value](/up.util.isList).
@function up.util.some
@param {List} list
@param {Function(value, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@stable
###
some = (list, tester) ->
!!findResult(list, tester)
###**
Consecutively calls the given function which each element
in the given array. Returns the first truthy return value.
Returned `undefined` iff the function does not return a truthy
value for any element in the array.
@function up.util.findResult
@param {Array} array
@param {Function(element): any} tester
A function that will be called with each element and (optional) iteration index.
@return {any|undefined}
@experimental
###
findResult = (array, tester) ->
tester = iteratee(tester)
for element, index in array
if result = tester(element, index)
return result
return undefined
###**
Returns whether the given function returns a truthy value
for all elements in the given [array-like value](/up.util.isList).
@function up.util.every
@param {List} list
@param {Function(element, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@experimental
###
every = (list, tester) ->
tester = iteratee(tester)
match = true
for element, index in list
unless tester(element, index)
match = false
break
match
###**
Returns all elements from the given array that are
neither `null` or `undefined`.
@function up.util.compact
@param {Array<T>} array
@return {Array<T>}
@stable
###
compact = (array) ->
filterList array, isGiven
compactObject = (object) ->
pickBy(object, isGiven)
###**
Returns the given array without duplicates.
@function up.util.uniq
@param {Array<T>} array
@return {Array<T>}
@stable
###
uniq = (array) ->
return array if array.length < 2
setToArray(arrayToSet(array))
###**
This function is like [`uniq`](/up.util.uniq), accept that
the given function is invoked for each element to generate the value
for which uniquness is computed.
@function up.util.uniqBy
@param {Array} array
@param {Function(value): any} array
@return {Array}
@experimental
###
uniqBy = (array, mapper) ->
return array if array.length < 2
mapper = iteratee(mapper)
set = new Set()
filterList array, (elem, index) ->
mapped = mapper(elem, index)
if set.has(mapped)
false
else
set.add(mapped)
true
###**
@function up.util.setToArray
@internal
###
setToArray = (set) ->
array = []
set.forEach (elem) -> array.push(elem)
array
###**
@function up.util.arrayToSet
@internal
###
arrayToSet = (array) ->
set = new Set()
array.forEach (elem) -> set.add(elem)
set
###**
Returns all elements from the given [array-like value](/up.util.isList) that return
a truthy value when passed to the given function.
@function up.util.filter
@param {List} list
@param {Function(value, index): boolean} tester
@return {Array}
@stable
###
filterList = (list, tester) ->
tester = iteratee(tester)
matches = []
each list, (element, index) ->
if tester(element, index)
matches.push(element)
matches
###**
Returns all elements from the given [array-like value](/up.util.isList) that do not return
a truthy value when passed to the given function.
@function up.util.reject
@param {List} list
@param {Function(element, index): boolean} tester
@return {Array}
@stable
###
reject = (list, tester) ->
tester = iteratee(tester)
filterList(list, (element, index) -> !tester(element, index))
###**
Returns the intersection of the given two arrays.
Implementation is not optimized. Don't use it for large arrays.
@function up.util.intersect
@internal
###
intersect = (array1, array2) ->
filterList array1, (element) ->
contains(array2, element)
###**
Waits for the given number of milliseconds, the runs the given callback.
Instead of `up.util.timer(0, fn)` you can also use [`up.util.task(fn)`](/up.util.task).
@function up.util.timer
@param {number} millis
@param {Function()} callback
@return {number}
The ID of the scheduled timeout.
You may pass this ID to `clearTimeout()` to un-schedule the timeout.
@stable
###
scheduleTimer = (millis, callback) ->
setTimeout(callback, millis)
###**
Pushes the given function to the [JavaScript task queue](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) (also "macrotask queue").
Equivalent to calling `setTimeout(fn, 0)`.
Also see `up.util.microtask()`.
@function up.util.task
@param {Function()} block
@stable
###
queueTask = (block) ->
setTimeout(block, 0)
###**
Pushes the given function to the [JavaScript microtask queue](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/).
@function up.util.microtask
@param {Function()} task
@return {Promise}
A promise that is resolved with the return value of `task`.
If `task` throws an error, the promise is rejected with that error.
@experimental
###
queueMicrotask = (task) ->
return Promise.resolve().then(task)
abortableMicrotask = (task) ->
aborted = false
queueMicrotask(-> task() unless aborted)
return -> aborted = true
###**
Returns the last element of the given array.
@function up.util.last
@param {Array<T>} array
@return {T}
@stable
###
last = (array) ->
array[array.length - 1]
###**
Returns whether the given value contains another value.
If `value` is a string, this returns whether `subValue` is a sub-string of `value`.
If `value` is an array, this returns whether `subValue` is an element of `value`.
@function up.util.contains
@param {Array|string} value
@param {Array|string} subValue
@stable
###
contains = (value, subValue) ->
value.indexOf(subValue) >= 0
###**
Returns whether `object`'s entries are a superset
of `subObject`'s entries.
@function up.util.objectContains
@param {Object} object
@param {Object} subObject
@internal
###
objectContains = (object, subObject) ->
reducedValue = pick(object, Object.keys(subObject))
isEqual(subObject, reducedValue)
###**
Returns a copy of the given object that only contains
the given keys.
@function up.util.pick
@param {Object} object
@param {Array} keys
@return {Object}
@stable
###
pick = (object, keys) ->
filtered = {}
for key in keys
if key of object
filtered[key] = object[key]
filtered
###**
Returns a copy of the given object that only contains
properties that pass the given tester function.
@function up.util.pickBy
@param {Object} object
@param {Function<string, string, object>} tester
A function that will be called with each property.
The arguments are the property value, key and the entire object.
@return {Object}
@experimental
###
pickBy = (object, tester) ->
tester = iteratee(tester)
filtered = {}
for key, value of object
if tester(value, key, object)
filtered[key] = object[key]
return filtered
###**
Returns a copy of the given object that contains all except
the given keys.
@function up.util.omit
@param {Object} object
@param {Array} keys
@stable
###
omit = (object, keys) ->
pickBy(object, (value, key) -> !contains(keys, key))
###**
Returns a promise that will never be resolved.
@function up.util.unresolvablePromise
@internal
###
unresolvablePromise = ->
new Promise(noop)
###**
Removes the given element from the given array.
This changes the given array.
@function up.util.remove
@param {Array<T>} array
The array to change.
@param {T} element
The element to remove.
@return {T|undefined}
The removed element, or `undefined` if the array didn't contain the element.
@stable
###
remove = (array, element) ->
index = array.indexOf(element)
if index >= 0
array.splice(index, 1)
return element
###**
If the given `value` is a function, calls the function with the given `args`.
Otherwise it just returns `value`.
\#\#\# Example
```js
up.util.evalOption(5) // => 5
let fn = () => 1 + 2
up.util.evalOption(fn) // => 3
```
@function up.util.evalOption
@param {any} value
@param {Array} ...args
@return {any}
@experimental
###
evalOption = (value, args...) ->
if isFunction(value)
value(args...)
else
value
ESCAPE_HTML_ENTITY_MAP =
"&": "&"
"<": "<"
">": ">"
'"': '"'
"'": '''
###**
Escapes the given string of HTML by replacing control chars with their HTML entities.
@function up.util.escapeHTML
@param {string} string
The text that should be escaped.
@stable
###
escapeHTML = (string) ->
string.replace /[&<>"']/g, (char) -> ESCAPE_HTML_ENTITY_MAP[char]
###**
@function up.util.escapeRegExp
@internal
###
escapeRegExp = (string) ->
# From https://github.com/benjamingr/RegExp.escape
string.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&')
###**
Deletes the property with the given key from the given object
and returns its value.
@function up.util.pluckKey
@param {Object} object
@param {string} key
@return {any}
@experimental
###
pluckKey = (object, key) ->
value = object[key]
delete object[key]
value
renameKey = (object, oldKey, newKey) ->
object[newKey] = pluckKey(object, oldKey)
extractLastArg = (args, tester) ->
lastArg = last(args)
if tester(lastArg)
return args.pop()
# extractFirstArg = (args, tester) ->
# firstArg = args[0]
# if tester(firstArg)
# return args.shift()
extractCallback = (args) ->
extractLastArg(args, isFunction)
extractOptions = (args) ->
extractLastArg(args, isOptions) || {}
# partial = (fn, fixedArgs...) ->
# return (callArgs...) ->
# fn.apply(this, fixedArgs.concat(callArgs))
#
# partialRight = (fn, fixedArgs...) ->
# return (callArgs...) ->
# fn.apply(this, callArgs.concat(fixedArgs))
#function throttle(callback, limit) { // From https://jsfiddle.net/jonathansampson/m7G64/
# var wait = false // Initially, we're not waiting
# return function () { // We return a throttled function
# if (!wait) { // If we're not waiting
# callback.call() // Execute users function
# wait = true // Prevent future invocations
# setTimeout(function () { // After a period of time
# wait = false // And allow future invocations
# }, limit)
# }
# }
#}
identity = (arg) -> arg
# ###**
# ###
# parsePath = (input) ->
# path = []
# pattern = /([^\.\[\]\"\']+)|\[\'([^\']+?)\'\]|\[\"([^\"]+?)\"\]|\[([^\]]+?)\]/g
# while match = pattern.exec(input)
# path.push(match[1] || match[2] || match[3] || match[4])
# path
# ###**
# Given an async function that will return a promise, returns a proxy function
# with an additional `.promise` attribute.
#
# When the proxy is called, the inner function is called.
# The proxy's `.promise` attribute is available even before the function is called
# and will resolve when the inner function's returned promise resolves.
#
# If the inner function does not return a promise, the proxy's `.promise` attribute
# will resolve as soon as the inner function returns.
#
# @function up.util.previewable
# @internal
# ###
# previewable = (fun) ->
# deferred = newDeferred()
# preview = (args...) ->
# funValue = fun(args...)
# # If funValue is again a Promise, it will defer resolution of `deferred`
# # until `funValue` is resolved.
# deferred.resolve(funValue)
# funValue
# preview.promise = deferred.promise()
# preview
###**
@function up.util.sequence
@param {Array<Function()>} functions
@return {Function()}
A function that will call all `functions` if called.
@internal
###
sequence = (functions) ->
if functions.length == 1
return functions[0]
else
return -> map(functions, (f) -> f())
# ###**
# @function up.util.race
# @internal
# ###
# race = (promises...) ->
# raceDone = newDeferred()
# each promises, (promise) ->
# promise.then -> raceDone.resolve()
# raceDone.promise()
# ###**
# Returns `'left'` if the center of the given element is in the left 50% of the screen.
# Otherwise returns `'right'`.
#
# @function up.util.horizontalScreenHalf
# @internal
# ###
# horizontalScreenHalf = (element) ->
# elementDims = element.getBoundingClientRect()
# elementMid = elementDims.left + 0.5 * elementDims.width
# screenMid = 0.5 * up.viewport.rootWidth()
# if elementMid < screenMid
# 'left'
# else
# 'right'
###**
Flattens the given `array` a single depth level.
\#\#\# Example
```js
let nested = [1, [2, 3], [4]]
up.util.flatten(nested) // => [1, 2, 3, 4]
@function up.util.flatten
@param {Array} array
An array which might contain other arrays
@return {Array}
The flattened array
@experimental
###
flatten = (array) ->
flattened = []
for object in array
if isList(object)
flattened.push(object...)
else
flattened.push(object)
flattened
# flattenObject = (object) ->
# result = {}
# for key, value of object
# result[key] = value
# result
###**
Maps each element using a mapping function,
then [flattens](/up.util.flatten) the result into a new array.
@function up.util.flatMap
@param {Array} array
@param {Function(element)} mapping
@return {Array}
@experimental
###
flatMap = (array, block) ->
flatten map(array, block)
###**
Returns whether the given value is truthy.
@function up.util.isTruthy
@internal
###
isTruthy = (object) ->
!!object
###**
Sets the given callback as both fulfillment and rejection handler for the given promise.
[Unlike `promise#finally()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally#Description), `up.util.always()` may change the settlement value
of the given promise.
@function up.util.always
@internal
###
always = (promise, callback) ->
promise.then(callback, callback)
# mutedFinally = (promise, callback) ->
# # Use finally() instead of always() so we don't accidentally
# # register a rejection handler, which would prevent an "Uncaught in Exception" error.
# finallyDone = promise.finally(callback)
#
# # Since finally's return value is itself a promise with the same state
# # as `promise`, we don't want to see "Uncaught in Exception".
# # If we didn't do this, we couldn't mute rejections in `promise`:
# #
# # promise = new Promise(...)
# # promise.finally(function() { ... })
# # up.util.muteRejection(promise) // has no effect
# muteRejection(finallyDone)
#
# # Return the original promise and *not* finally's return value.
# return promise
###**
Registers an empty rejection handler with the given promise.
This prevents browsers from printing "Uncaught (in promise)" to the error
console when the promise is rejected.
This is helpful for event handlers where it is clear that no rejection
handler will be registered:
up.on('submit', 'form[up-target]', (event, $form) => {
promise = up.submit($form)
up.util.muteRejection(promise)
})
Does nothing if passed a missing value.
@function up.util.muteRejection
@param {Promise|undefined|null} promise
@return {Promise}
@internal
###
muteRejection = (promise) ->
return promise?.catch(noop)
###**
@function up.util.newDeferred
@internal
###
newDeferred = ->
resolveFn = undefined
rejectFn = undefined
nativePromise = new Promise (givenResolve, givenReject) ->
resolveFn = givenResolve
rejectFn = givenReject
nativePromise.resolve = resolveFn
nativePromise.reject = rejectFn
nativePromise.promise = -> nativePromise # just return self
nativePromise
# ###**
# Calls the given block. If the block throws an exception,
# a rejected promise is returned instead.
#
# @function up.util.rejectOnError
# @internal
# ###
# rejectOnError = (block) ->
# try
# block()
# catch error
# Promise.reject(error)
asyncify = (block) ->
# The side effects of this should be sync, otherwise we could
# just do `Promise.resolve().then(block)`.
try
return Promise.resolve(block())
catch error
return Promise.reject(error)
# sum = (list, block) ->
# block = iteratee(block)
# totalValue = 0
# for entry in list
# entryValue = block(entry)
# if isGiven(entryValue) # ignore undefined/null, like SQL would do
# totalValue += entryValue
# totalValue
isBasicObjectProperty = (k) ->
Object.prototype.hasOwnProperty(k)
###**
Returns whether the two arguments are equal by value.
\#\#\# Comparison protocol
- By default `up.util.isEqual()` can compare strings, numbers,
[array-like values](/up.util.isList), plain objects and `Date` objects.
- To make the copying protocol work with user-defined classes,
see `up.util.isEqual.key`.
- Objects without a defined comparison protocol are
defined by reference (`===`).
@function up.util.isEqual
@param {any} a
@param {any} b
@return {boolean}
Whether the arguments are equal by value.
@experimental
###
isEqual = (a, b) ->
a = a.valueOf() if a?.valueOf # Date, String objects, Number objects
b = b.valueOf() if b?.valueOf # Date, String objects, Number objects
if typeof(a) != typeof(b)
false
else if isList(a) && isList(b)
isEqualList(a, b)
else if isObject(a) && a[isEqual.key]
a[isEqual.key](b)
else if isOptions(a) && isOptions(b)
aKeys = Object.keys(a)
bKeys = Object.keys(b)
if isEqualList(aKeys, bKeys)
every aKeys, (aKey) -> isEqual(a[aKey], b[aKey])
else
false
else
a == b
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.isEqual()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.isEqual()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.isEqual.key](other) {
return this.email === other.email;
}
}
```
Note that the protocol method is not actually named `'up.util.isEqual.key'`.
Instead it is named after the *value* of the `up.util.isEqual.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.isEqual()`:
```
one = new User('foo@foo.com')
two = new User('foo@foo.com')
three = new User('bar@bar.com')
isEqual = up.util.isEqual(one, two)
// isEqual is now true
isEqual = up.util.isEqual(one, three)
// isEqual is now false
```
@property up.util.isEqual.key
@param {string} key
@experimental
###
isEqual.key = 'up.util.isEqual'
isEqualList = (a, b) ->
a.length == b.length && every(a, (elem, index) -> isEqual(elem, b[index]))
splitValues = (value, separator = ' ') ->
if isString(value)
value = value.split(separator)
value = map value, (v) -> v.trim()
value = filterList(value, isPresent)
value
else
wrapList(value)
endsWith = (string, search) ->
if search.length > string.length
false
else
string.substring(string.length - search.length) == search
simpleEase = (x) ->
# easing: http://fooplot.com/?lang=de#W3sidHlwZSI6MCwiZXEiOiJ4PDAuNT8yKngqeDp4Kig0LXgqMiktMSIsImNvbG9yIjoiIzEzRjIxNyJ9LHsidHlwZSI6MCwiZXEiOiJzaW4oKHheMC43LTAuNSkqcGkpKjAuNSswLjUiLCJjb2xvciI6IiMxQTUyRUQifSx7InR5cGUiOjEwMDAsIndpbmRvdyI6WyItMS40NyIsIjEuNzgiLCItMC41NSIsIjEuNDUiXX1d
# easing nice: sin((x^0.7-0.5)*pi)*0.5+0.5
# easing performant: x < 0.5 ? 2*x*x : x*(4 - x*2)-1
# https://jsperf.com/easings/1
# Math.sin((Math.pow(x, 0.7) - 0.5) * Math.PI) * 0.5 + 0.5
if x < 0.5
2*x*x
else
x*(4 - x*2)-1
wrapValue = (constructor, args...) ->
if args[0] instanceof constructor
# This object has gone through instantiation and normalization before.
args[0]
else
new constructor(args...)
# wrapArray = (objOrArray) ->
# if isUndefined(objOrArray)
# []
# else if isArray(objOrArray)
# objOrArray
# else
# [objOrArray]
nextUid = 0
uid = ->
nextUid++
###**
Returns a copy of the given list, in reversed order.
@function up.util.reverse
@param {List<T>} list
@return {Array<T>}
@internal
###
reverse = (list) ->
copy(list).reverse()
# ###**
# Returns a copy of the given `object` with the given `prefix` removed
# from its camel-cased keys.
#
# @function up.util.unprefixKeys
# @param {Object} object
# @param {string} prefix
# @return {Object}
# @internal
# ###
# unprefixKeys = (object, prefix) ->
# unprefixed = {}
# prefixLength = prefix.length
# for key, value of object
# if key.indexOf(prefix) == 0
# key = unprefixCamelCase(key, prefixLength)
# unprefixed[key] = value
# unprefixed
# replaceValue = (value, matchValue, replaceValueFn) ->
# if value == matchValue
# return replaceValueFn()
# else
# return value
renameKeys = (object, renameKeyFn) ->
renamed = {}
for key, value of object
renamed[renameKeyFn(key)] = value
return renamed
camelToKebabCase = (str) ->
str.replace /[A-Z]/g, (char) -> '-' + char.toLowerCase()
prefixCamelCase = (str, prefix) ->
prefix + upperCaseFirst(str)
unprefixCamelCase = (str, prefix) ->
pattern = new RegExp('^' + prefix + '(.+)$')
if match = str.match(pattern)
return lowerCaseFirst(match[1])
lowerCaseFirst = (str) ->
str[0].toLowerCase() + str.slice(1)
upperCaseFirst = (str) ->
str[0].toUpperCase() + str.slice(1)
defineGetter = (object, prop, get) ->
Object.defineProperty(object, prop, { get })
defineDelegates = (object, props, targetProvider) ->
wrapList(props).forEach (prop) ->
Object.defineProperty object, prop,
get: ->
target = targetProvider.call(this)
value = target[prop]
if isFunction(value)
value = value.bind(target)
return value
set: (newValue) ->
target = targetProvider.call(this)
target[prop] = newValue
literal = (obj) ->
result = {}
for key, value of obj
if unprefixedKey = unprefixCamelCase(key, 'get_')
defineGetter(result, unprefixedKey, value)
else
result[key] = value
result
stringifyArg = (arg) ->
maxLength = 200
closer = ''
if isString(arg)
string = arg.replace(/[\n\r\t ]+/g, ' ')
string = string.replace(/^[\n\r\t ]+/, '')
string = string.replace(/[\n\r\t ]$/, '')
# string = "\"#{string}\""
# closer = '"'
else if isUndefined(arg)
# JSON.stringify(undefined) is actually undefined
string = 'undefined'
else if isNumber(arg) || isFunction(arg)
string = arg.toString()
else if isArray(arg)
string = "[#{map(arg, stringifyArg).join(', ')}]"
closer = ']'
else if isJQuery(arg)
string = "$(#{map(arg, stringifyArg).join(', ')})"
closer = ')'
else if isElement(arg)
string = "<#{arg.tagName.toLowerCase()}"
for attr in ['id', 'name', 'class']
if value = arg.getAttribute(attr)
string += " #{attr}=\"#{value}\""
string += ">"
closer = '>'
else if isRegExp(arg)
string = arg.toString()
else # object, array
try
string = JSON.stringify(arg)
catch error
if error.name == 'TypeError'
string = '(circular structure)'
else
throw error
if string.length > maxLength
string = "#{string.substr(0, maxLength)} …"
string += closer
string
SPRINTF_PLACEHOLDERS = /\%[oOdisf]/g
secondsSinceEpoch = ->
Math.floor(Date.now() * 0.001)
###**
See https://developer.mozilla.org/en-US/docs/Web/API/Console#Using_string_substitutions
@function up.util.sprintf
@internal
###
sprintf = (message, args...) ->
sprintfWithFormattedArgs(identity, message, args...)
###**
@function up.util.sprintfWithFormattedArgs
@internal
###
sprintfWithFormattedArgs = (formatter, message, args...) ->
return '' unless message
i = 0
message.replace SPRINTF_PLACEHOLDERS, ->
arg = args[i]
arg = formatter(stringifyArg(arg))
i += 1
arg
# Remove with IE11.
# When removed we can also remove muteRejection(), as this is the only caller.
allSettled = (promises) ->
return Promise.all(map(promises, muteRejection))
parseURL: parseURL
normalizeURL: normalizeURL
urlWithoutHost: urlWithoutHost
matchURLs: matchURLs
normalizeMethod: normalizeMethod
methodAllowsPayload: methodAllowsPayload
# isGoodSelector: isGoodSelector
assign: assign
assignPolyfill: assignPolyfill
copy: copy
copyArrayLike: copyArrayLike
# deepCopy: deepCopy
merge: merge
mergeDefined: mergeDefined
# deepAssign: deepAssign
# deepMerge: deepMerge
options: newOptions
parseArgIntoOptions: parseArgIntoOptions
each: each
eachIterator: eachIterator
map: map
flatMap: flatMap
mapObject: mapObject
times: times
findResult: findResult
some: some
every: every
find: findInList
filter: filterList
reject: reject
intersect: intersect
compact: compact
compactObject: compactObject
uniq: uniq
uniqBy: uniqBy
last: last
isNull: isNull
isDefined: isDefined
isUndefined: isUndefined
isGiven: isGiven
isMissing: isMissing
isPresent: isPresent
isBlank: isBlank
presence: presence
isObject: isObject
isFunction: isFunction
isString: isString
isBoolean: isBoolean
isNumber: isNumber
isElement: isElement
isJQuery: isJQuery
isElementish: isElementish
isPromise: isPromise
isOptions: isOptions
isArray: isArray
isFormData: isFormData
isNodeList: isNodeList
isArguments: isArguments
isList: isList
isRegExp: isRegExp
timer: scheduleTimer
contains: contains
objectContains: objectContains
toArray: toArray
pick: pick
pickBy: pickBy
omit: omit
unresolvablePromise: unresolvablePromise
remove: remove
memoize: memoize
pluckKey: pluckKey
renameKey: renameKey
extractOptions: extractOptions
extractCallback: extractCallback
noop: noop
asyncNoop: asyncNoop
identity: identity
escapeHTML: escapeHTML
escapeRegExp: escapeRegExp
sequence: sequence
# previewable: previewable
# parsePath: parsePath
evalOption: evalOption
# horizontalScreenHalf: horizontalScreenHalf
flatten: flatten
# flattenObject: flattenObject
isTruthy: isTruthy
newDeferred: newDeferred
always: always
# mutedFinally: mutedFinally
muteRejection: muteRejection
# rejectOnError: rejectOnError
asyncify: asyncify
isBasicObjectProperty: isBasicObjectProperty
isCrossOrigin: isCrossOrigin
task: queueTask
microtask: queueMicrotask
abortableMicrotask: abortableMicrotask
isEqual: isEqual
splitValues : splitValues
endsWith: endsWith
# sum: sum
# wrapArray: wrapArray
wrapList: wrapList
wrapValue: wrapValue
simpleEase: simpleEase
values: objectValues
# partial: partial
# partialRight: partialRight
arrayToSet: arrayToSet
setToArray: setToArray
# unprefixKeys: unprefixKeys
uid: uid
upperCaseFirst: upperCaseFirst
lowerCaseFirst: lowerCaseFirst
getter: defineGetter
delegate: defineDelegates
literal: literal
# asyncWrap: asyncWrap
reverse: reverse
prefixCamelCase: prefixCamelCase
unprefixCamelCase: unprefixCamelCase
camelToKebabCase: camelToKebabCase
nullToUndefined: nullToUndefined
sprintf: sprintf
sprintfWithFormattedArgs: sprintfWithFormattedArgs
renameKeys: renameKeys
timestamp: secondsSinceEpoch
allSettled: allSettled
| 38591 | ###**
Utility functions
=================
The `up.util` module contains functions to facilitate the work with basic JavaScript
values like lists, strings or functions.
You will recognize many functions form other utility libraries like [Lodash](https://lodash.com/).
While feature parity with Lodash is not a goal of `up.util`, you might find it sufficient
to not include another library in your asset bundle.
@module up.util
###
up.util = do ->
###**
A function that does nothing.
@function up.util.noop
@experimental
###
noop = (->)
###**
A function that returns a resolved promise.
@function up.util.asyncNoop
@internal
###
asyncNoop = -> Promise.resolve()
###**
Ensures that the given function can only be called a single time.
Subsequent calls will return the return value of the first call.
Note that this is a simple implementation that
doesn't distinguish between argument lists.
@function up.util.memoize
@internal
###
memoize = (func) ->
cachedValue = undefined
cached = false
(args...) ->
if cached
return cachedValue
else
cached = true
return cachedValue = func.apply(this, args)
###**
Returns if the given port is the default port for the given protocol.
@function up.util.isStandardPort
@internal
###
isStandardPort = (protocol, port) ->
port = port.toString()
((port == "" || port == "80") && protocol == 'http:') || (port == "443" && protocol == 'https:')
NORMALIZE_URL_DEFAULTS = {
host: 'cross-domain'
stripTrailingSlash: false
search: true
hash: false
}
###**
Normalizes the given URL or path.
@function up.util.normalizeURL
@param {boolean} [options.host='cross-domain']
Whether to include protocol, hostname and port in the normalized URL.
By default the host is only included if it differ's from the page's hostname.
@param {boolean} [options.hash=false]
Whether to include an `#hash` anchor in the normalized URL
@param {boolean} [options.search=true]
Whether to include a `?query` string in the normalized URL
@param {boolean} [options.stripTrailingSlash=false]
Whether to strip a trailing slash from the pathname
@return {string}
The normalized URL.
@internal
###
normalizeURL = (urlOrAnchor, options) ->
options = newOptions(options, NORMALIZE_URL_DEFAULTS)
parts = parseURL(urlOrAnchor)
normalized = ''
if options.host == 'cross-domain'
options.host = isCrossOrigin(parts)
if options.host
normalized += parts.protocol + "//" + parts.hostname
# Once we drop IE11 we can just use { host }, which contains port and hostname
# and also handles standard ports.
# See https://developer.mozilla.org/en-US/docs/Web/API/URL/host
unless isStandardPort(parts.protocol, parts.port)
normalized += ":#{parts.port}"
pathname = parts.pathname
if options.stripTrailingSlash
pathname = pathname.replace(/\/$/, '')
normalized += pathname
if options.search
normalized += parts.search
if options.hash
normalized += parts.hash
normalized
urlWithoutHost = (url) ->
normalizeURL(url, host: false)
matchURLs = (leftURL, rightURL) ->
return normalizeURL(leftURL) == normalizeURL(rightURL)
# We're calling isCrossOrigin() a lot.
# Accessing location.protocol and location.hostname every time
# is much slower than comparing cached strings.
# https://jsben.ch/kBATt
APP_PROTOCOL = location.protocol
APP_HOSTNAME = location.hostname
isCrossOrigin = (urlOrAnchor) ->
# If the given URL does not contain a hostname we know it cannot be cross-origin.
# In that case we don't need to parse the URL.
if isString(urlOrAnchor) && urlOrAnchor.indexOf('//') == -1
return false
parts = parseURL(urlOrAnchor)
return APP_HOSTNAME != parts.hostname || APP_PROTOCOL != parts.protocol
###**
Parses the given URL into components such as hostname and path.
If the given URL is not fully qualified, it is assumed to be relative
to the current page.
\#\#\# Example
```js
let parsed = up.util.parseURL('/path?foo=value')
parsed.pathname // => '/path'
parsed.search // => '/?foo=value'
parsed.hash // => ''
```
@function up.util.parseURL
@return {Object}
The parsed URL as an object with
`protocol`, `hostname`, `port`, `pathname`, `search` and `hash`
properties.
@stable
###
parseURL = (urlOrLink) ->
if isJQuery(urlOrLink)
# In case someone passed us a $link, unwrap it
link = up.element.get(urlOrLink)
else if urlOrLink.pathname
# If we are handed a parsed URL, just return it
link = urlOrLink
else
link = document.createElement('a')
link.href = urlOrLink
# In IE11 the #hostname and #port properties of unqualified URLs are empty strings.
# We can fix this by setting the link's { href } on the link itself.
unless link.hostname
link.href = link.href
# Some IEs don't include a leading slash in the #pathname property.
# We have confirmed this in IE11 and earlier.
unless link.pathname[0] == '/'
# Only copy the link into an object when we need to (to change a property).
# Note that we're parsing a lot of URLs for [up-active].
link = pick(link, ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash'])
link.pathname = '/' + link.pathname
link
###**
@function up.util.normalizeMethod
@internal
###
normalizeMethod = (method) ->
if method
method.toUpperCase()
else
'GET'
###**
@function up.util.methodAllowsPayload
@internal
###
methodAllowsPayload = (method) ->
method != 'GET' && method != 'HEAD'
# Remove with IE11
assignPolyfill = (target, sources...) ->
for source in sources
for own key, value of source
target[key] = value
target
###**
Merge the own properties of one or more `sources` into the `target` object.
@function up.util.assign
@param {Object} target
@param {Array<Object>} sources...
@stable
###
assign = Object.assign || assignPolyfill
# Remove with IE11
valuesPolyfill = (object) ->
value for key, value of object
###**
Returns an array of values of the given object.
@function up.util.values
@param {Object} object
@return {Array<string>}
@stable
###
objectValues = Object.values || valuesPolyfill
iteratee = (block) ->
if isString(block)
(item) -> item[block]
else
block
###**
Translate all items in an array to new array of items.
@function up.util.map
@param {Array} array
@param {Function(element, index): any|String} block
A function that will be called with each element and (optional) iteration index.
You can also pass a property name as a String,
which will be collected from each item in the array.
@return {Array}
A new array containing the result of each function call.
@stable
###
map = (array, block) ->
return [] if array.length == 0
block = iteratee(block)
for item, index in array
block(item, index)
###**
@function up.util.mapObject
@internal
###
mapObject = (array, pairer) ->
merger = (object, pair) ->
object[pair[0]] = pair[1]
return object
map(array, pairer).reduce(merger, {})
###**
Calls the given function for each element (and, optional, index)
of the given array.
@function up.util.each
@param {Array} array
@param {Function(element, index)} block
A function that will be called with each element and (optional) iteration index.
@stable
###
each = map # note that the native Array.forEach is very slow (https://jsperf.com/fast-array-foreach)
eachIterator = (iterator, callback) ->
while (entry = iterator.next()) && !entry.done
callback(entry.value)
###**
Calls the given function for the given number of times.
@function up.util.times
@param {number} count
@param {Function()} block
@stable
###
times = (count, block) ->
block(iteration) for iteration in [0..(count - 1)]
###**
Returns whether the given argument is `null`.
@function up.util.isNull
@param object
@return {boolean}
@stable
###
isNull = (object) ->
object == null
###**
Returns whether the given argument is `undefined`.
@function up.util.isUndefined
@param object
@return {boolean}
@stable
###
isUndefined = (object) ->
object == undefined
###**
Returns whether the given argument is not `undefined`.
@function up.util.isDefined
@param object
@return {boolean}
@stable
###
isDefined = (object) ->
!isUndefined(object)
###**
Returns whether the given argument is either `undefined` or `null`.
Note that empty strings or zero are *not* considered to be "missing".
For the opposite of `up.util.isMissing()` see [`up.util.isGiven()`](/up.util.isGiven).
@function up.util.isMissing
@param object
@return {boolean}
@stable
###
isMissing = (object) ->
isUndefined(object) || isNull(object)
###**
Returns whether the given argument is neither `undefined` nor `null`.
Note that empty strings or zero *are* considered to be "given".
For the opposite of `up.util.isGiven()` see [`up.util.isMissing()`](/up.util.isMissing).
@function up.util.isGiven
@param object
@return {boolean}
@stable
###
isGiven = (object) ->
!isMissing(object)
# isNan = (object) ->
# isNumber(value) && value != +value
###**
Return whether the given argument is considered to be blank.
By default, this function returns `true` for:
- `undefined`
- `null`
- Empty strings
- Empty arrays
- A plain object without own enumerable properties
All other arguments return `false`.
To check implement blank-ness checks for user-defined classes,
see `up.util.isBlank.key`.
@function up.util.isBlank
@param value
The value is to check.
@return {boolean}
Whether the value is blank.
@stable
###
isBlank = (value) ->
if isMissing(value)
return true
if isObject(value) && value[isBlank.key]
return value[isBlank.key]()
if isString(value) || isList(value)
return value.length == 0
if isOptions(value)
return Object.keys(value).length == 0
return false
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.isBlank()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.isBlank()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.isBlank.key]() {
return up.util.isBlank(this.email)
}
}
```
Note that the protocol method is not actually named `'up.util.isBlank.key'`.
Instead it is named after the *value* of the `up.util.isBlank.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.isBlank()`:
```
foo = new Account('<EMAIL>')
bar = new Account('')
console.log(up.util.isBlank(foo)) // prints false
console.log(up.util.isBlank(bar)) // prints true
```
@property up.util.isBlank.key
@experimental
###
isBlank.key = '<KEY>'
###**
Returns the given argument if the argument is [present](/up.util.isPresent),
otherwise returns `undefined`.
@function up.util.presence
@param value
@param {Function(value): boolean} [tester=up.util.isPresent]
The function that will be used to test whether the argument is present.
@return {any|undefined}
@stable
###
presence = (value, tester = isPresent) ->
if tester(value) then value else undefined
###**
Returns whether the given argument is not [blank](/up.util.isBlank).
@function up.util.isPresent
@param object
@return {boolean}
@stable
###
isPresent = (object) ->
!isBlank(object)
###**
Returns whether the given argument is a function.
@function up.util.isFunction
@param object
@return {boolean}
@stable
###
isFunction = (object) ->
typeof(object) == 'function'
###**
Returns whether the given argument is a string.
@function up.util.isString
@param object
@return {boolean}
@stable
###
isString = (object) ->
typeof(object) == 'string' || object instanceof String
###**
Returns whether the given argument is a boolean value.
@function up.util.isBoolean
@param object
@return {boolean}
@stable
###
isBoolean = (object) ->
typeof(object) == 'boolean' || object instanceof Boolean
###**
Returns whether the given argument is a number.
Note that this will check the argument's *type*.
It will return `false` for a string like `"123"`.
@function up.util.isNumber
@param object
@return {boolean}
@stable
###
isNumber = (object) ->
typeof(object) == 'number' || object instanceof Number
###**
Returns whether the given argument is an options hash,
Differently from [`up.util.isObject()`], this returns false for
functions, jQuery collections, promises, `FormData` instances and arrays.
@function up.util.isOptions
@param object
@return {boolean}
@internal
###
isOptions = (object) ->
typeof(object) == 'object' && !isNull(object) && (isUndefined(object.constructor) || object.constructor == Object)
###**
Returns whether the given argument is an object.
This also returns `true` for functions, which may behave like objects in JavaScript.
@function up.util.isObject
@param object
@return {boolean}
@stable
###
isObject = (object) ->
typeOfResult = typeof(object)
(typeOfResult == 'object' && !isNull(object)) || typeOfResult == 'function'
###**
Returns whether the given argument is a [DOM element](https://developer.mozilla.org/de/docs/Web/API/Element).
@function up.util.isElement
@param object
@return {boolean}
@stable
###
isElement = (object) ->
object instanceof Element
###**
Returns whether the given argument is a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).
@function up.util.isRegExp
@param object
@return {boolean}
@internal
###
isRegExp = (object) ->
object instanceof RegExp
###**
Returns whether the given argument is a [jQuery collection](https://learn.jquery.com/using-jquery-core/jquery-object/).
@function up.util.isJQuery
@param object
@return {boolean}
@stable
###
isJQuery = (object) ->
# We cannot do `object instanceof jQuery` since window.jQuery might not be set
!!object?.jquery
###**
@function up.util.isElementish
@param object
@return {boolean}
@internal
###
isElementish = (object) ->
!!(object && (object.addEventListener || object[0]?.addEventListener))
###**
Returns whether the given argument is an object with a `then` method.
@function up.util.isPromise
@param object
@return {boolean}
@stable
###
isPromise = (object) ->
isObject(object) && isFunction(object.then)
###**
Returns whether the given argument is an array.
@function up.util.isArray
@param object
@return {boolean}
@stable
###
# https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
isArray = Array.isArray
###**
Returns whether the given argument is a `FormData` instance.
Always returns `false` in browsers that don't support `FormData`.
@function up.util.isFormData
@param object
@return {boolean}
@internal
###
isFormData = (object) ->
object instanceof FormData
###**
Converts the given [array-like value](/up.util.isList) into an array.
If the given value is already an array, it is returned unchanged.
@function up.util.toArray
@param object
@return {Array}
@stable
###
toArray = (value) ->
if isArray(value)
value
else
copyArrayLike(value)
###**
Returns whether the given argument is an array-like value.
Return true for `Array`, a
[`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList),
the [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
or a jQuery collection.
Use [`up.util.isArray()`](/up.util.isArray) to test whether a value is an actual `Array`.
@function up.util.isList
@param value
@return {boolean}
@stable
###
isList = (value) ->
isArray(value) ||
isNodeList(value) ||
isArguments(value) ||
isJQuery(value) ||
isHTMLCollection(value)
###**
Returns whether the given value is a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList).
`NodeLists` are array-like objects returned by [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll).
@function up.util.isNodeList
@param value
@return {boolean}
@internal
###
isNodeList = (value) ->
value instanceof NodeList
isHTMLCollection = (value) ->
value instanceof HTMLCollection
###**
Returns whether the given value is an [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments).
@function up.util.isArguments
@param value
@return {boolean}
@internal
###
isArguments = (value) ->
Object.prototype.toString.call(value) == '[object Arguments]'
nullToUndefined = (value) ->
if isNull(value)
return undefined
else
return value
###**
Returns the given value if it is [array-like](/up.util.isList), otherwise
returns an array with the given value as its only element.
\#\#\# Example
```js
up.util.wrapList([1, 2, 3]) // => [1, 2, 3]
up.util.wrapList('foo') // => ['foo']
```
@function up.util.wrapList
@param {any} value
@return {Array|NodeList|jQuery}
@experimental
###
wrapList = (value) ->
if isList(value)
value
else if isMissing(value)
[]
else
[value]
###**
Returns a shallow copy of the given value.
\#\#\# Copying protocol
- By default `up.util.copy()` can copy [array-like values](/up.util.isList),
plain objects and `Date` instances.
- Array-like objects are copied into new arrays.
- Unsupported types of values are returned unchanged.
- To make the copying protocol work with user-defined class,
see `up.util.copy.key`.
- Immutable objects, like strings or numbers, do not need to be copied.
@function up.util.copy
@param {any} object
@return {any}
@stable
###
copy = (value) ->
if isObject(value) && value[copy.key]
value = value[copy.key]()
else if isList(value)
value = copyArrayLike(value)
# copied = true
else if isOptions(value)
value = assign({}, value)
# copied = true
# if copied && deep
# for k, v of value
# value[k] = copy(v, true)
value
copyArrayLike = (arrayLike) ->
Array.prototype.slice.call(arrayLike)
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.copy()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.copy()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.copy.key]() {
return new Account(this.email)
}
}
```
Note that the protocol method is not actually named `'up.util.copy.key'`.
Instead it is named after the *value* of the `up.util.copy.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.copy()`:
```
original = new User('<EMAIL>')
copy = up.util.copy(original)
console.log(copy.email) // prints '<EMAIL>'
original.email = '<EMAIL>' // change the original
console.log(copy.email) // still prints '<EMAIL>'
```
@property up.util.copy.key
@param {string} key
@experimental
###
copy.key = '<KEY>'
# Implement up.util.copy protocol for Date
Date.prototype[copy.key] = -> new Date(+@)
# ###**
# Returns a deep copy of the given array or object.
#
# @function up.util.deepCopy
# @param {Object|Array} object
# @return {Object|Array}
# @internal
# ###
# deepCopy = (object) ->
# copy(object, true)
###**
Creates a new object by merging together the properties from the given objects.
@function up.util.merge
@param {Array<Object>} sources...
@return Object
@stable
###
merge = (sources...) ->
assign({}, sources...)
###**
@function up.util.mergeDefined
@param {Array<Object>} sources...
@return Object
@internal
###
mergeDefined = (sources...) ->
result = {}
for source in sources
if source
for key, value of source
if isDefined(value)
result[key] = value
result
# ###**
# Creates a new object by recursively merging together the properties from the given objects.
#
# @function up.util.deepMerge
# @param {Array<Object>} ...sources
# @return Object
#
# @internal
# ###
# deepMerge = (sources...) ->
# deepAssign({}, sources...)
#
# ###**
# @function up.util.deepAssign
# @param {Array<Object>} ...sources
# @return Object
# ###
# deepAssign = (target, sources...) ->
# for source in sources
# for key, newValue of source
# if isOptions(newValue)
# oldValue = target[key]
# if isOptions(oldValue)
# newValue = deepMerge(oldValue, newValue)
# target[key] = newValue
# target
###**
Creates an options hash from the given argument and some defaults.
The semantics of this function are confusing.
We want to get rid of this in the future.
@function up.util.options
@param {Object} object
@param {Object} [defaults]
@return {Object}
@internal
###
newOptions = (object, defaults) ->
if defaults
merge(defaults, object)
else if object
copy(object)
else
{}
parseArgIntoOptions = (args, argKey) ->
options = extractOptions(args)
if isDefined(args[0])
options = copy(options)
options[argKey] = args[0]
options
###**
Passes each element in the given [array-like value](/up.util.isList) to the given function.
Returns the first element for which the function returns a truthy value.
If no object matches, returns `undefined`.
@function up.util.find
@param {List<T>} list
@param {Function(value): boolean} tester
@return {T|undefined}
@stable
###
findInList = (list, tester) ->
tester = iteratee(tester)
match = undefined
for element in list
if tester(element)
match = element
break
match
###**
Returns whether the given function returns a truthy value
for any element in the given [array-like value](/up.util.isList).
@function up.util.some
@param {List} list
@param {Function(value, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@stable
###
some = (list, tester) ->
!!findResult(list, tester)
###**
Consecutively calls the given function which each element
in the given array. Returns the first truthy return value.
Returned `undefined` iff the function does not return a truthy
value for any element in the array.
@function up.util.findResult
@param {Array} array
@param {Function(element): any} tester
A function that will be called with each element and (optional) iteration index.
@return {any|undefined}
@experimental
###
findResult = (array, tester) ->
tester = iteratee(tester)
for element, index in array
if result = tester(element, index)
return result
return undefined
###**
Returns whether the given function returns a truthy value
for all elements in the given [array-like value](/up.util.isList).
@function up.util.every
@param {List} list
@param {Function(element, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@experimental
###
every = (list, tester) ->
tester = iteratee(tester)
match = true
for element, index in list
unless tester(element, index)
match = false
break
match
###**
Returns all elements from the given array that are
neither `null` or `undefined`.
@function up.util.compact
@param {Array<T>} array
@return {Array<T>}
@stable
###
compact = (array) ->
filterList array, isGiven
compactObject = (object) ->
pickBy(object, isGiven)
###**
Returns the given array without duplicates.
@function up.util.uniq
@param {Array<T>} array
@return {Array<T>}
@stable
###
uniq = (array) ->
return array if array.length < 2
setToArray(arrayToSet(array))
###**
This function is like [`uniq`](/up.util.uniq), accept that
the given function is invoked for each element to generate the value
for which uniquness is computed.
@function up.util.uniqBy
@param {Array} array
@param {Function(value): any} array
@return {Array}
@experimental
###
uniqBy = (array, mapper) ->
return array if array.length < 2
mapper = iteratee(mapper)
set = new Set()
filterList array, (elem, index) ->
mapped = mapper(elem, index)
if set.has(mapped)
false
else
set.add(mapped)
true
###**
@function up.util.setToArray
@internal
###
setToArray = (set) ->
array = []
set.forEach (elem) -> array.push(elem)
array
###**
@function up.util.arrayToSet
@internal
###
arrayToSet = (array) ->
set = new Set()
array.forEach (elem) -> set.add(elem)
set
###**
Returns all elements from the given [array-like value](/up.util.isList) that return
a truthy value when passed to the given function.
@function up.util.filter
@param {List} list
@param {Function(value, index): boolean} tester
@return {Array}
@stable
###
filterList = (list, tester) ->
tester = iteratee(tester)
matches = []
each list, (element, index) ->
if tester(element, index)
matches.push(element)
matches
###**
Returns all elements from the given [array-like value](/up.util.isList) that do not return
a truthy value when passed to the given function.
@function up.util.reject
@param {List} list
@param {Function(element, index): boolean} tester
@return {Array}
@stable
###
reject = (list, tester) ->
tester = iteratee(tester)
filterList(list, (element, index) -> !tester(element, index))
###**
Returns the intersection of the given two arrays.
Implementation is not optimized. Don't use it for large arrays.
@function up.util.intersect
@internal
###
intersect = (array1, array2) ->
filterList array1, (element) ->
contains(array2, element)
###**
Waits for the given number of milliseconds, the runs the given callback.
Instead of `up.util.timer(0, fn)` you can also use [`up.util.task(fn)`](/up.util.task).
@function up.util.timer
@param {number} millis
@param {Function()} callback
@return {number}
The ID of the scheduled timeout.
You may pass this ID to `clearTimeout()` to un-schedule the timeout.
@stable
###
scheduleTimer = (millis, callback) ->
setTimeout(callback, millis)
###**
Pushes the given function to the [JavaScript task queue](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) (also "macrotask queue").
Equivalent to calling `setTimeout(fn, 0)`.
Also see `up.util.microtask()`.
@function up.util.task
@param {Function()} block
@stable
###
queueTask = (block) ->
setTimeout(block, 0)
###**
Pushes the given function to the [JavaScript microtask queue](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/).
@function up.util.microtask
@param {Function()} task
@return {Promise}
A promise that is resolved with the return value of `task`.
If `task` throws an error, the promise is rejected with that error.
@experimental
###
queueMicrotask = (task) ->
return Promise.resolve().then(task)
abortableMicrotask = (task) ->
aborted = false
queueMicrotask(-> task() unless aborted)
return -> aborted = true
###**
Returns the last element of the given array.
@function up.util.last
@param {Array<T>} array
@return {T}
@stable
###
last = (array) ->
array[array.length - 1]
###**
Returns whether the given value contains another value.
If `value` is a string, this returns whether `subValue` is a sub-string of `value`.
If `value` is an array, this returns whether `subValue` is an element of `value`.
@function up.util.contains
@param {Array|string} value
@param {Array|string} subValue
@stable
###
contains = (value, subValue) ->
value.indexOf(subValue) >= 0
###**
Returns whether `object`'s entries are a superset
of `subObject`'s entries.
@function up.util.objectContains
@param {Object} object
@param {Object} subObject
@internal
###
objectContains = (object, subObject) ->
reducedValue = pick(object, Object.keys(subObject))
isEqual(subObject, reducedValue)
###**
Returns a copy of the given object that only contains
the given keys.
@function up.util.pick
@param {Object} object
@param {Array} keys
@return {Object}
@stable
###
pick = (object, keys) ->
filtered = {}
for key in keys
if key of object
filtered[key] = object[key]
filtered
###**
Returns a copy of the given object that only contains
properties that pass the given tester function.
@function up.util.pickBy
@param {Object} object
@param {Function<string, string, object>} tester
A function that will be called with each property.
The arguments are the property value, key and the entire object.
@return {Object}
@experimental
###
pickBy = (object, tester) ->
tester = iteratee(tester)
filtered = {}
for key, value of object
if tester(value, key, object)
filtered[key] = object[key]
return filtered
###**
Returns a copy of the given object that contains all except
the given keys.
@function up.util.omit
@param {Object} object
@param {Array} keys
@stable
###
omit = (object, keys) ->
pickBy(object, (value, key) -> !contains(keys, key))
###**
Returns a promise that will never be resolved.
@function up.util.unresolvablePromise
@internal
###
unresolvablePromise = ->
new Promise(noop)
###**
Removes the given element from the given array.
This changes the given array.
@function up.util.remove
@param {Array<T>} array
The array to change.
@param {T} element
The element to remove.
@return {T|undefined}
The removed element, or `undefined` if the array didn't contain the element.
@stable
###
remove = (array, element) ->
index = array.indexOf(element)
if index >= 0
array.splice(index, 1)
return element
###**
If the given `value` is a function, calls the function with the given `args`.
Otherwise it just returns `value`.
\#\#\# Example
```js
up.util.evalOption(5) // => 5
let fn = () => 1 + 2
up.util.evalOption(fn) // => 3
```
@function up.util.evalOption
@param {any} value
@param {Array} ...args
@return {any}
@experimental
###
evalOption = (value, args...) ->
if isFunction(value)
value(args...)
else
value
ESCAPE_HTML_ENTITY_MAP =
"&": "&"
"<": "<"
">": ">"
'"': '"'
"'": '''
###**
Escapes the given string of HTML by replacing control chars with their HTML entities.
@function up.util.escapeHTML
@param {string} string
The text that should be escaped.
@stable
###
escapeHTML = (string) ->
string.replace /[&<>"']/g, (char) -> ESCAPE_HTML_ENTITY_MAP[char]
###**
@function up.util.escapeRegExp
@internal
###
escapeRegExp = (string) ->
# From https://github.com/benjamingr/RegExp.escape
string.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&')
###**
Deletes the property with the given key from the given object
and returns its value.
@function up.util.pluckKey
@param {Object} object
@param {string} key
@return {any}
@experimental
###
pluckKey = (object, key) ->
value = object[key]
delete object[key]
value
renameKey = (object, oldKey, newKey) ->
object[newKey] = pluckKey(object, oldKey)
extractLastArg = (args, tester) ->
lastArg = last(args)
if tester(lastArg)
return args.pop()
# extractFirstArg = (args, tester) ->
# firstArg = args[0]
# if tester(firstArg)
# return args.shift()
extractCallback = (args) ->
extractLastArg(args, isFunction)
extractOptions = (args) ->
extractLastArg(args, isOptions) || {}
# partial = (fn, fixedArgs...) ->
# return (callArgs...) ->
# fn.apply(this, fixedArgs.concat(callArgs))
#
# partialRight = (fn, fixedArgs...) ->
# return (callArgs...) ->
# fn.apply(this, callArgs.concat(fixedArgs))
#function throttle(callback, limit) { // From https://jsfiddle.net/jonathansampson/m7G64/
# var wait = false // Initially, we're not waiting
# return function () { // We return a throttled function
# if (!wait) { // If we're not waiting
# callback.call() // Execute users function
# wait = true // Prevent future invocations
# setTimeout(function () { // After a period of time
# wait = false // And allow future invocations
# }, limit)
# }
# }
#}
identity = (arg) -> arg
# ###**
# ###
# parsePath = (input) ->
# path = []
# pattern = /([^\.\[\]\"\']+)|\[\'([^\']+?)\'\]|\[\"([^\"]+?)\"\]|\[([^\]]+?)\]/g
# while match = pattern.exec(input)
# path.push(match[1] || match[2] || match[3] || match[4])
# path
# ###**
# Given an async function that will return a promise, returns a proxy function
# with an additional `.promise` attribute.
#
# When the proxy is called, the inner function is called.
# The proxy's `.promise` attribute is available even before the function is called
# and will resolve when the inner function's returned promise resolves.
#
# If the inner function does not return a promise, the proxy's `.promise` attribute
# will resolve as soon as the inner function returns.
#
# @function up.util.previewable
# @internal
# ###
# previewable = (fun) ->
# deferred = newDeferred()
# preview = (args...) ->
# funValue = fun(args...)
# # If funValue is again a Promise, it will defer resolution of `deferred`
# # until `funValue` is resolved.
# deferred.resolve(funValue)
# funValue
# preview.promise = deferred.promise()
# preview
###**
@function up.util.sequence
@param {Array<Function()>} functions
@return {Function()}
A function that will call all `functions` if called.
@internal
###
sequence = (functions) ->
if functions.length == 1
return functions[0]
else
return -> map(functions, (f) -> f())
# ###**
# @function up.util.race
# @internal
# ###
# race = (promises...) ->
# raceDone = newDeferred()
# each promises, (promise) ->
# promise.then -> raceDone.resolve()
# raceDone.promise()
# ###**
# Returns `'left'` if the center of the given element is in the left 50% of the screen.
# Otherwise returns `'right'`.
#
# @function up.util.horizontalScreenHalf
# @internal
# ###
# horizontalScreenHalf = (element) ->
# elementDims = element.getBoundingClientRect()
# elementMid = elementDims.left + 0.5 * elementDims.width
# screenMid = 0.5 * up.viewport.rootWidth()
# if elementMid < screenMid
# 'left'
# else
# 'right'
###**
Flattens the given `array` a single depth level.
\#\#\# Example
```js
let nested = [1, [2, 3], [4]]
up.util.flatten(nested) // => [1, 2, 3, 4]
@function up.util.flatten
@param {Array} array
An array which might contain other arrays
@return {Array}
The flattened array
@experimental
###
flatten = (array) ->
flattened = []
for object in array
if isList(object)
flattened.push(object...)
else
flattened.push(object)
flattened
# flattenObject = (object) ->
# result = {}
# for key, value of object
# result[key] = value
# result
###**
Maps each element using a mapping function,
then [flattens](/up.util.flatten) the result into a new array.
@function up.util.flatMap
@param {Array} array
@param {Function(element)} mapping
@return {Array}
@experimental
###
flatMap = (array, block) ->
flatten map(array, block)
###**
Returns whether the given value is truthy.
@function up.util.isTruthy
@internal
###
isTruthy = (object) ->
!!object
###**
Sets the given callback as both fulfillment and rejection handler for the given promise.
[Unlike `promise#finally()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally#Description), `up.util.always()` may change the settlement value
of the given promise.
@function up.util.always
@internal
###
always = (promise, callback) ->
promise.then(callback, callback)
# mutedFinally = (promise, callback) ->
# # Use finally() instead of always() so we don't accidentally
# # register a rejection handler, which would prevent an "Uncaught in Exception" error.
# finallyDone = promise.finally(callback)
#
# # Since finally's return value is itself a promise with the same state
# # as `promise`, we don't want to see "Uncaught in Exception".
# # If we didn't do this, we couldn't mute rejections in `promise`:
# #
# # promise = new Promise(...)
# # promise.finally(function() { ... })
# # up.util.muteRejection(promise) // has no effect
# muteRejection(finallyDone)
#
# # Return the original promise and *not* finally's return value.
# return promise
###**
Registers an empty rejection handler with the given promise.
This prevents browsers from printing "Uncaught (in promise)" to the error
console when the promise is rejected.
This is helpful for event handlers where it is clear that no rejection
handler will be registered:
up.on('submit', 'form[up-target]', (event, $form) => {
promise = up.submit($form)
up.util.muteRejection(promise)
})
Does nothing if passed a missing value.
@function up.util.muteRejection
@param {Promise|undefined|null} promise
@return {Promise}
@internal
###
muteRejection = (promise) ->
return promise?.catch(noop)
###**
@function up.util.newDeferred
@internal
###
newDeferred = ->
resolveFn = undefined
rejectFn = undefined
nativePromise = new Promise (givenResolve, givenReject) ->
resolveFn = givenResolve
rejectFn = givenReject
nativePromise.resolve = resolveFn
nativePromise.reject = rejectFn
nativePromise.promise = -> nativePromise # just return self
nativePromise
# ###**
# Calls the given block. If the block throws an exception,
# a rejected promise is returned instead.
#
# @function up.util.rejectOnError
# @internal
# ###
# rejectOnError = (block) ->
# try
# block()
# catch error
# Promise.reject(error)
asyncify = (block) ->
# The side effects of this should be sync, otherwise we could
# just do `Promise.resolve().then(block)`.
try
return Promise.resolve(block())
catch error
return Promise.reject(error)
# sum = (list, block) ->
# block = iteratee(block)
# totalValue = 0
# for entry in list
# entryValue = block(entry)
# if isGiven(entryValue) # ignore undefined/null, like SQL would do
# totalValue += entryValue
# totalValue
isBasicObjectProperty = (k) ->
Object.prototype.hasOwnProperty(k)
###**
Returns whether the two arguments are equal by value.
\#\#\# Comparison protocol
- By default `up.util.isEqual()` can compare strings, numbers,
[array-like values](/up.util.isList), plain objects and `Date` objects.
- To make the copying protocol work with user-defined classes,
see `up.util.isEqual.key`.
- Objects without a defined comparison protocol are
defined by reference (`===`).
@function up.util.isEqual
@param {any} a
@param {any} b
@return {boolean}
Whether the arguments are equal by value.
@experimental
###
isEqual = (a, b) ->
a = a.valueOf() if a?.valueOf # Date, String objects, Number objects
b = b.valueOf() if b?.valueOf # Date, String objects, Number objects
if typeof(a) != typeof(b)
false
else if isList(a) && isList(b)
isEqualList(a, b)
else if isObject(a) && a[isEqual.key]
a[isEqual.key](b)
else if isOptions(a) && isOptions(b)
aKeys = Object.keys(a)
bKeys = Object.keys(b)
if isEqualList(aKeys, bKeys)
every aKeys, (aKey) -> isEqual(a[aKey], b[aKey])
else
false
else
a == b
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.isEqual()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.isEqual()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.isEqual.key](other) {
return this.email === other.email;
}
}
```
Note that the protocol method is not actually named `'up.util.isEqual.key'`.
Instead it is named after the *value* of the `up.util.isEqual.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.isEqual()`:
```
one = new User('<EMAIL>')
two = new User('<EMAIL>')
three = new User('<EMAIL>')
isEqual = up.util.isEqual(one, two)
// isEqual is now true
isEqual = up.util.isEqual(one, three)
// isEqual is now false
```
@property up.util.isEqual.key
@param {string} key
@experimental
###
isEqual.key = 'up.util.isEqual'
isEqualList = (a, b) ->
a.length == b.length && every(a, (elem, index) -> isEqual(elem, b[index]))
splitValues = (value, separator = ' ') ->
if isString(value)
value = value.split(separator)
value = map value, (v) -> v.trim()
value = filterList(value, isPresent)
value
else
wrapList(value)
endsWith = (string, search) ->
if search.length > string.length
false
else
string.substring(string.length - search.length) == search
simpleEase = (x) ->
# easing: http://fooplot.com/?lang=de#W3sidHlwZSI<KEY>
# easing nice: sin((x^0.7-0.5)*pi)*0.5+0.5
# easing performant: x < 0.5 ? 2*x*x : x*(4 - x*2)-1
# https://jsperf.com/easings/1
# Math.sin((Math.pow(x, 0.7) - 0.5) * Math.PI) * 0.5 + 0.5
if x < 0.5
2*x*x
else
x*(4 - x*2)-1
wrapValue = (constructor, args...) ->
if args[0] instanceof constructor
# This object has gone through instantiation and normalization before.
args[0]
else
new constructor(args...)
# wrapArray = (objOrArray) ->
# if isUndefined(objOrArray)
# []
# else if isArray(objOrArray)
# objOrArray
# else
# [objOrArray]
nextUid = 0
uid = ->
nextUid++
###**
Returns a copy of the given list, in reversed order.
@function up.util.reverse
@param {List<T>} list
@return {Array<T>}
@internal
###
reverse = (list) ->
copy(list).reverse()
# ###**
# Returns a copy of the given `object` with the given `prefix` removed
# from its camel-cased keys.
#
# @function up.util.unprefixKeys
# @param {Object} object
# @param {string} prefix
# @return {Object}
# @internal
# ###
# unprefixKeys = (object, prefix) ->
# unprefixed = {}
# prefixLength = prefix.length
# for key, value of object
# if key.indexOf(prefix) == 0
# key = unprefixCamelCase(key, prefixLength)
# unprefixed[key] = value
# unprefixed
# replaceValue = (value, matchValue, replaceValueFn) ->
# if value == matchValue
# return replaceValueFn()
# else
# return value
renameKeys = (object, renameKeyFn) ->
renamed = {}
for key, value of object
renamed[renameKeyFn(key)] = value
return renamed
camelToKebabCase = (str) ->
str.replace /[A-Z]/g, (char) -> '-' + char.toLowerCase()
prefixCamelCase = (str, prefix) ->
prefix + upperCaseFirst(str)
unprefixCamelCase = (str, prefix) ->
pattern = new RegExp('^' + prefix + '(.+)$')
if match = str.match(pattern)
return lowerCaseFirst(match[1])
lowerCaseFirst = (str) ->
str[0].toLowerCase() + str.slice(1)
upperCaseFirst = (str) ->
str[0].toUpperCase() + str.slice(1)
defineGetter = (object, prop, get) ->
Object.defineProperty(object, prop, { get })
defineDelegates = (object, props, targetProvider) ->
wrapList(props).forEach (prop) ->
Object.defineProperty object, prop,
get: ->
target = targetProvider.call(this)
value = target[prop]
if isFunction(value)
value = value.bind(target)
return value
set: (newValue) ->
target = targetProvider.call(this)
target[prop] = newValue
literal = (obj) ->
result = {}
for key, value of obj
if unprefixedKey = unprefixCamelCase(key, 'get_')
defineGetter(result, unprefixedKey, value)
else
result[key] = value
result
stringifyArg = (arg) ->
maxLength = 200
closer = ''
if isString(arg)
string = arg.replace(/[\n\r\t ]+/g, ' ')
string = string.replace(/^[\n\r\t ]+/, '')
string = string.replace(/[\n\r\t ]$/, '')
# string = "\"#{string}\""
# closer = '"'
else if isUndefined(arg)
# JSON.stringify(undefined) is actually undefined
string = 'undefined'
else if isNumber(arg) || isFunction(arg)
string = arg.toString()
else if isArray(arg)
string = "[#{map(arg, stringifyArg).join(', ')}]"
closer = ']'
else if isJQuery(arg)
string = "$(#{map(arg, stringifyArg).join(', ')})"
closer = ')'
else if isElement(arg)
string = "<#{arg.tagName.toLowerCase()}"
for attr in ['id', 'name', 'class']
if value = arg.getAttribute(attr)
string += " #{attr}=\"#{value}\""
string += ">"
closer = '>'
else if isRegExp(arg)
string = arg.toString()
else # object, array
try
string = JSON.stringify(arg)
catch error
if error.name == 'TypeError'
string = '(circular structure)'
else
throw error
if string.length > maxLength
string = "#{string.substr(0, maxLength)} …"
string += closer
string
SPRINTF_PLACEHOLDERS = /\%[oOdisf]/g
secondsSinceEpoch = ->
Math.floor(Date.now() * 0.001)
###**
See https://developer.mozilla.org/en-US/docs/Web/API/Console#Using_string_substitutions
@function up.util.sprintf
@internal
###
sprintf = (message, args...) ->
sprintfWithFormattedArgs(identity, message, args...)
###**
@function up.util.sprintfWithFormattedArgs
@internal
###
sprintfWithFormattedArgs = (formatter, message, args...) ->
return '' unless message
i = 0
message.replace SPRINTF_PLACEHOLDERS, ->
arg = args[i]
arg = formatter(stringifyArg(arg))
i += 1
arg
# Remove with IE11.
# When removed we can also remove muteRejection(), as this is the only caller.
allSettled = (promises) ->
return Promise.all(map(promises, muteRejection))
parseURL: parseURL
normalizeURL: normalizeURL
urlWithoutHost: urlWithoutHost
matchURLs: matchURLs
normalizeMethod: normalizeMethod
methodAllowsPayload: methodAllowsPayload
# isGoodSelector: isGoodSelector
assign: assign
assignPolyfill: assignPolyfill
copy: copy
copyArrayLike: copyArrayLike
# deepCopy: deepCopy
merge: merge
mergeDefined: mergeDefined
# deepAssign: deepAssign
# deepMerge: deepMerge
options: newOptions
parseArgIntoOptions: parseArgIntoOptions
each: each
eachIterator: eachIterator
map: map
flatMap: flatMap
mapObject: mapObject
times: times
findResult: findResult
some: some
every: every
find: findInList
filter: filterList
reject: reject
intersect: intersect
compact: compact
compactObject: compactObject
uniq: uniq
uniqBy: uniqBy
last: last
isNull: isNull
isDefined: isDefined
isUndefined: isUndefined
isGiven: isGiven
isMissing: isMissing
isPresent: isPresent
isBlank: isBlank
presence: presence
isObject: isObject
isFunction: isFunction
isString: isString
isBoolean: isBoolean
isNumber: isNumber
isElement: isElement
isJQuery: isJQuery
isElementish: isElementish
isPromise: isPromise
isOptions: isOptions
isArray: isArray
isFormData: isFormData
isNodeList: isNodeList
isArguments: isArguments
isList: isList
isRegExp: isRegExp
timer: scheduleTimer
contains: contains
objectContains: objectContains
toArray: toArray
pick: pick
pickBy: pickBy
omit: omit
unresolvablePromise: unresolvablePromise
remove: remove
memoize: memoize
pluckKey: pluckKey
renameKey: renameKey
extractOptions: extractOptions
extractCallback: extractCallback
noop: noop
asyncNoop: asyncNoop
identity: identity
escapeHTML: escapeHTML
escapeRegExp: escapeRegExp
sequence: sequence
# previewable: previewable
# parsePath: parsePath
evalOption: evalOption
# horizontalScreenHalf: horizontalScreenHalf
flatten: flatten
# flattenObject: flattenObject
isTruthy: isTruthy
newDeferred: newDeferred
always: always
# mutedFinally: mutedFinally
muteRejection: muteRejection
# rejectOnError: rejectOnError
asyncify: asyncify
isBasicObjectProperty: isBasicObjectProperty
isCrossOrigin: isCrossOrigin
task: queueTask
microtask: queueMicrotask
abortableMicrotask: abortableMicrotask
isEqual: isEqual
splitValues : splitValues
endsWith: endsWith
# sum: sum
# wrapArray: wrapArray
wrapList: wrapList
wrapValue: wrapValue
simpleEase: simpleEase
values: objectValues
# partial: partial
# partialRight: partialRight
arrayToSet: arrayToSet
setToArray: setToArray
# unprefixKeys: unprefixKeys
uid: uid
upperCaseFirst: upperCaseFirst
lowerCaseFirst: lowerCaseFirst
getter: defineGetter
delegate: defineDelegates
literal: literal
# asyncWrap: asyncWrap
reverse: reverse
prefixCamelCase: prefixCamelCase
unprefixCamelCase: unprefixCamelCase
camelToKebabCase: camelToKebabCase
nullToUndefined: nullToUndefined
sprintf: sprintf
sprintfWithFormattedArgs: sprintfWithFormattedArgs
renameKeys: renameKeys
timestamp: secondsSinceEpoch
allSettled: allSettled
| true | ###**
Utility functions
=================
The `up.util` module contains functions to facilitate the work with basic JavaScript
values like lists, strings or functions.
You will recognize many functions form other utility libraries like [Lodash](https://lodash.com/).
While feature parity with Lodash is not a goal of `up.util`, you might find it sufficient
to not include another library in your asset bundle.
@module up.util
###
up.util = do ->
###**
A function that does nothing.
@function up.util.noop
@experimental
###
noop = (->)
###**
A function that returns a resolved promise.
@function up.util.asyncNoop
@internal
###
asyncNoop = -> Promise.resolve()
###**
Ensures that the given function can only be called a single time.
Subsequent calls will return the return value of the first call.
Note that this is a simple implementation that
doesn't distinguish between argument lists.
@function up.util.memoize
@internal
###
memoize = (func) ->
cachedValue = undefined
cached = false
(args...) ->
if cached
return cachedValue
else
cached = true
return cachedValue = func.apply(this, args)
###**
Returns if the given port is the default port for the given protocol.
@function up.util.isStandardPort
@internal
###
isStandardPort = (protocol, port) ->
port = port.toString()
((port == "" || port == "80") && protocol == 'http:') || (port == "443" && protocol == 'https:')
NORMALIZE_URL_DEFAULTS = {
host: 'cross-domain'
stripTrailingSlash: false
search: true
hash: false
}
###**
Normalizes the given URL or path.
@function up.util.normalizeURL
@param {boolean} [options.host='cross-domain']
Whether to include protocol, hostname and port in the normalized URL.
By default the host is only included if it differ's from the page's hostname.
@param {boolean} [options.hash=false]
Whether to include an `#hash` anchor in the normalized URL
@param {boolean} [options.search=true]
Whether to include a `?query` string in the normalized URL
@param {boolean} [options.stripTrailingSlash=false]
Whether to strip a trailing slash from the pathname
@return {string}
The normalized URL.
@internal
###
normalizeURL = (urlOrAnchor, options) ->
options = newOptions(options, NORMALIZE_URL_DEFAULTS)
parts = parseURL(urlOrAnchor)
normalized = ''
if options.host == 'cross-domain'
options.host = isCrossOrigin(parts)
if options.host
normalized += parts.protocol + "//" + parts.hostname
# Once we drop IE11 we can just use { host }, which contains port and hostname
# and also handles standard ports.
# See https://developer.mozilla.org/en-US/docs/Web/API/URL/host
unless isStandardPort(parts.protocol, parts.port)
normalized += ":#{parts.port}"
pathname = parts.pathname
if options.stripTrailingSlash
pathname = pathname.replace(/\/$/, '')
normalized += pathname
if options.search
normalized += parts.search
if options.hash
normalized += parts.hash
normalized
urlWithoutHost = (url) ->
normalizeURL(url, host: false)
matchURLs = (leftURL, rightURL) ->
return normalizeURL(leftURL) == normalizeURL(rightURL)
# We're calling isCrossOrigin() a lot.
# Accessing location.protocol and location.hostname every time
# is much slower than comparing cached strings.
# https://jsben.ch/kBATt
APP_PROTOCOL = location.protocol
APP_HOSTNAME = location.hostname
isCrossOrigin = (urlOrAnchor) ->
# If the given URL does not contain a hostname we know it cannot be cross-origin.
# In that case we don't need to parse the URL.
if isString(urlOrAnchor) && urlOrAnchor.indexOf('//') == -1
return false
parts = parseURL(urlOrAnchor)
return APP_HOSTNAME != parts.hostname || APP_PROTOCOL != parts.protocol
###**
Parses the given URL into components such as hostname and path.
If the given URL is not fully qualified, it is assumed to be relative
to the current page.
\#\#\# Example
```js
let parsed = up.util.parseURL('/path?foo=value')
parsed.pathname // => '/path'
parsed.search // => '/?foo=value'
parsed.hash // => ''
```
@function up.util.parseURL
@return {Object}
The parsed URL as an object with
`protocol`, `hostname`, `port`, `pathname`, `search` and `hash`
properties.
@stable
###
parseURL = (urlOrLink) ->
if isJQuery(urlOrLink)
# In case someone passed us a $link, unwrap it
link = up.element.get(urlOrLink)
else if urlOrLink.pathname
# If we are handed a parsed URL, just return it
link = urlOrLink
else
link = document.createElement('a')
link.href = urlOrLink
# In IE11 the #hostname and #port properties of unqualified URLs are empty strings.
# We can fix this by setting the link's { href } on the link itself.
unless link.hostname
link.href = link.href
# Some IEs don't include a leading slash in the #pathname property.
# We have confirmed this in IE11 and earlier.
unless link.pathname[0] == '/'
# Only copy the link into an object when we need to (to change a property).
# Note that we're parsing a lot of URLs for [up-active].
link = pick(link, ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash'])
link.pathname = '/' + link.pathname
link
###**
@function up.util.normalizeMethod
@internal
###
normalizeMethod = (method) ->
if method
method.toUpperCase()
else
'GET'
###**
@function up.util.methodAllowsPayload
@internal
###
methodAllowsPayload = (method) ->
method != 'GET' && method != 'HEAD'
# Remove with IE11
assignPolyfill = (target, sources...) ->
for source in sources
for own key, value of source
target[key] = value
target
###**
Merge the own properties of one or more `sources` into the `target` object.
@function up.util.assign
@param {Object} target
@param {Array<Object>} sources...
@stable
###
assign = Object.assign || assignPolyfill
# Remove with IE11
valuesPolyfill = (object) ->
value for key, value of object
###**
Returns an array of values of the given object.
@function up.util.values
@param {Object} object
@return {Array<string>}
@stable
###
objectValues = Object.values || valuesPolyfill
iteratee = (block) ->
if isString(block)
(item) -> item[block]
else
block
###**
Translate all items in an array to new array of items.
@function up.util.map
@param {Array} array
@param {Function(element, index): any|String} block
A function that will be called with each element and (optional) iteration index.
You can also pass a property name as a String,
which will be collected from each item in the array.
@return {Array}
A new array containing the result of each function call.
@stable
###
map = (array, block) ->
return [] if array.length == 0
block = iteratee(block)
for item, index in array
block(item, index)
###**
@function up.util.mapObject
@internal
###
mapObject = (array, pairer) ->
merger = (object, pair) ->
object[pair[0]] = pair[1]
return object
map(array, pairer).reduce(merger, {})
###**
Calls the given function for each element (and, optional, index)
of the given array.
@function up.util.each
@param {Array} array
@param {Function(element, index)} block
A function that will be called with each element and (optional) iteration index.
@stable
###
each = map # note that the native Array.forEach is very slow (https://jsperf.com/fast-array-foreach)
eachIterator = (iterator, callback) ->
while (entry = iterator.next()) && !entry.done
callback(entry.value)
###**
Calls the given function for the given number of times.
@function up.util.times
@param {number} count
@param {Function()} block
@stable
###
times = (count, block) ->
block(iteration) for iteration in [0..(count - 1)]
###**
Returns whether the given argument is `null`.
@function up.util.isNull
@param object
@return {boolean}
@stable
###
isNull = (object) ->
object == null
###**
Returns whether the given argument is `undefined`.
@function up.util.isUndefined
@param object
@return {boolean}
@stable
###
isUndefined = (object) ->
object == undefined
###**
Returns whether the given argument is not `undefined`.
@function up.util.isDefined
@param object
@return {boolean}
@stable
###
isDefined = (object) ->
!isUndefined(object)
###**
Returns whether the given argument is either `undefined` or `null`.
Note that empty strings or zero are *not* considered to be "missing".
For the opposite of `up.util.isMissing()` see [`up.util.isGiven()`](/up.util.isGiven).
@function up.util.isMissing
@param object
@return {boolean}
@stable
###
isMissing = (object) ->
isUndefined(object) || isNull(object)
###**
Returns whether the given argument is neither `undefined` nor `null`.
Note that empty strings or zero *are* considered to be "given".
For the opposite of `up.util.isGiven()` see [`up.util.isMissing()`](/up.util.isMissing).
@function up.util.isGiven
@param object
@return {boolean}
@stable
###
isGiven = (object) ->
!isMissing(object)
# isNan = (object) ->
# isNumber(value) && value != +value
###**
Return whether the given argument is considered to be blank.
By default, this function returns `true` for:
- `undefined`
- `null`
- Empty strings
- Empty arrays
- A plain object without own enumerable properties
All other arguments return `false`.
To check implement blank-ness checks for user-defined classes,
see `up.util.isBlank.key`.
@function up.util.isBlank
@param value
The value is to check.
@return {boolean}
Whether the value is blank.
@stable
###
isBlank = (value) ->
if isMissing(value)
return true
if isObject(value) && value[isBlank.key]
return value[isBlank.key]()
if isString(value) || isList(value)
return value.length == 0
if isOptions(value)
return Object.keys(value).length == 0
return false
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.isBlank()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.isBlank()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.isBlank.key]() {
return up.util.isBlank(this.email)
}
}
```
Note that the protocol method is not actually named `'up.util.isBlank.key'`.
Instead it is named after the *value* of the `up.util.isBlank.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.isBlank()`:
```
foo = new Account('PI:EMAIL:<EMAIL>END_PI')
bar = new Account('')
console.log(up.util.isBlank(foo)) // prints false
console.log(up.util.isBlank(bar)) // prints true
```
@property up.util.isBlank.key
@experimental
###
isBlank.key = 'PI:KEY:<KEY>END_PI'
###**
Returns the given argument if the argument is [present](/up.util.isPresent),
otherwise returns `undefined`.
@function up.util.presence
@param value
@param {Function(value): boolean} [tester=up.util.isPresent]
The function that will be used to test whether the argument is present.
@return {any|undefined}
@stable
###
presence = (value, tester = isPresent) ->
if tester(value) then value else undefined
###**
Returns whether the given argument is not [blank](/up.util.isBlank).
@function up.util.isPresent
@param object
@return {boolean}
@stable
###
isPresent = (object) ->
!isBlank(object)
###**
Returns whether the given argument is a function.
@function up.util.isFunction
@param object
@return {boolean}
@stable
###
isFunction = (object) ->
typeof(object) == 'function'
###**
Returns whether the given argument is a string.
@function up.util.isString
@param object
@return {boolean}
@stable
###
isString = (object) ->
typeof(object) == 'string' || object instanceof String
###**
Returns whether the given argument is a boolean value.
@function up.util.isBoolean
@param object
@return {boolean}
@stable
###
isBoolean = (object) ->
typeof(object) == 'boolean' || object instanceof Boolean
###**
Returns whether the given argument is a number.
Note that this will check the argument's *type*.
It will return `false` for a string like `"123"`.
@function up.util.isNumber
@param object
@return {boolean}
@stable
###
isNumber = (object) ->
typeof(object) == 'number' || object instanceof Number
###**
Returns whether the given argument is an options hash,
Differently from [`up.util.isObject()`], this returns false for
functions, jQuery collections, promises, `FormData` instances and arrays.
@function up.util.isOptions
@param object
@return {boolean}
@internal
###
isOptions = (object) ->
typeof(object) == 'object' && !isNull(object) && (isUndefined(object.constructor) || object.constructor == Object)
###**
Returns whether the given argument is an object.
This also returns `true` for functions, which may behave like objects in JavaScript.
@function up.util.isObject
@param object
@return {boolean}
@stable
###
isObject = (object) ->
typeOfResult = typeof(object)
(typeOfResult == 'object' && !isNull(object)) || typeOfResult == 'function'
###**
Returns whether the given argument is a [DOM element](https://developer.mozilla.org/de/docs/Web/API/Element).
@function up.util.isElement
@param object
@return {boolean}
@stable
###
isElement = (object) ->
object instanceof Element
###**
Returns whether the given argument is a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).
@function up.util.isRegExp
@param object
@return {boolean}
@internal
###
isRegExp = (object) ->
object instanceof RegExp
###**
Returns whether the given argument is a [jQuery collection](https://learn.jquery.com/using-jquery-core/jquery-object/).
@function up.util.isJQuery
@param object
@return {boolean}
@stable
###
isJQuery = (object) ->
# We cannot do `object instanceof jQuery` since window.jQuery might not be set
!!object?.jquery
###**
@function up.util.isElementish
@param object
@return {boolean}
@internal
###
isElementish = (object) ->
!!(object && (object.addEventListener || object[0]?.addEventListener))
###**
Returns whether the given argument is an object with a `then` method.
@function up.util.isPromise
@param object
@return {boolean}
@stable
###
isPromise = (object) ->
isObject(object) && isFunction(object.then)
###**
Returns whether the given argument is an array.
@function up.util.isArray
@param object
@return {boolean}
@stable
###
# https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
isArray = Array.isArray
###**
Returns whether the given argument is a `FormData` instance.
Always returns `false` in browsers that don't support `FormData`.
@function up.util.isFormData
@param object
@return {boolean}
@internal
###
isFormData = (object) ->
object instanceof FormData
###**
Converts the given [array-like value](/up.util.isList) into an array.
If the given value is already an array, it is returned unchanged.
@function up.util.toArray
@param object
@return {Array}
@stable
###
toArray = (value) ->
if isArray(value)
value
else
copyArrayLike(value)
###**
Returns whether the given argument is an array-like value.
Return true for `Array`, a
[`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList),
the [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
or a jQuery collection.
Use [`up.util.isArray()`](/up.util.isArray) to test whether a value is an actual `Array`.
@function up.util.isList
@param value
@return {boolean}
@stable
###
isList = (value) ->
isArray(value) ||
isNodeList(value) ||
isArguments(value) ||
isJQuery(value) ||
isHTMLCollection(value)
###**
Returns whether the given value is a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList).
`NodeLists` are array-like objects returned by [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll).
@function up.util.isNodeList
@param value
@return {boolean}
@internal
###
isNodeList = (value) ->
value instanceof NodeList
isHTMLCollection = (value) ->
value instanceof HTMLCollection
###**
Returns whether the given value is an [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments).
@function up.util.isArguments
@param value
@return {boolean}
@internal
###
isArguments = (value) ->
Object.prototype.toString.call(value) == '[object Arguments]'
nullToUndefined = (value) ->
if isNull(value)
return undefined
else
return value
###**
Returns the given value if it is [array-like](/up.util.isList), otherwise
returns an array with the given value as its only element.
\#\#\# Example
```js
up.util.wrapList([1, 2, 3]) // => [1, 2, 3]
up.util.wrapList('foo') // => ['foo']
```
@function up.util.wrapList
@param {any} value
@return {Array|NodeList|jQuery}
@experimental
###
wrapList = (value) ->
if isList(value)
value
else if isMissing(value)
[]
else
[value]
###**
Returns a shallow copy of the given value.
\#\#\# Copying protocol
- By default `up.util.copy()` can copy [array-like values](/up.util.isList),
plain objects and `Date` instances.
- Array-like objects are copied into new arrays.
- Unsupported types of values are returned unchanged.
- To make the copying protocol work with user-defined class,
see `up.util.copy.key`.
- Immutable objects, like strings or numbers, do not need to be copied.
@function up.util.copy
@param {any} object
@return {any}
@stable
###
copy = (value) ->
if isObject(value) && value[copy.key]
value = value[copy.key]()
else if isList(value)
value = copyArrayLike(value)
# copied = true
else if isOptions(value)
value = assign({}, value)
# copied = true
# if copied && deep
# for k, v of value
# value[k] = copy(v, true)
value
copyArrayLike = (arrayLike) ->
Array.prototype.slice.call(arrayLike)
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.copy()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.copy()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.copy.key]() {
return new Account(this.email)
}
}
```
Note that the protocol method is not actually named `'up.util.copy.key'`.
Instead it is named after the *value* of the `up.util.copy.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.copy()`:
```
original = new User('PI:EMAIL:<EMAIL>END_PI')
copy = up.util.copy(original)
console.log(copy.email) // prints 'PI:EMAIL:<EMAIL>END_PI'
original.email = 'PI:EMAIL:<EMAIL>END_PI' // change the original
console.log(copy.email) // still prints 'PI:EMAIL:<EMAIL>END_PI'
```
@property up.util.copy.key
@param {string} key
@experimental
###
copy.key = 'PI:KEY:<KEY>END_PI'
# Implement up.util.copy protocol for Date
Date.prototype[copy.key] = -> new Date(+@)
# ###**
# Returns a deep copy of the given array or object.
#
# @function up.util.deepCopy
# @param {Object|Array} object
# @return {Object|Array}
# @internal
# ###
# deepCopy = (object) ->
# copy(object, true)
###**
Creates a new object by merging together the properties from the given objects.
@function up.util.merge
@param {Array<Object>} sources...
@return Object
@stable
###
merge = (sources...) ->
assign({}, sources...)
###**
@function up.util.mergeDefined
@param {Array<Object>} sources...
@return Object
@internal
###
mergeDefined = (sources...) ->
result = {}
for source in sources
if source
for key, value of source
if isDefined(value)
result[key] = value
result
# ###**
# Creates a new object by recursively merging together the properties from the given objects.
#
# @function up.util.deepMerge
# @param {Array<Object>} ...sources
# @return Object
#
# @internal
# ###
# deepMerge = (sources...) ->
# deepAssign({}, sources...)
#
# ###**
# @function up.util.deepAssign
# @param {Array<Object>} ...sources
# @return Object
# ###
# deepAssign = (target, sources...) ->
# for source in sources
# for key, newValue of source
# if isOptions(newValue)
# oldValue = target[key]
# if isOptions(oldValue)
# newValue = deepMerge(oldValue, newValue)
# target[key] = newValue
# target
###**
Creates an options hash from the given argument and some defaults.
The semantics of this function are confusing.
We want to get rid of this in the future.
@function up.util.options
@param {Object} object
@param {Object} [defaults]
@return {Object}
@internal
###
newOptions = (object, defaults) ->
if defaults
merge(defaults, object)
else if object
copy(object)
else
{}
parseArgIntoOptions = (args, argKey) ->
options = extractOptions(args)
if isDefined(args[0])
options = copy(options)
options[argKey] = args[0]
options
###**
Passes each element in the given [array-like value](/up.util.isList) to the given function.
Returns the first element for which the function returns a truthy value.
If no object matches, returns `undefined`.
@function up.util.find
@param {List<T>} list
@param {Function(value): boolean} tester
@return {T|undefined}
@stable
###
findInList = (list, tester) ->
tester = iteratee(tester)
match = undefined
for element in list
if tester(element)
match = element
break
match
###**
Returns whether the given function returns a truthy value
for any element in the given [array-like value](/up.util.isList).
@function up.util.some
@param {List} list
@param {Function(value, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@stable
###
some = (list, tester) ->
!!findResult(list, tester)
###**
Consecutively calls the given function which each element
in the given array. Returns the first truthy return value.
Returned `undefined` iff the function does not return a truthy
value for any element in the array.
@function up.util.findResult
@param {Array} array
@param {Function(element): any} tester
A function that will be called with each element and (optional) iteration index.
@return {any|undefined}
@experimental
###
findResult = (array, tester) ->
tester = iteratee(tester)
for element, index in array
if result = tester(element, index)
return result
return undefined
###**
Returns whether the given function returns a truthy value
for all elements in the given [array-like value](/up.util.isList).
@function up.util.every
@param {List} list
@param {Function(element, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@experimental
###
every = (list, tester) ->
tester = iteratee(tester)
match = true
for element, index in list
unless tester(element, index)
match = false
break
match
###**
Returns all elements from the given array that are
neither `null` or `undefined`.
@function up.util.compact
@param {Array<T>} array
@return {Array<T>}
@stable
###
compact = (array) ->
filterList array, isGiven
compactObject = (object) ->
pickBy(object, isGiven)
###**
Returns the given array without duplicates.
@function up.util.uniq
@param {Array<T>} array
@return {Array<T>}
@stable
###
uniq = (array) ->
return array if array.length < 2
setToArray(arrayToSet(array))
###**
This function is like [`uniq`](/up.util.uniq), accept that
the given function is invoked for each element to generate the value
for which uniquness is computed.
@function up.util.uniqBy
@param {Array} array
@param {Function(value): any} array
@return {Array}
@experimental
###
uniqBy = (array, mapper) ->
return array if array.length < 2
mapper = iteratee(mapper)
set = new Set()
filterList array, (elem, index) ->
mapped = mapper(elem, index)
if set.has(mapped)
false
else
set.add(mapped)
true
###**
@function up.util.setToArray
@internal
###
setToArray = (set) ->
array = []
set.forEach (elem) -> array.push(elem)
array
###**
@function up.util.arrayToSet
@internal
###
arrayToSet = (array) ->
set = new Set()
array.forEach (elem) -> set.add(elem)
set
###**
Returns all elements from the given [array-like value](/up.util.isList) that return
a truthy value when passed to the given function.
@function up.util.filter
@param {List} list
@param {Function(value, index): boolean} tester
@return {Array}
@stable
###
filterList = (list, tester) ->
tester = iteratee(tester)
matches = []
each list, (element, index) ->
if tester(element, index)
matches.push(element)
matches
###**
Returns all elements from the given [array-like value](/up.util.isList) that do not return
a truthy value when passed to the given function.
@function up.util.reject
@param {List} list
@param {Function(element, index): boolean} tester
@return {Array}
@stable
###
reject = (list, tester) ->
tester = iteratee(tester)
filterList(list, (element, index) -> !tester(element, index))
###**
Returns the intersection of the given two arrays.
Implementation is not optimized. Don't use it for large arrays.
@function up.util.intersect
@internal
###
intersect = (array1, array2) ->
filterList array1, (element) ->
contains(array2, element)
###**
Waits for the given number of milliseconds, the runs the given callback.
Instead of `up.util.timer(0, fn)` you can also use [`up.util.task(fn)`](/up.util.task).
@function up.util.timer
@param {number} millis
@param {Function()} callback
@return {number}
The ID of the scheduled timeout.
You may pass this ID to `clearTimeout()` to un-schedule the timeout.
@stable
###
scheduleTimer = (millis, callback) ->
setTimeout(callback, millis)
###**
Pushes the given function to the [JavaScript task queue](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) (also "macrotask queue").
Equivalent to calling `setTimeout(fn, 0)`.
Also see `up.util.microtask()`.
@function up.util.task
@param {Function()} block
@stable
###
queueTask = (block) ->
setTimeout(block, 0)
###**
Pushes the given function to the [JavaScript microtask queue](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/).
@function up.util.microtask
@param {Function()} task
@return {Promise}
A promise that is resolved with the return value of `task`.
If `task` throws an error, the promise is rejected with that error.
@experimental
###
queueMicrotask = (task) ->
return Promise.resolve().then(task)
abortableMicrotask = (task) ->
aborted = false
queueMicrotask(-> task() unless aborted)
return -> aborted = true
###**
Returns the last element of the given array.
@function up.util.last
@param {Array<T>} array
@return {T}
@stable
###
last = (array) ->
array[array.length - 1]
###**
Returns whether the given value contains another value.
If `value` is a string, this returns whether `subValue` is a sub-string of `value`.
If `value` is an array, this returns whether `subValue` is an element of `value`.
@function up.util.contains
@param {Array|string} value
@param {Array|string} subValue
@stable
###
contains = (value, subValue) ->
value.indexOf(subValue) >= 0
###**
Returns whether `object`'s entries are a superset
of `subObject`'s entries.
@function up.util.objectContains
@param {Object} object
@param {Object} subObject
@internal
###
objectContains = (object, subObject) ->
reducedValue = pick(object, Object.keys(subObject))
isEqual(subObject, reducedValue)
###**
Returns a copy of the given object that only contains
the given keys.
@function up.util.pick
@param {Object} object
@param {Array} keys
@return {Object}
@stable
###
pick = (object, keys) ->
filtered = {}
for key in keys
if key of object
filtered[key] = object[key]
filtered
###**
Returns a copy of the given object that only contains
properties that pass the given tester function.
@function up.util.pickBy
@param {Object} object
@param {Function<string, string, object>} tester
A function that will be called with each property.
The arguments are the property value, key and the entire object.
@return {Object}
@experimental
###
pickBy = (object, tester) ->
tester = iteratee(tester)
filtered = {}
for key, value of object
if tester(value, key, object)
filtered[key] = object[key]
return filtered
###**
Returns a copy of the given object that contains all except
the given keys.
@function up.util.omit
@param {Object} object
@param {Array} keys
@stable
###
omit = (object, keys) ->
pickBy(object, (value, key) -> !contains(keys, key))
###**
Returns a promise that will never be resolved.
@function up.util.unresolvablePromise
@internal
###
unresolvablePromise = ->
new Promise(noop)
###**
Removes the given element from the given array.
This changes the given array.
@function up.util.remove
@param {Array<T>} array
The array to change.
@param {T} element
The element to remove.
@return {T|undefined}
The removed element, or `undefined` if the array didn't contain the element.
@stable
###
remove = (array, element) ->
index = array.indexOf(element)
if index >= 0
array.splice(index, 1)
return element
###**
If the given `value` is a function, calls the function with the given `args`.
Otherwise it just returns `value`.
\#\#\# Example
```js
up.util.evalOption(5) // => 5
let fn = () => 1 + 2
up.util.evalOption(fn) // => 3
```
@function up.util.evalOption
@param {any} value
@param {Array} ...args
@return {any}
@experimental
###
evalOption = (value, args...) ->
if isFunction(value)
value(args...)
else
value
ESCAPE_HTML_ENTITY_MAP =
"&": "&"
"<": "<"
">": ">"
'"': '"'
"'": '''
###**
Escapes the given string of HTML by replacing control chars with their HTML entities.
@function up.util.escapeHTML
@param {string} string
The text that should be escaped.
@stable
###
escapeHTML = (string) ->
string.replace /[&<>"']/g, (char) -> ESCAPE_HTML_ENTITY_MAP[char]
###**
@function up.util.escapeRegExp
@internal
###
escapeRegExp = (string) ->
# From https://github.com/benjamingr/RegExp.escape
string.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&')
###**
Deletes the property with the given key from the given object
and returns its value.
@function up.util.pluckKey
@param {Object} object
@param {string} key
@return {any}
@experimental
###
pluckKey = (object, key) ->
value = object[key]
delete object[key]
value
renameKey = (object, oldKey, newKey) ->
object[newKey] = pluckKey(object, oldKey)
extractLastArg = (args, tester) ->
lastArg = last(args)
if tester(lastArg)
return args.pop()
# extractFirstArg = (args, tester) ->
# firstArg = args[0]
# if tester(firstArg)
# return args.shift()
extractCallback = (args) ->
extractLastArg(args, isFunction)
extractOptions = (args) ->
extractLastArg(args, isOptions) || {}
# partial = (fn, fixedArgs...) ->
# return (callArgs...) ->
# fn.apply(this, fixedArgs.concat(callArgs))
#
# partialRight = (fn, fixedArgs...) ->
# return (callArgs...) ->
# fn.apply(this, callArgs.concat(fixedArgs))
#function throttle(callback, limit) { // From https://jsfiddle.net/jonathansampson/m7G64/
# var wait = false // Initially, we're not waiting
# return function () { // We return a throttled function
# if (!wait) { // If we're not waiting
# callback.call() // Execute users function
# wait = true // Prevent future invocations
# setTimeout(function () { // After a period of time
# wait = false // And allow future invocations
# }, limit)
# }
# }
#}
identity = (arg) -> arg
# ###**
# ###
# parsePath = (input) ->
# path = []
# pattern = /([^\.\[\]\"\']+)|\[\'([^\']+?)\'\]|\[\"([^\"]+?)\"\]|\[([^\]]+?)\]/g
# while match = pattern.exec(input)
# path.push(match[1] || match[2] || match[3] || match[4])
# path
# ###**
# Given an async function that will return a promise, returns a proxy function
# with an additional `.promise` attribute.
#
# When the proxy is called, the inner function is called.
# The proxy's `.promise` attribute is available even before the function is called
# and will resolve when the inner function's returned promise resolves.
#
# If the inner function does not return a promise, the proxy's `.promise` attribute
# will resolve as soon as the inner function returns.
#
# @function up.util.previewable
# @internal
# ###
# previewable = (fun) ->
# deferred = newDeferred()
# preview = (args...) ->
# funValue = fun(args...)
# # If funValue is again a Promise, it will defer resolution of `deferred`
# # until `funValue` is resolved.
# deferred.resolve(funValue)
# funValue
# preview.promise = deferred.promise()
# preview
###**
@function up.util.sequence
@param {Array<Function()>} functions
@return {Function()}
A function that will call all `functions` if called.
@internal
###
sequence = (functions) ->
if functions.length == 1
return functions[0]
else
return -> map(functions, (f) -> f())
# ###**
# @function up.util.race
# @internal
# ###
# race = (promises...) ->
# raceDone = newDeferred()
# each promises, (promise) ->
# promise.then -> raceDone.resolve()
# raceDone.promise()
# ###**
# Returns `'left'` if the center of the given element is in the left 50% of the screen.
# Otherwise returns `'right'`.
#
# @function up.util.horizontalScreenHalf
# @internal
# ###
# horizontalScreenHalf = (element) ->
# elementDims = element.getBoundingClientRect()
# elementMid = elementDims.left + 0.5 * elementDims.width
# screenMid = 0.5 * up.viewport.rootWidth()
# if elementMid < screenMid
# 'left'
# else
# 'right'
###**
Flattens the given `array` a single depth level.
\#\#\# Example
```js
let nested = [1, [2, 3], [4]]
up.util.flatten(nested) // => [1, 2, 3, 4]
@function up.util.flatten
@param {Array} array
An array which might contain other arrays
@return {Array}
The flattened array
@experimental
###
flatten = (array) ->
flattened = []
for object in array
if isList(object)
flattened.push(object...)
else
flattened.push(object)
flattened
# flattenObject = (object) ->
# result = {}
# for key, value of object
# result[key] = value
# result
###**
Maps each element using a mapping function,
then [flattens](/up.util.flatten) the result into a new array.
@function up.util.flatMap
@param {Array} array
@param {Function(element)} mapping
@return {Array}
@experimental
###
flatMap = (array, block) ->
flatten map(array, block)
###**
Returns whether the given value is truthy.
@function up.util.isTruthy
@internal
###
isTruthy = (object) ->
!!object
###**
Sets the given callback as both fulfillment and rejection handler for the given promise.
[Unlike `promise#finally()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally#Description), `up.util.always()` may change the settlement value
of the given promise.
@function up.util.always
@internal
###
always = (promise, callback) ->
promise.then(callback, callback)
# mutedFinally = (promise, callback) ->
# # Use finally() instead of always() so we don't accidentally
# # register a rejection handler, which would prevent an "Uncaught in Exception" error.
# finallyDone = promise.finally(callback)
#
# # Since finally's return value is itself a promise with the same state
# # as `promise`, we don't want to see "Uncaught in Exception".
# # If we didn't do this, we couldn't mute rejections in `promise`:
# #
# # promise = new Promise(...)
# # promise.finally(function() { ... })
# # up.util.muteRejection(promise) // has no effect
# muteRejection(finallyDone)
#
# # Return the original promise and *not* finally's return value.
# return promise
###**
Registers an empty rejection handler with the given promise.
This prevents browsers from printing "Uncaught (in promise)" to the error
console when the promise is rejected.
This is helpful for event handlers where it is clear that no rejection
handler will be registered:
up.on('submit', 'form[up-target]', (event, $form) => {
promise = up.submit($form)
up.util.muteRejection(promise)
})
Does nothing if passed a missing value.
@function up.util.muteRejection
@param {Promise|undefined|null} promise
@return {Promise}
@internal
###
muteRejection = (promise) ->
return promise?.catch(noop)
###**
@function up.util.newDeferred
@internal
###
newDeferred = ->
resolveFn = undefined
rejectFn = undefined
nativePromise = new Promise (givenResolve, givenReject) ->
resolveFn = givenResolve
rejectFn = givenReject
nativePromise.resolve = resolveFn
nativePromise.reject = rejectFn
nativePromise.promise = -> nativePromise # just return self
nativePromise
# ###**
# Calls the given block. If the block throws an exception,
# a rejected promise is returned instead.
#
# @function up.util.rejectOnError
# @internal
# ###
# rejectOnError = (block) ->
# try
# block()
# catch error
# Promise.reject(error)
asyncify = (block) ->
# The side effects of this should be sync, otherwise we could
# just do `Promise.resolve().then(block)`.
try
return Promise.resolve(block())
catch error
return Promise.reject(error)
# sum = (list, block) ->
# block = iteratee(block)
# totalValue = 0
# for entry in list
# entryValue = block(entry)
# if isGiven(entryValue) # ignore undefined/null, like SQL would do
# totalValue += entryValue
# totalValue
isBasicObjectProperty = (k) ->
Object.prototype.hasOwnProperty(k)
###**
Returns whether the two arguments are equal by value.
\#\#\# Comparison protocol
- By default `up.util.isEqual()` can compare strings, numbers,
[array-like values](/up.util.isList), plain objects and `Date` objects.
- To make the copying protocol work with user-defined classes,
see `up.util.isEqual.key`.
- Objects without a defined comparison protocol are
defined by reference (`===`).
@function up.util.isEqual
@param {any} a
@param {any} b
@return {boolean}
Whether the arguments are equal by value.
@experimental
###
isEqual = (a, b) ->
a = a.valueOf() if a?.valueOf # Date, String objects, Number objects
b = b.valueOf() if b?.valueOf # Date, String objects, Number objects
if typeof(a) != typeof(b)
false
else if isList(a) && isList(b)
isEqualList(a, b)
else if isObject(a) && a[isEqual.key]
a[isEqual.key](b)
else if isOptions(a) && isOptions(b)
aKeys = Object.keys(a)
bKeys = Object.keys(b)
if isEqualList(aKeys, bKeys)
every aKeys, (aKey) -> isEqual(a[aKey], b[aKey])
else
false
else
a == b
###**
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.isEqual()` protocol.
\#\#\# Example
We have a user-defined `Account` class that we want to use with `up.util.isEqual()`:
```
class Account {
constructor(email) {
this.email = email
}
[up.util.isEqual.key](other) {
return this.email === other.email;
}
}
```
Note that the protocol method is not actually named `'up.util.isEqual.key'`.
Instead it is named after the *value* of the `up.util.isEqual.key` property.
To do so, the code sample above is using a
[computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
in square brackets.
We may now use `Account` instances with `up.util.isEqual()`:
```
one = new User('PI:EMAIL:<EMAIL>END_PI')
two = new User('PI:EMAIL:<EMAIL>END_PI')
three = new User('PI:EMAIL:<EMAIL>END_PI')
isEqual = up.util.isEqual(one, two)
// isEqual is now true
isEqual = up.util.isEqual(one, three)
// isEqual is now false
```
@property up.util.isEqual.key
@param {string} key
@experimental
###
isEqual.key = 'up.util.isEqual'
isEqualList = (a, b) ->
a.length == b.length && every(a, (elem, index) -> isEqual(elem, b[index]))
splitValues = (value, separator = ' ') ->
if isString(value)
value = value.split(separator)
value = map value, (v) -> v.trim()
value = filterList(value, isPresent)
value
else
wrapList(value)
endsWith = (string, search) ->
if search.length > string.length
false
else
string.substring(string.length - search.length) == search
simpleEase = (x) ->
# easing: http://fooplot.com/?lang=de#W3sidHlwZSIPI:KEY:<KEY>END_PI
# easing nice: sin((x^0.7-0.5)*pi)*0.5+0.5
# easing performant: x < 0.5 ? 2*x*x : x*(4 - x*2)-1
# https://jsperf.com/easings/1
# Math.sin((Math.pow(x, 0.7) - 0.5) * Math.PI) * 0.5 + 0.5
if x < 0.5
2*x*x
else
x*(4 - x*2)-1
wrapValue = (constructor, args...) ->
if args[0] instanceof constructor
# This object has gone through instantiation and normalization before.
args[0]
else
new constructor(args...)
# wrapArray = (objOrArray) ->
# if isUndefined(objOrArray)
# []
# else if isArray(objOrArray)
# objOrArray
# else
# [objOrArray]
nextUid = 0
uid = ->
nextUid++
###**
Returns a copy of the given list, in reversed order.
@function up.util.reverse
@param {List<T>} list
@return {Array<T>}
@internal
###
reverse = (list) ->
copy(list).reverse()
# ###**
# Returns a copy of the given `object` with the given `prefix` removed
# from its camel-cased keys.
#
# @function up.util.unprefixKeys
# @param {Object} object
# @param {string} prefix
# @return {Object}
# @internal
# ###
# unprefixKeys = (object, prefix) ->
# unprefixed = {}
# prefixLength = prefix.length
# for key, value of object
# if key.indexOf(prefix) == 0
# key = unprefixCamelCase(key, prefixLength)
# unprefixed[key] = value
# unprefixed
# replaceValue = (value, matchValue, replaceValueFn) ->
# if value == matchValue
# return replaceValueFn()
# else
# return value
renameKeys = (object, renameKeyFn) ->
renamed = {}
for key, value of object
renamed[renameKeyFn(key)] = value
return renamed
camelToKebabCase = (str) ->
str.replace /[A-Z]/g, (char) -> '-' + char.toLowerCase()
prefixCamelCase = (str, prefix) ->
prefix + upperCaseFirst(str)
unprefixCamelCase = (str, prefix) ->
pattern = new RegExp('^' + prefix + '(.+)$')
if match = str.match(pattern)
return lowerCaseFirst(match[1])
lowerCaseFirst = (str) ->
str[0].toLowerCase() + str.slice(1)
upperCaseFirst = (str) ->
str[0].toUpperCase() + str.slice(1)
defineGetter = (object, prop, get) ->
Object.defineProperty(object, prop, { get })
defineDelegates = (object, props, targetProvider) ->
wrapList(props).forEach (prop) ->
Object.defineProperty object, prop,
get: ->
target = targetProvider.call(this)
value = target[prop]
if isFunction(value)
value = value.bind(target)
return value
set: (newValue) ->
target = targetProvider.call(this)
target[prop] = newValue
literal = (obj) ->
result = {}
for key, value of obj
if unprefixedKey = unprefixCamelCase(key, 'get_')
defineGetter(result, unprefixedKey, value)
else
result[key] = value
result
stringifyArg = (arg) ->
maxLength = 200
closer = ''
if isString(arg)
string = arg.replace(/[\n\r\t ]+/g, ' ')
string = string.replace(/^[\n\r\t ]+/, '')
string = string.replace(/[\n\r\t ]$/, '')
# string = "\"#{string}\""
# closer = '"'
else if isUndefined(arg)
# JSON.stringify(undefined) is actually undefined
string = 'undefined'
else if isNumber(arg) || isFunction(arg)
string = arg.toString()
else if isArray(arg)
string = "[#{map(arg, stringifyArg).join(', ')}]"
closer = ']'
else if isJQuery(arg)
string = "$(#{map(arg, stringifyArg).join(', ')})"
closer = ')'
else if isElement(arg)
string = "<#{arg.tagName.toLowerCase()}"
for attr in ['id', 'name', 'class']
if value = arg.getAttribute(attr)
string += " #{attr}=\"#{value}\""
string += ">"
closer = '>'
else if isRegExp(arg)
string = arg.toString()
else # object, array
try
string = JSON.stringify(arg)
catch error
if error.name == 'TypeError'
string = '(circular structure)'
else
throw error
if string.length > maxLength
string = "#{string.substr(0, maxLength)} …"
string += closer
string
SPRINTF_PLACEHOLDERS = /\%[oOdisf]/g
secondsSinceEpoch = ->
Math.floor(Date.now() * 0.001)
###**
See https://developer.mozilla.org/en-US/docs/Web/API/Console#Using_string_substitutions
@function up.util.sprintf
@internal
###
sprintf = (message, args...) ->
sprintfWithFormattedArgs(identity, message, args...)
###**
@function up.util.sprintfWithFormattedArgs
@internal
###
sprintfWithFormattedArgs = (formatter, message, args...) ->
return '' unless message
i = 0
message.replace SPRINTF_PLACEHOLDERS, ->
arg = args[i]
arg = formatter(stringifyArg(arg))
i += 1
arg
# Remove with IE11.
# When removed we can also remove muteRejection(), as this is the only caller.
allSettled = (promises) ->
return Promise.all(map(promises, muteRejection))
parseURL: parseURL
normalizeURL: normalizeURL
urlWithoutHost: urlWithoutHost
matchURLs: matchURLs
normalizeMethod: normalizeMethod
methodAllowsPayload: methodAllowsPayload
# isGoodSelector: isGoodSelector
assign: assign
assignPolyfill: assignPolyfill
copy: copy
copyArrayLike: copyArrayLike
# deepCopy: deepCopy
merge: merge
mergeDefined: mergeDefined
# deepAssign: deepAssign
# deepMerge: deepMerge
options: newOptions
parseArgIntoOptions: parseArgIntoOptions
each: each
eachIterator: eachIterator
map: map
flatMap: flatMap
mapObject: mapObject
times: times
findResult: findResult
some: some
every: every
find: findInList
filter: filterList
reject: reject
intersect: intersect
compact: compact
compactObject: compactObject
uniq: uniq
uniqBy: uniqBy
last: last
isNull: isNull
isDefined: isDefined
isUndefined: isUndefined
isGiven: isGiven
isMissing: isMissing
isPresent: isPresent
isBlank: isBlank
presence: presence
isObject: isObject
isFunction: isFunction
isString: isString
isBoolean: isBoolean
isNumber: isNumber
isElement: isElement
isJQuery: isJQuery
isElementish: isElementish
isPromise: isPromise
isOptions: isOptions
isArray: isArray
isFormData: isFormData
isNodeList: isNodeList
isArguments: isArguments
isList: isList
isRegExp: isRegExp
timer: scheduleTimer
contains: contains
objectContains: objectContains
toArray: toArray
pick: pick
pickBy: pickBy
omit: omit
unresolvablePromise: unresolvablePromise
remove: remove
memoize: memoize
pluckKey: pluckKey
renameKey: renameKey
extractOptions: extractOptions
extractCallback: extractCallback
noop: noop
asyncNoop: asyncNoop
identity: identity
escapeHTML: escapeHTML
escapeRegExp: escapeRegExp
sequence: sequence
# previewable: previewable
# parsePath: parsePath
evalOption: evalOption
# horizontalScreenHalf: horizontalScreenHalf
flatten: flatten
# flattenObject: flattenObject
isTruthy: isTruthy
newDeferred: newDeferred
always: always
# mutedFinally: mutedFinally
muteRejection: muteRejection
# rejectOnError: rejectOnError
asyncify: asyncify
isBasicObjectProperty: isBasicObjectProperty
isCrossOrigin: isCrossOrigin
task: queueTask
microtask: queueMicrotask
abortableMicrotask: abortableMicrotask
isEqual: isEqual
splitValues : splitValues
endsWith: endsWith
# sum: sum
# wrapArray: wrapArray
wrapList: wrapList
wrapValue: wrapValue
simpleEase: simpleEase
values: objectValues
# partial: partial
# partialRight: partialRight
arrayToSet: arrayToSet
setToArray: setToArray
# unprefixKeys: unprefixKeys
uid: uid
upperCaseFirst: upperCaseFirst
lowerCaseFirst: lowerCaseFirst
getter: defineGetter
delegate: defineDelegates
literal: literal
# asyncWrap: asyncWrap
reverse: reverse
prefixCamelCase: prefixCamelCase
unprefixCamelCase: unprefixCamelCase
camelToKebabCase: camelToKebabCase
nullToUndefined: nullToUndefined
sprintf: sprintf
sprintfWithFormattedArgs: sprintfWithFormattedArgs
renameKeys: renameKeys
timestamp: secondsSinceEpoch
allSettled: allSettled
|
[
{
"context": "sc6oIFXdfHHJEAuefFcjg8E40\", \"rev\": 3, \"dsid\": \".UI3UDtl4k2f2uQlST-5Sf5gnuqtB_rjUPvY7DZzRiGg\"}, {\"handle",
"end": 959,
"score": 0.5417376160621643,
"start": 956,
"tag": "KEY",
"value": "3UD"
},
{
"context": "FXdfHHJEAuefFcjg8E40\", \"rev\": 3, \"dsid\": \".UI3UDt... | test/src/fast/datastore/datastore_manager_test.coffee | noamraph/datastore-js | 0 | {ListDatastoresResponse, EventSourceWithInitialData} = Dropbox.Datastore.impl
class MockClient
constructor: ->
@nextResponse = null
_getNextResponse: ->
x = @nextResponse
assert x
@nextResponse = null
return x
isAuthenticated: -> true
_datastoreAwait: ->
# nothing for now
_getOrCreateDatastore: (dsid, cb) ->
cb null, @_getNextResponse()
_getDatastore: (dsid, cb) ->
cb null, @_getNextResponse()
_getSnapshot: (handle, cb) ->
cb null, @_getNextResponse()
_deleteDatastore: (handle, cb) ->
cb null, @_getNextResponse()
describe 'DatastoreManager', ->
it "parses list_datastores responses correctly", ->
m = new Dropbox.Datastore.DatastoreManager {
isAuthenticated: -> true
_datastoreAwait: -> null
}
infos = m._getOverlaidDatastoreInfosFromListResponse new ListDatastoresResponse {"datastores": [{"handle": "VU8wysc6oIFXdfHHJEAuefFcjg8E40", "rev": 3, "dsid": ".UI3UDtl4k2f2uQlST-5Sf5gnuqtB_rjUPvY7DZzRiGg"}, {"handle": "COTEgE3T4UITuztSY2eNHBYx3VLI3C", "rev": 1, "dsid": "default"}], "token": "853c478e022607229fa5a6e334f9aa0114fcc8b7f5beda2687138a8a65233a8c"}
expect(infos.length).to.equal 2
expect(infos[0].getId()).to.equal ".UI3UDtl4k2f2uQlST-5Sf5gnuqtB_rjUPvY7DZzRiGg"
expect(infos[1].getId()).to.equal "default"
describe 'running with mock client', ->
beforeEach ->
@mockClient = new MockClient
@datastoreManager = new Dropbox.Datastore.DatastoreManager @mockClient
it 'openDatastore() handles datastore not found', (done) ->
@mockClient.nextResponse = {"notfound": "it's not there"}
@datastoreManager.openDatastore "todosv5", (err, ds) ->
expect(ds).to.be.falsy
expect("#{err}").to.contain("Datastore todosv5 not found or not accessible")
done()
it 'deleteDatastore() handles datastore not found', (done) ->
@mockClient.nextResponse = {"notfound": "it's not there"}
@datastoreManager.deleteDatastore "todosv5", (err) ->
expect("#{err}").to.contain("Datastore todosv5 not found or not accessible")
done()
describe 'DatastoreManager EventSourceWithInitialData', ->
beforeEach ->
@s = new EventSourceWithInitialData
it "doesn't call the listener initially when there's no event", (done) ->
l1 = (data) =>
assert false, "should not be called"
@s.addListener l1
done()
it "calls the listener with the initial event", (done) ->
@s.dispatch "foo"
l1 = (data) =>
expect(data).to.equal "foo"
done()
@s.addListener l1
it "calls the listener when event is fired", (done) ->
l1 = (data) =>
expect(data).to.equal "bar"
done()
@s.addListener l1
@s.dispatch "bar"
| 185623 | {ListDatastoresResponse, EventSourceWithInitialData} = Dropbox.Datastore.impl
class MockClient
constructor: ->
@nextResponse = null
_getNextResponse: ->
x = @nextResponse
assert x
@nextResponse = null
return x
isAuthenticated: -> true
_datastoreAwait: ->
# nothing for now
_getOrCreateDatastore: (dsid, cb) ->
cb null, @_getNextResponse()
_getDatastore: (dsid, cb) ->
cb null, @_getNextResponse()
_getSnapshot: (handle, cb) ->
cb null, @_getNextResponse()
_deleteDatastore: (handle, cb) ->
cb null, @_getNextResponse()
describe 'DatastoreManager', ->
it "parses list_datastores responses correctly", ->
m = new Dropbox.Datastore.DatastoreManager {
isAuthenticated: -> true
_datastoreAwait: -> null
}
infos = m._getOverlaidDatastoreInfosFromListResponse new ListDatastoresResponse {"datastores": [{"handle": "VU8wysc6oIFXdfHHJEAuefFcjg8E40", "rev": 3, "dsid": ".UI<KEY>tl<KEY>"}, {"handle": "COTEgE3T4UITuztSY2eNHBYx3VLI3C", "rev": 1, "dsid": "default"}], "token": "<KEY> <PASSWORD>"}
expect(infos.length).to.equal 2
expect(infos[0].getId()).to.equal <KEY>"
expect(infos[1].getId()).to.equal "default"
describe 'running with mock client', ->
beforeEach ->
@mockClient = new MockClient
@datastoreManager = new Dropbox.Datastore.DatastoreManager @mockClient
it 'openDatastore() handles datastore not found', (done) ->
@mockClient.nextResponse = {"notfound": "it's not there"}
@datastoreManager.openDatastore "todosv5", (err, ds) ->
expect(ds).to.be.falsy
expect("#{err}").to.contain("Datastore todosv5 not found or not accessible")
done()
it 'deleteDatastore() handles datastore not found', (done) ->
@mockClient.nextResponse = {"notfound": "it's not there"}
@datastoreManager.deleteDatastore "todosv5", (err) ->
expect("#{err}").to.contain("Datastore todosv5 not found or not accessible")
done()
describe 'DatastoreManager EventSourceWithInitialData', ->
beforeEach ->
@s = new EventSourceWithInitialData
it "doesn't call the listener initially when there's no event", (done) ->
l1 = (data) =>
assert false, "should not be called"
@s.addListener l1
done()
it "calls the listener with the initial event", (done) ->
@s.dispatch "foo"
l1 = (data) =>
expect(data).to.equal "foo"
done()
@s.addListener l1
it "calls the listener when event is fired", (done) ->
l1 = (data) =>
expect(data).to.equal "bar"
done()
@s.addListener l1
@s.dispatch "bar"
| true | {ListDatastoresResponse, EventSourceWithInitialData} = Dropbox.Datastore.impl
class MockClient
constructor: ->
@nextResponse = null
_getNextResponse: ->
x = @nextResponse
assert x
@nextResponse = null
return x
isAuthenticated: -> true
_datastoreAwait: ->
# nothing for now
_getOrCreateDatastore: (dsid, cb) ->
cb null, @_getNextResponse()
_getDatastore: (dsid, cb) ->
cb null, @_getNextResponse()
_getSnapshot: (handle, cb) ->
cb null, @_getNextResponse()
_deleteDatastore: (handle, cb) ->
cb null, @_getNextResponse()
describe 'DatastoreManager', ->
it "parses list_datastores responses correctly", ->
m = new Dropbox.Datastore.DatastoreManager {
isAuthenticated: -> true
_datastoreAwait: -> null
}
infos = m._getOverlaidDatastoreInfosFromListResponse new ListDatastoresResponse {"datastores": [{"handle": "VU8wysc6oIFXdfHHJEAuefFcjg8E40", "rev": 3, "dsid": ".UIPI:KEY:<KEY>END_PItlPI:KEY:<KEY>END_PI"}, {"handle": "COTEgE3T4UITuztSY2eNHBYx3VLI3C", "rev": 1, "dsid": "default"}], "token": "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI"}
expect(infos.length).to.equal 2
expect(infos[0].getId()).to.equal PI:KEY:<KEY>END_PI"
expect(infos[1].getId()).to.equal "default"
describe 'running with mock client', ->
beforeEach ->
@mockClient = new MockClient
@datastoreManager = new Dropbox.Datastore.DatastoreManager @mockClient
it 'openDatastore() handles datastore not found', (done) ->
@mockClient.nextResponse = {"notfound": "it's not there"}
@datastoreManager.openDatastore "todosv5", (err, ds) ->
expect(ds).to.be.falsy
expect("#{err}").to.contain("Datastore todosv5 not found or not accessible")
done()
it 'deleteDatastore() handles datastore not found', (done) ->
@mockClient.nextResponse = {"notfound": "it's not there"}
@datastoreManager.deleteDatastore "todosv5", (err) ->
expect("#{err}").to.contain("Datastore todosv5 not found or not accessible")
done()
describe 'DatastoreManager EventSourceWithInitialData', ->
beforeEach ->
@s = new EventSourceWithInitialData
it "doesn't call the listener initially when there's no event", (done) ->
l1 = (data) =>
assert false, "should not be called"
@s.addListener l1
done()
it "calls the listener with the initial event", (done) ->
@s.dispatch "foo"
l1 = (data) =>
expect(data).to.equal "foo"
done()
@s.addListener l1
it "calls the listener when event is fired", (done) ->
l1 = (data) =>
expect(data).to.equal "bar"
done()
@s.addListener l1
@s.dispatch "bar"
|
[
{
"context": "f not password.match /^[0-9a-f]{32}$/\n\t\tpassword = utils.md5 utils.md5 password\n\treturn password\n\ncurrent_timestamp = ->\n\tnew Dat",
"end": 281,
"score": 0.9073479175567627,
"start": 253,
"tag": "PASSWORD",
"value": "utils.md5 utils.md5 password"
},
{
"context":... | firefox/lib/lixian.coffee | yineric/xunlei-lixian-web | 0 |
join_url = (base, url) ->
if url.match /^http:/i
return url
if url.match /^\//
return base.replace(/\/$/, '') + url
throw new Error("Not Implemented: #{url}")
encypt_password = (password) ->
if not password.match /^[0-9a-f]{32}$/
password = utils.md5 utils.md5 password
return password
current_timestamp = ->
new Date().getTime()
no_cache = (url) ->
if url.indexOf('?') == -1
url += '?'
else
url += '&'
url += 'nocache=' + current_timestamp()
################################################################################
# utils
################################################################################
utils =
encypt_password: encypt_password
md5: ->
throw new Error("Not Implemented: md5")
setTimeout: this.setTimeout
################################################################################
# task
################################################################################
status_map =
0: 'waiting'
1: 'downloading'
2: 'completed'
3: 'failed'
5: 'pending'
expired_map =
0: false
4: true
class Task
constructor: (json) ->
for k, v of json
@[k] = v
@type = @protocol = @url.match('^[^:]+')[0].toLowerCase()
@name = unescape(@taskname).replace /(&)+/g, '&'
@filename = @name
@full_path = @filename
@original_url = @url
@download_url = @lixian_url
@bt_hash = @cid
@size = parseInt @filesize
@size_text = parseInt @ysfilesize
@status = parseInt @download_status
@status_text = status_map[@download_status]
@expired = expired_map[@flag]
class TaskFile
constructor: (json) ->
for k, v of json
@[k] = v
@type = 'bt'
@index = @id
@id = @taskid
@name = @title.replace /(&)+/g, '&'
@filename = @name.replace /^.*\\/, ''
@dirs = @name.match(/^(.*)\\/)?[1].split('\\') ? []
@full_path = @dirs.concat([@filename]).join('/')
@original_url = @url
@download_url = @downurl
@size_text = @size
@size = parseInt @filesize
@status = parseInt @download_status
@status_text = status_map[@download_status]
################################################################################
# client
################################################################################
class XunleiClient
constructor: ->
@initialized = false
@id = null
@base_url = 'http://dynamic.cloud.vip.xunlei.com/'
@page_size = 100
@bt_page_size = 9999
get_domain_cookie: (domain, key) ->
throw new Error("Not Implemented: get_domain_cookie")
set_domain_cookie: (domain, key, value) ->
throw new Error("Not Implemented: set_domain_cookie")
get_cookie: (domain, key) ->
if not key?
key = domain
domain = "dynamic.cloud.vip.xunlei.com"
@get_domain_cookie domain, key
set_cookie: (domain, key, value) ->
@set_domain_cookie domain, key, value
http_get: (url, callback) ->
throw new Error("Not Implemented: http_get")
http_post: (url, form, callback) ->
throw new Error("Not Implemented: http_post")
http_upload: (url, form, callback) ->
throw new Error("Not Implemented: http_upload")
http_form: ->
throw new Error("Not Implemented: http_upload")
url: (u) ->
join_url(@base_url, u)
get: (url, callback) -> # support auto-relogin relavant url
url = @url url
@http_get url, (result) =>
if @auto_relogin and @is_session_timed_out_response(result.text)
@auto_login (result) =>
if result.ok
@http_get url, callback
else
callback result
else
callback result
post: (url, form, callback) -> # support auto-relogin relavant url
url = @url url
@http_post url, form, (result) =>
if @auto_relogin and @is_session_timed_out_response(result.text)
@auto_login (result) =>
if result.ok
@http_post url, form, callback
else
callback result
else
callback result
upload: (url, form, callback) -> # support auto-relogin relavant url
url = @url url
@login_check =>
# TODO: check response for session timeout
@http_upload url, form, callback
init: (callback) ->
if @initialized
callback()
return
@get_json @to_page_url(0, 1), (data) ->
@initialized = true
callback()
#########
# login #
#########
is_session_timed_out_response: (text) ->
text == '''<script>document.cookie ="sessionid=; path=/; domain=xunlei.com"; document.cookie ="lx_sessionid=; path=/; domain=vip.xunlei.com";top.location='http://lixian.vip.xunlei.com/task.html?error=1'</script>'''
get_id_from_cookie: ->
@get_cookie('xunlei.com', 'userid')
login_with_verification_code: (username, password, verification_code, callback) ->
@last_username = username
@last_login_time = new Date
password = encypt_password password
verification_code = verification_code?.toUpperCase()
password = utils.md5 password + verification_code
login_url = 'http://login.xunlei.com/sec2login/'
form =
u: username
p: password
verifycode: verification_code
@http_post login_url, form, ({text}) =>
if not @get_id_from_cookie()
callback? ok: false
else
callback? ok: true
login_without_retry: (username, password, callback) ->
cachetime = current_timestamp()
check_url = no_cache "http://login.xunlei.com/check?u=#{username}"
@http_get check_url, ({text}) =>
verification_code = @get_cookie('check_result')?.substr(2)
if verification_code
@login_with_verification_code username, password, verification_code, callback
else
callback
ok: false
reason: "Verification code required"
verification_code: no_cache "http://verify2.xunlei.com/image?t=MVA"
login_with_retry: (username, password, callback, retries=30) ->
@login_without_retry username, password, (result) =>
if result.ok
callback result
else if result.verification_code
callback result
else if retries > 0
console.log "login failed, retrying..."
utils.setTimeout =>
@login_with_retry username, password, callback, retries-1
, 1000
else
callback result
login: (username, password, callback) ->
@login_with_retry username, password, callback
login_enrich_cookie: (callback) ->
cachetime = current_timestamp()
check_url = no_cache "http://dynamic.cloud.vip.xunlei.com/interface/verify_login"
@http_get check_url, ({text}) =>
if text == '({"result":0})'
callback
ok: false
reason: "Session timed out" # XXX: or already logged in?
else
m = text.match /^verify_login_resp\((\{.*\})\)$/
if m
json = JSON.parse(m[1])
if json.result == 1
for k, v of json.data
@set_cookie '.xunlei.com', k, v
@set_cookie '.xunlei.com', 'sessionid', @get_cookie '.xunlei.com', 'lsessionid'
callback ok: true
else
callback
ok: false
reason: "result: #{json.result}"
response: text
else
callback
ok: false
reason: "Can't parse response"
response: text
auto_login: (callback) ->
console.log "session timedout. trying to relogin..."
if @username and @password
@login @username, @password, (result) =>
if result.ok
callback result
else if result.verification_code
if @require_login
@require_login
username: @username
password: @password
verification_code: result.verification_code
, ({username, password, verification_code}) =>
@username = username
@password = password
@login_with_verification_code @username, @password, verification_code, callback
else
callback result
else
callback result
else
@require_login
username: @username
password: @password
, ({username, password}) =>
@username = username
@password = password
@auto_login callback
login_check: (callback) ->
# if @get_cookie('.xunlei.com', 'sessionid')
# throw new Error("Not Implemented: login_check")
# else if @get_cookie '.xunlei.com', 'lsessionid'
# @login_enrich_cookie (result) =>
# if result.ok
# callback result
# else
# callback ok: false
# else
# callback ok: false, reason: 'No session found'
if not (@get_cookie('xunlei.com', 'userid') and @get_cookie('.xunlei.com', 'sessionid'))
@login_enrich_cookie (result) =>
if result.ok
callback result
else
if @auto_relogin
@auto_login (result) =>
callback result
else
callback ok: false, reason: 'auto-relogin is disabled'
else
callback ok: true
# TODO:
auto_relogin_for: ({url, form, pattern, callback}) ->
if form?
request = (callback) => @post url, form, callback
else
request = (callback) => @get url, callback
if Object.prototype.toString.call(pattern) == '[object RegExp]'
is_timeout = (text) -> pattern.match text
else
is_timeout = (text) -> text == pattern
relogin = =>
@auto_login (result) =>
if result.ok
request (result) =>
callback result
else
callback result
start = =>
request (result) =>
{text} = result
if is_timeout(text) and @auto_relogin
relogin()
else
callback result
@login_check =>
start()
with_id: (callback) ->
@login_check =>
callback @get_id_from_cookie()
#######
# add #
#######
add_simple_task: (url, callback) ->
throw new Error("Not Implemented: add_simple_task")
upload_torrent_file_by_blob: (blob, callback) ->
upload_url = '/interface/torrent_upload'
form = new @http_form()
form.append 'filepath', blob, 'attachment.torrent'
@upload upload_url, form, ({text}) =>
upload_failed = text?.match(/<script>document\.domain="xunlei\.com";var btResult =(\{"ret_value":0\});<\/script>/)?[1]
upload_success = text?.match(/<script>document\.domain="xunlei\.com";var btResult =(\{.*\});<\/script>/)?[1]
already_exists = text?.match(/parent\.edit_bt_list\((\{.*\}),'','0'\)/)?[1]
if upload_failed?
callback ok: false, reason: 'Upload failed', response: text
else if upload_success?
result = JSON.parse upload_success
callback
ok: true
done: false
info_hash: result['infoid']
name: result['ftitle']
size: result['btsize']
files: (id: x.id, name: x.subtitle, size: x.subsize for x in result['filelist'])
else if already_exists?
result = JSON.parse already_exists
callback
ok: true
done: true
info_hash: result['infoid']
else
callback ok: false, reason: 'Failed be parse upload result', response: text
parse_jsonp_response: (response, jsonp) ->
code = response.match("^#{jsonp}\\((.+)\\)$")?[1]
if code?
return JSON.parse code
commit_bt_task: ({info_hash, name, size, files}, callback) ->
@with_id (id) =>
form =
uid: id
btname: name
cid: info_hash
tsize: size
findex: (f['id']+'_' for f in files).join('')
size: (f['size']+'_' for f in files).join('')
from: '0'
try_commit = =>
jsonp = "jsonp#{current_timestamp()}"
commit_url = "/interface/bt_task_commit?callback=#{jsonp}"
@post commit_url, form, ({text}) =>
result = @parse_jsonp_response text, jsonp
if result?.progress? and result.progress not in [-12, -11]
callback ok: true, reason: 'BT task created', info_hash: info_hash
else if result?.progress in [-12, -11]
if @require_verification_code
@require_verification_code (verification_code) ->
form.verify_code = verification_code
try_commit()
else
callback ok: false, reason: 'Verification code required', response: text
else
callback ok: false, reason: 'Failed be parse bt result', detail: "Failed be parse bt result: #{text}", response: text
try_commit()
add_bt_task_by_blob: (blob, callback) ->
@upload_torrent_file_by_blob blob, (result) =>
if result.ok and not result.done
@commit_bt_task result, callback
else
callback result
query_bt_task_by_url: (url, callback) ->
url = "/interface/url_query?callback=queryUrl&u=#{encodeURIComponent url}&random=#{current_timestamp()}"
@get url, ({text}) =>
m = text.match /^queryUrl(\(1,.*\))\s*$/ # XXX: sometimes it returns queryUrl(0,...)?
if m
[_, cid, tsize, btname, _, names, sizes_, sizes, _, types, findexes, timestamp, _] = @parse_queryUrl text
callback
ok: true
done: false
info_hash: cid
name: btname
size: tsize
files: (name: name, id: findexes[i], size: sizes[i] for name, i in names)
else
m = text.match /^queryUrl\(-1,'([^']{40})/
if m
callback ok: true, done: true, reason: 'BT task alrady exists', info_hash: m[1]
else
callback ok: false, reason: 'Failed to add bt task', response: text
add_bt_task_by_query_url: (url, callback) ->
@query_bt_task_by_url url, (result) =>
if result.ok and not result.done
@commit_bt_task result, callback
else
callback result
add_bt_task_by_info_hash: (hash, callback) ->
hash = hash.toUpperCase()
@with_id (id) =>
url = "http://dynamic.cloud.vip.xunlei.com/interface/get_torrent?userid=#{id}&infoid=#{hash}"
@add_bt_task_by_query_url url, callback
add_magnet_task: (url, callback) ->
@login_check =>
# TODO: check response for session timeout
@add_bt_task_by_query_url url, callback
add_task: (url, callback) ->
throw new Error("Not Implemented: add_task")
add_batch_tasks: (urls, callback) ->
urls = (url for url in urls when url.match(/^(http|https|ftp|ed2k|thunder):/i))
if not urls
callback ok: false, reason: 'No valid URL found'
return
form = {}
for url, i in urls
form["cid[#{i}]"] = ''
form["url[#{i}]"] = url
form['batch_old_taskid'] = '0' + ('' for [0...urls.length]).join(',')
try_add = =>
jsonp = "jsonp#{current_timestamp()}"
url = "/interface/batch_task_commit?callback=#{jsonp}"
# @post url, form, callback
@auto_relogin_for
url: url
form: form
pattern: '''<script>document.cookie ="sessionid=; path=/; domain=xunlei.com"; document.cookie ="lx_sessionid=; path=/; domain=vip.xunlei.com";top.location='http://lixian.vip.xunlei.com/task.html?error=1'</script>'''
callback: (result) =>
if result.ok
text = result.text
code = @parse_jsonp_response text, jsonp
if code? and code not in [-12, -11]
callback ok: true
else if code in [-12, -11]
if @require_verification_code
@require_verification_code (verification_code) ->
form.verify_code = verification_code
try_add()
else
callback ok: false, reason: 'Verification code required', response: text
else
callback ok: false, reason: 'jsonp', detail: text, response: text
else
callback result
try_add()
########
# list #
########
set_page_size_in_cokie: (size) ->
@set_cookie '.vip.xunlei.com', 'pagenum', size
to_page_url: (type_id, page_index, page_size) ->
# type_id: 1 for downloading, 2 for completed, 4 for downloading+completed+expired, 11 for deleted, 13 for expired
if type_id == 0
type_id = 4
page = page_index + 1
p = 1 # XXX: what is it?
url = no_cache "/interface/showtask_unfresh?type_id=#{type_id}&page=#{page}&tasknum=#{page_size}&p=#{p}&interfrom=task"
return url
parse_rebuild: (text) ->
m = text.match /^rebuild\((\{(.+)\})\)$/
if m
result = JSON.parse(m[1])
if result.rtcode == 0
info = result.info
info.ok = true
info.tasks = (new Task(t) for t in info.tasks)
info.total = info.total_num
info
else
ok: false
reason: "rtcode: #{result.rtcode}"
response: text
else
ok: false
reason: "Can't parse response"
response: text
list_tasks_by: (type_id, page_index, page_size, callback) ->
url = @to_page_url type_id, page_index, page_size
@auto_relogin_for
url: url
pattern: 'rebuild({"rtcode":-1,"list":[]})'
callback: (result) =>
if result.ok
callback @parse_rebuild result.text
else
callback result
list_tasks_by_page: (page_index, callback) ->
@list_tasks_by 4, page_index, @page_size, callback
parse_fill_bt_list: (text) ->
m = text.match /^fill_bt_list\((\{(.+)\})\)$/
if m
json = JSON.parse(m[1])
if json.Result?.Record?
ok: true
files: (new TaskFile(f) for f in json.Result.Record)
total: json.Result.btnum
json: json
else
ok: false
reason: "Can't find Result.Record"
response: text
else
ok: false
reason: "Can't parse response"
response: text
list_bt: (task, callback) ->
if task.type != 'bt'
callback ok: false, reason: 'Not a bt task'
return
@with_id (id) =>
url = no_cache "/interface/fill_bt_list?callback=fill_bt_list&tid=#{task.id}&infoid=#{task.bt_hash}&g_net=1&p=1&uid=#{id}"
@set_page_size_in_cokie 9999
@get url, ({text}) =>
result = @parse_fill_bt_list text
{ok, files} = result
if ok
unless files.length == 1 and files[0].name == task.name
for file in files
file.dirs.unshift task.name
# file.dirname = file.dirs.join '/'
file.full_path = task.name + '/' + file.full_path
callback result
##########
# delete #
##########
delete_tasks_by_id: (ids, callback) ->
jsonp = "jsonp#{current_timestamp()}"
form =
taskids: ids.join(',')+','
databases: '0,'
url = no_cache "/interface/task_delete?callback=#{jsonp}&type=2" # XXX: what is 'type'?
@post url, form, (result) ->
if result.ok
if result.text == """#{jsonp}({"result":1,"type":2})"""
callback ok: true
else
callback
ok: false
reason: "Can't parse response"
response: result.text
else
callback result
delete_task_by_id: (id, callback) ->
@delete_tasks_by_id [id], callback
################################################################################
# export
################################################################################
module.exports =
XunleiClient: XunleiClient
utils: utils
| 50795 |
join_url = (base, url) ->
if url.match /^http:/i
return url
if url.match /^\//
return base.replace(/\/$/, '') + url
throw new Error("Not Implemented: #{url}")
encypt_password = (password) ->
if not password.match /^[0-9a-f]{32}$/
password = <PASSWORD>
return password
current_timestamp = ->
new Date().getTime()
no_cache = (url) ->
if url.indexOf('?') == -1
url += '?'
else
url += '&'
url += 'nocache=' + current_timestamp()
################################################################################
# utils
################################################################################
utils =
encypt_password: <PASSWORD>
md5: ->
throw new Error("Not Implemented: md5")
setTimeout: this.setTimeout
################################################################################
# task
################################################################################
status_map =
0: 'waiting'
1: 'downloading'
2: 'completed'
3: 'failed'
5: 'pending'
expired_map =
0: false
4: true
class Task
constructor: (json) ->
for k, v of json
@[k] = v
@type = @protocol = @url.match('^[^:]+')[0].toLowerCase()
@name = unescape(@taskname).replace /(&)+/g, '&'
@filename = @name
@full_path = @filename
@original_url = @url
@download_url = @lixian_url
@bt_hash = @cid
@size = parseInt @filesize
@size_text = parseInt @ysfilesize
@status = parseInt @download_status
@status_text = status_map[@download_status]
@expired = expired_map[@flag]
class TaskFile
constructor: (json) ->
for k, v of json
@[k] = v
@type = 'bt'
@index = @id
@id = @taskid
@name = @title.replace /(&)+/g, '&'
@filename = @name.replace /^.*\\/, ''
@dirs = @name.match(/^(.*)\\/)?[1].split('\\') ? []
@full_path = @dirs.concat([@filename]).join('/')
@original_url = @url
@download_url = @downurl
@size_text = @size
@size = parseInt @filesize
@status = parseInt @download_status
@status_text = status_map[@download_status]
################################################################################
# client
################################################################################
class XunleiClient
constructor: ->
@initialized = false
@id = null
@base_url = 'http://dynamic.cloud.vip.xunlei.com/'
@page_size = 100
@bt_page_size = 9999
get_domain_cookie: (domain, key) ->
throw new Error("Not Implemented: get_domain_cookie")
set_domain_cookie: (domain, key, value) ->
throw new Error("Not Implemented: set_domain_cookie")
get_cookie: (domain, key) ->
if not key?
key = domain
domain = "dynamic.cloud.vip.xunlei.com"
@get_domain_cookie domain, key
set_cookie: (domain, key, value) ->
@set_domain_cookie domain, key, value
http_get: (url, callback) ->
throw new Error("Not Implemented: http_get")
http_post: (url, form, callback) ->
throw new Error("Not Implemented: http_post")
http_upload: (url, form, callback) ->
throw new Error("Not Implemented: http_upload")
http_form: ->
throw new Error("Not Implemented: http_upload")
url: (u) ->
join_url(@base_url, u)
get: (url, callback) -> # support auto-relogin relavant url
url = @url url
@http_get url, (result) =>
if @auto_relogin and @is_session_timed_out_response(result.text)
@auto_login (result) =>
if result.ok
@http_get url, callback
else
callback result
else
callback result
post: (url, form, callback) -> # support auto-relogin relavant url
url = @url url
@http_post url, form, (result) =>
if @auto_relogin and @is_session_timed_out_response(result.text)
@auto_login (result) =>
if result.ok
@http_post url, form, callback
else
callback result
else
callback result
upload: (url, form, callback) -> # support auto-relogin relavant url
url = @url url
@login_check =>
# TODO: check response for session timeout
@http_upload url, form, callback
init: (callback) ->
if @initialized
callback()
return
@get_json @to_page_url(0, 1), (data) ->
@initialized = true
callback()
#########
# login #
#########
is_session_timed_out_response: (text) ->
text == '''<script>document.cookie ="sessionid=; path=/; domain=xunlei.com"; document.cookie ="lx_sessionid=; path=/; domain=vip.xunlei.com";top.location='http://lixian.vip.xunlei.com/task.html?error=1'</script>'''
get_id_from_cookie: ->
@get_cookie('xunlei.com', 'userid')
login_with_verification_code: (username, password, verification_code, callback) ->
@last_username = username
@last_login_time = new Date
password = <PASSWORD>
verification_code = verification_code?.toUpperCase()
password = <PASSWORD> + verification_code
login_url = 'http://login.xunlei.com/sec2login/'
form =
u: username
p: <PASSWORD>
verifycode: verification_code
@http_post login_url, form, ({text}) =>
if not @get_id_from_cookie()
callback? ok: false
else
callback? ok: true
login_without_retry: (username, password, callback) ->
cachetime = current_timestamp()
check_url = no_cache "http://login.xunlei.com/check?u=#{username}"
@http_get check_url, ({text}) =>
verification_code = @get_cookie('check_result')?.substr(2)
if verification_code
@login_with_verification_code username, password, verification_code, callback
else
callback
ok: false
reason: "Verification code required"
verification_code: no_cache "http://verify2.xunlei.com/image?t=MVA"
login_with_retry: (username, password, callback, retries=30) ->
@login_without_retry username, password, (result) =>
if result.ok
callback result
else if result.verification_code
callback result
else if retries > 0
console.log "login failed, retrying..."
utils.setTimeout =>
@login_with_retry username, password, callback, retries-1
, 1000
else
callback result
login: (username, password, callback) ->
@login_with_retry username, password, callback
login_enrich_cookie: (callback) ->
cachetime = current_timestamp()
check_url = no_cache "http://dynamic.cloud.vip.xunlei.com/interface/verify_login"
@http_get check_url, ({text}) =>
if text == '({"result":0})'
callback
ok: false
reason: "Session timed out" # XXX: or already logged in?
else
m = text.match /^verify_login_resp\((\{.*\})\)$/
if m
json = JSON.parse(m[1])
if json.result == 1
for k, v of json.data
@set_cookie '.xunlei.com', k, v
@set_cookie '.xunlei.com', 'sessionid', @get_cookie '.xunlei.com', 'lsessionid'
callback ok: true
else
callback
ok: false
reason: "result: #{json.result}"
response: text
else
callback
ok: false
reason: "Can't parse response"
response: text
auto_login: (callback) ->
console.log "session timedout. trying to relogin..."
if @username and @password
@login @username, @password, (result) =>
if result.ok
callback result
else if result.verification_code
if @require_login
@require_login
username: @username
password: <PASSWORD>
verification_code: result.verification_code
, ({username, password, verification_code}) =>
@username = username
@password = <PASSWORD>
@login_with_verification_code @username, @password, verification_code, callback
else
callback result
else
callback result
else
@require_login
username: @username
password: <PASSWORD>
, ({username, password}) =>
@username = username
@password = <PASSWORD>
@auto_login callback
login_check: (callback) ->
# if @get_cookie('.xunlei.com', 'sessionid')
# throw new Error("Not Implemented: login_check")
# else if @get_cookie '.xunlei.com', 'lsessionid'
# @login_enrich_cookie (result) =>
# if result.ok
# callback result
# else
# callback ok: false
# else
# callback ok: false, reason: 'No session found'
if not (@get_cookie('xunlei.com', 'userid') and @get_cookie('.xunlei.com', 'sessionid'))
@login_enrich_cookie (result) =>
if result.ok
callback result
else
if @auto_relogin
@auto_login (result) =>
callback result
else
callback ok: false, reason: 'auto-relogin is disabled'
else
callback ok: true
# TODO:
auto_relogin_for: ({url, form, pattern, callback}) ->
if form?
request = (callback) => @post url, form, callback
else
request = (callback) => @get url, callback
if Object.prototype.toString.call(pattern) == '[object RegExp]'
is_timeout = (text) -> pattern.match text
else
is_timeout = (text) -> text == pattern
relogin = =>
@auto_login (result) =>
if result.ok
request (result) =>
callback result
else
callback result
start = =>
request (result) =>
{text} = result
if is_timeout(text) and @auto_relogin
relogin()
else
callback result
@login_check =>
start()
with_id: (callback) ->
@login_check =>
callback @get_id_from_cookie()
#######
# add #
#######
add_simple_task: (url, callback) ->
throw new Error("Not Implemented: add_simple_task")
upload_torrent_file_by_blob: (blob, callback) ->
upload_url = '/interface/torrent_upload'
form = new @http_form()
form.append 'filepath', blob, 'attachment.torrent'
@upload upload_url, form, ({text}) =>
upload_failed = text?.match(/<script>document\.domain="xunlei\.com";var btResult =(\{"ret_value":0\});<\/script>/)?[1]
upload_success = text?.match(/<script>document\.domain="xunlei\.com";var btResult =(\{.*\});<\/script>/)?[1]
already_exists = text?.match(/parent\.edit_bt_list\((\{.*\}),'','0'\)/)?[1]
if upload_failed?
callback ok: false, reason: 'Upload failed', response: text
else if upload_success?
result = JSON.parse upload_success
callback
ok: true
done: false
info_hash: result['infoid']
name: result['ftitle']
size: result['btsize']
files: (id: x.id, name: x.subtitle, size: x.subsize for x in result['filelist'])
else if already_exists?
result = JSON.parse already_exists
callback
ok: true
done: true
info_hash: result['infoid']
else
callback ok: false, reason: 'Failed be parse upload result', response: text
parse_jsonp_response: (response, jsonp) ->
code = response.match("^#{jsonp}\\((.+)\\)$")?[1]
if code?
return JSON.parse code
commit_bt_task: ({info_hash, name, size, files}, callback) ->
@with_id (id) =>
form =
uid: id
btname: <NAME>
cid: info_hash
tsize: size
findex: (f['id']+'_' for f in files).join('')
size: (f['size']+'_' for f in files).join('')
from: '0'
try_commit = =>
jsonp = "jsonp#{current_timestamp()}"
commit_url = "/interface/bt_task_commit?callback=#{jsonp}"
@post commit_url, form, ({text}) =>
result = @parse_jsonp_response text, jsonp
if result?.progress? and result.progress not in [-12, -11]
callback ok: true, reason: 'BT task created', info_hash: info_hash
else if result?.progress in [-12, -11]
if @require_verification_code
@require_verification_code (verification_code) ->
form.verify_code = verification_code
try_commit()
else
callback ok: false, reason: 'Verification code required', response: text
else
callback ok: false, reason: 'Failed be parse bt result', detail: "Failed be parse bt result: #{text}", response: text
try_commit()
add_bt_task_by_blob: (blob, callback) ->
@upload_torrent_file_by_blob blob, (result) =>
if result.ok and not result.done
@commit_bt_task result, callback
else
callback result
query_bt_task_by_url: (url, callback) ->
url = "/interface/url_query?callback=queryUrl&u=#{encodeURIComponent url}&random=#{current_timestamp()}"
@get url, ({text}) =>
m = text.match /^queryUrl(\(1,.*\))\s*$/ # XXX: sometimes it returns queryUrl(0,...)?
if m
[_, cid, tsize, btname, _, names, sizes_, sizes, _, types, findexes, timestamp, _] = @parse_queryUrl text
callback
ok: true
done: false
info_hash: cid
name: btname
size: tsize
files: (name: name, id: findexes[i], size: sizes[i] for name, i in names)
else
m = text.match /^queryUrl\(-1,'([^']{40})/
if m
callback ok: true, done: true, reason: 'BT task alrady exists', info_hash: m[1]
else
callback ok: false, reason: 'Failed to add bt task', response: text
add_bt_task_by_query_url: (url, callback) ->
@query_bt_task_by_url url, (result) =>
if result.ok and not result.done
@commit_bt_task result, callback
else
callback result
add_bt_task_by_info_hash: (hash, callback) ->
hash = hash.toUpperCase()
@with_id (id) =>
url = "http://dynamic.cloud.vip.xunlei.com/interface/get_torrent?userid=#{id}&infoid=#{hash}"
@add_bt_task_by_query_url url, callback
add_magnet_task: (url, callback) ->
@login_check =>
# TODO: check response for session timeout
@add_bt_task_by_query_url url, callback
add_task: (url, callback) ->
throw new Error("Not Implemented: add_task")
add_batch_tasks: (urls, callback) ->
urls = (url for url in urls when url.match(/^(http|https|ftp|ed2k|thunder):/i))
if not urls
callback ok: false, reason: 'No valid URL found'
return
form = {}
for url, i in urls
form["cid[#{i}]"] = ''
form["url[#{i}]"] = url
form['batch_old_taskid'] = '0' + ('' for [0...urls.length]).join(',')
try_add = =>
jsonp = "jsonp#{current_timestamp()}"
url = "/interface/batch_task_commit?callback=#{jsonp}"
# @post url, form, callback
@auto_relogin_for
url: url
form: form
pattern: '''<script>document.cookie ="sessionid=; path=/; domain=xunlei.com"; document.cookie ="lx_sessionid=; path=/; domain=vip.xunlei.com";top.location='http://lixian.vip.xunlei.com/task.html?error=1'</script>'''
callback: (result) =>
if result.ok
text = result.text
code = @parse_jsonp_response text, jsonp
if code? and code not in [-12, -11]
callback ok: true
else if code in [-12, -11]
if @require_verification_code
@require_verification_code (verification_code) ->
form.verify_code = verification_code
try_add()
else
callback ok: false, reason: 'Verification code required', response: text
else
callback ok: false, reason: 'jsonp', detail: text, response: text
else
callback result
try_add()
########
# list #
########
set_page_size_in_cokie: (size) ->
@set_cookie '.vip.xunlei.com', 'pagenum', size
to_page_url: (type_id, page_index, page_size) ->
# type_id: 1 for downloading, 2 for completed, 4 for downloading+completed+expired, 11 for deleted, 13 for expired
if type_id == 0
type_id = 4
page = page_index + 1
p = 1 # XXX: what is it?
url = no_cache "/interface/showtask_unfresh?type_id=#{type_id}&page=#{page}&tasknum=#{page_size}&p=#{p}&interfrom=task"
return url
parse_rebuild: (text) ->
m = text.match /^rebuild\((\{(.+)\})\)$/
if m
result = JSON.parse(m[1])
if result.rtcode == 0
info = result.info
info.ok = true
info.tasks = (new Task(t) for t in info.tasks)
info.total = info.total_num
info
else
ok: false
reason: "rtcode: #{result.rtcode}"
response: text
else
ok: false
reason: "Can't parse response"
response: text
list_tasks_by: (type_id, page_index, page_size, callback) ->
url = @to_page_url type_id, page_index, page_size
@auto_relogin_for
url: url
pattern: 'rebuild({"rtcode":-1,"list":[]})'
callback: (result) =>
if result.ok
callback @parse_rebuild result.text
else
callback result
list_tasks_by_page: (page_index, callback) ->
@list_tasks_by 4, page_index, @page_size, callback
parse_fill_bt_list: (text) ->
m = text.match /^fill_bt_list\((\{(.+)\})\)$/
if m
json = JSON.parse(m[1])
if json.Result?.Record?
ok: true
files: (new TaskFile(f) for f in json.Result.Record)
total: json.Result.btnum
json: json
else
ok: false
reason: "Can't find Result.Record"
response: text
else
ok: false
reason: "Can't parse response"
response: text
list_bt: (task, callback) ->
if task.type != 'bt'
callback ok: false, reason: 'Not a bt task'
return
@with_id (id) =>
url = no_cache "/interface/fill_bt_list?callback=fill_bt_list&tid=#{task.id}&infoid=#{task.bt_hash}&g_net=1&p=1&uid=#{id}"
@set_page_size_in_cokie 9999
@get url, ({text}) =>
result = @parse_fill_bt_list text
{ok, files} = result
if ok
unless files.length == 1 and files[0].name == task.name
for file in files
file.dirs.unshift task.name
# file.dirname = file.dirs.join '/'
file.full_path = task.name + '/' + file.full_path
callback result
##########
# delete #
##########
delete_tasks_by_id: (ids, callback) ->
jsonp = "jsonp#{current_timestamp()}"
form =
taskids: ids.join(',')+','
databases: '0,'
url = no_cache "/interface/task_delete?callback=#{jsonp}&type=2" # XXX: what is 'type'?
@post url, form, (result) ->
if result.ok
if result.text == """#{jsonp}({"result":1,"type":2})"""
callback ok: true
else
callback
ok: false
reason: "Can't parse response"
response: result.text
else
callback result
delete_task_by_id: (id, callback) ->
@delete_tasks_by_id [id], callback
################################################################################
# export
################################################################################
module.exports =
XunleiClient: XunleiClient
utils: utils
| true |
join_url = (base, url) ->
if url.match /^http:/i
return url
if url.match /^\//
return base.replace(/\/$/, '') + url
throw new Error("Not Implemented: #{url}")
encypt_password = (password) ->
if not password.match /^[0-9a-f]{32}$/
password = PI:PASSWORD:<PASSWORD>END_PI
return password
current_timestamp = ->
new Date().getTime()
no_cache = (url) ->
if url.indexOf('?') == -1
url += '?'
else
url += '&'
url += 'nocache=' + current_timestamp()
################################################################################
# utils
################################################################################
utils =
encypt_password: PI:PASSWORD:<PASSWORD>END_PI
md5: ->
throw new Error("Not Implemented: md5")
setTimeout: this.setTimeout
################################################################################
# task
################################################################################
status_map =
0: 'waiting'
1: 'downloading'
2: 'completed'
3: 'failed'
5: 'pending'
expired_map =
0: false
4: true
class Task
constructor: (json) ->
for k, v of json
@[k] = v
@type = @protocol = @url.match('^[^:]+')[0].toLowerCase()
@name = unescape(@taskname).replace /(&)+/g, '&'
@filename = @name
@full_path = @filename
@original_url = @url
@download_url = @lixian_url
@bt_hash = @cid
@size = parseInt @filesize
@size_text = parseInt @ysfilesize
@status = parseInt @download_status
@status_text = status_map[@download_status]
@expired = expired_map[@flag]
class TaskFile
constructor: (json) ->
for k, v of json
@[k] = v
@type = 'bt'
@index = @id
@id = @taskid
@name = @title.replace /(&)+/g, '&'
@filename = @name.replace /^.*\\/, ''
@dirs = @name.match(/^(.*)\\/)?[1].split('\\') ? []
@full_path = @dirs.concat([@filename]).join('/')
@original_url = @url
@download_url = @downurl
@size_text = @size
@size = parseInt @filesize
@status = parseInt @download_status
@status_text = status_map[@download_status]
################################################################################
# client
################################################################################
class XunleiClient
constructor: ->
@initialized = false
@id = null
@base_url = 'http://dynamic.cloud.vip.xunlei.com/'
@page_size = 100
@bt_page_size = 9999
get_domain_cookie: (domain, key) ->
throw new Error("Not Implemented: get_domain_cookie")
set_domain_cookie: (domain, key, value) ->
throw new Error("Not Implemented: set_domain_cookie")
get_cookie: (domain, key) ->
if not key?
key = domain
domain = "dynamic.cloud.vip.xunlei.com"
@get_domain_cookie domain, key
set_cookie: (domain, key, value) ->
@set_domain_cookie domain, key, value
http_get: (url, callback) ->
throw new Error("Not Implemented: http_get")
http_post: (url, form, callback) ->
throw new Error("Not Implemented: http_post")
http_upload: (url, form, callback) ->
throw new Error("Not Implemented: http_upload")
http_form: ->
throw new Error("Not Implemented: http_upload")
url: (u) ->
join_url(@base_url, u)
get: (url, callback) -> # support auto-relogin relavant url
url = @url url
@http_get url, (result) =>
if @auto_relogin and @is_session_timed_out_response(result.text)
@auto_login (result) =>
if result.ok
@http_get url, callback
else
callback result
else
callback result
post: (url, form, callback) -> # support auto-relogin relavant url
url = @url url
@http_post url, form, (result) =>
if @auto_relogin and @is_session_timed_out_response(result.text)
@auto_login (result) =>
if result.ok
@http_post url, form, callback
else
callback result
else
callback result
upload: (url, form, callback) -> # support auto-relogin relavant url
url = @url url
@login_check =>
# TODO: check response for session timeout
@http_upload url, form, callback
init: (callback) ->
if @initialized
callback()
return
@get_json @to_page_url(0, 1), (data) ->
@initialized = true
callback()
#########
# login #
#########
is_session_timed_out_response: (text) ->
text == '''<script>document.cookie ="sessionid=; path=/; domain=xunlei.com"; document.cookie ="lx_sessionid=; path=/; domain=vip.xunlei.com";top.location='http://lixian.vip.xunlei.com/task.html?error=1'</script>'''
get_id_from_cookie: ->
@get_cookie('xunlei.com', 'userid')
login_with_verification_code: (username, password, verification_code, callback) ->
@last_username = username
@last_login_time = new Date
password = PI:PASSWORD:<PASSWORD>END_PI
verification_code = verification_code?.toUpperCase()
password = PI:PASSWORD:<PASSWORD>END_PI + verification_code
login_url = 'http://login.xunlei.com/sec2login/'
form =
u: username
p: PI:PASSWORD:<PASSWORD>END_PI
verifycode: verification_code
@http_post login_url, form, ({text}) =>
if not @get_id_from_cookie()
callback? ok: false
else
callback? ok: true
login_without_retry: (username, password, callback) ->
cachetime = current_timestamp()
check_url = no_cache "http://login.xunlei.com/check?u=#{username}"
@http_get check_url, ({text}) =>
verification_code = @get_cookie('check_result')?.substr(2)
if verification_code
@login_with_verification_code username, password, verification_code, callback
else
callback
ok: false
reason: "Verification code required"
verification_code: no_cache "http://verify2.xunlei.com/image?t=MVA"
login_with_retry: (username, password, callback, retries=30) ->
@login_without_retry username, password, (result) =>
if result.ok
callback result
else if result.verification_code
callback result
else if retries > 0
console.log "login failed, retrying..."
utils.setTimeout =>
@login_with_retry username, password, callback, retries-1
, 1000
else
callback result
login: (username, password, callback) ->
@login_with_retry username, password, callback
login_enrich_cookie: (callback) ->
cachetime = current_timestamp()
check_url = no_cache "http://dynamic.cloud.vip.xunlei.com/interface/verify_login"
@http_get check_url, ({text}) =>
if text == '({"result":0})'
callback
ok: false
reason: "Session timed out" # XXX: or already logged in?
else
m = text.match /^verify_login_resp\((\{.*\})\)$/
if m
json = JSON.parse(m[1])
if json.result == 1
for k, v of json.data
@set_cookie '.xunlei.com', k, v
@set_cookie '.xunlei.com', 'sessionid', @get_cookie '.xunlei.com', 'lsessionid'
callback ok: true
else
callback
ok: false
reason: "result: #{json.result}"
response: text
else
callback
ok: false
reason: "Can't parse response"
response: text
auto_login: (callback) ->
console.log "session timedout. trying to relogin..."
if @username and @password
@login @username, @password, (result) =>
if result.ok
callback result
else if result.verification_code
if @require_login
@require_login
username: @username
password: PI:PASSWORD:<PASSWORD>END_PI
verification_code: result.verification_code
, ({username, password, verification_code}) =>
@username = username
@password = PI:PASSWORD:<PASSWORD>END_PI
@login_with_verification_code @username, @password, verification_code, callback
else
callback result
else
callback result
else
@require_login
username: @username
password: PI:PASSWORD:<PASSWORD>END_PI
, ({username, password}) =>
@username = username
@password = PI:PASSWORD:<PASSWORD>END_PI
@auto_login callback
login_check: (callback) ->
# if @get_cookie('.xunlei.com', 'sessionid')
# throw new Error("Not Implemented: login_check")
# else if @get_cookie '.xunlei.com', 'lsessionid'
# @login_enrich_cookie (result) =>
# if result.ok
# callback result
# else
# callback ok: false
# else
# callback ok: false, reason: 'No session found'
if not (@get_cookie('xunlei.com', 'userid') and @get_cookie('.xunlei.com', 'sessionid'))
@login_enrich_cookie (result) =>
if result.ok
callback result
else
if @auto_relogin
@auto_login (result) =>
callback result
else
callback ok: false, reason: 'auto-relogin is disabled'
else
callback ok: true
# TODO:
auto_relogin_for: ({url, form, pattern, callback}) ->
if form?
request = (callback) => @post url, form, callback
else
request = (callback) => @get url, callback
if Object.prototype.toString.call(pattern) == '[object RegExp]'
is_timeout = (text) -> pattern.match text
else
is_timeout = (text) -> text == pattern
relogin = =>
@auto_login (result) =>
if result.ok
request (result) =>
callback result
else
callback result
start = =>
request (result) =>
{text} = result
if is_timeout(text) and @auto_relogin
relogin()
else
callback result
@login_check =>
start()
with_id: (callback) ->
@login_check =>
callback @get_id_from_cookie()
#######
# add #
#######
add_simple_task: (url, callback) ->
throw new Error("Not Implemented: add_simple_task")
upload_torrent_file_by_blob: (blob, callback) ->
upload_url = '/interface/torrent_upload'
form = new @http_form()
form.append 'filepath', blob, 'attachment.torrent'
@upload upload_url, form, ({text}) =>
upload_failed = text?.match(/<script>document\.domain="xunlei\.com";var btResult =(\{"ret_value":0\});<\/script>/)?[1]
upload_success = text?.match(/<script>document\.domain="xunlei\.com";var btResult =(\{.*\});<\/script>/)?[1]
already_exists = text?.match(/parent\.edit_bt_list\((\{.*\}),'','0'\)/)?[1]
if upload_failed?
callback ok: false, reason: 'Upload failed', response: text
else if upload_success?
result = JSON.parse upload_success
callback
ok: true
done: false
info_hash: result['infoid']
name: result['ftitle']
size: result['btsize']
files: (id: x.id, name: x.subtitle, size: x.subsize for x in result['filelist'])
else if already_exists?
result = JSON.parse already_exists
callback
ok: true
done: true
info_hash: result['infoid']
else
callback ok: false, reason: 'Failed be parse upload result', response: text
parse_jsonp_response: (response, jsonp) ->
code = response.match("^#{jsonp}\\((.+)\\)$")?[1]
if code?
return JSON.parse code
commit_bt_task: ({info_hash, name, size, files}, callback) ->
@with_id (id) =>
form =
uid: id
btname: PI:NAME:<NAME>END_PI
cid: info_hash
tsize: size
findex: (f['id']+'_' for f in files).join('')
size: (f['size']+'_' for f in files).join('')
from: '0'
try_commit = =>
jsonp = "jsonp#{current_timestamp()}"
commit_url = "/interface/bt_task_commit?callback=#{jsonp}"
@post commit_url, form, ({text}) =>
result = @parse_jsonp_response text, jsonp
if result?.progress? and result.progress not in [-12, -11]
callback ok: true, reason: 'BT task created', info_hash: info_hash
else if result?.progress in [-12, -11]
if @require_verification_code
@require_verification_code (verification_code) ->
form.verify_code = verification_code
try_commit()
else
callback ok: false, reason: 'Verification code required', response: text
else
callback ok: false, reason: 'Failed be parse bt result', detail: "Failed be parse bt result: #{text}", response: text
try_commit()
add_bt_task_by_blob: (blob, callback) ->
@upload_torrent_file_by_blob blob, (result) =>
if result.ok and not result.done
@commit_bt_task result, callback
else
callback result
query_bt_task_by_url: (url, callback) ->
url = "/interface/url_query?callback=queryUrl&u=#{encodeURIComponent url}&random=#{current_timestamp()}"
@get url, ({text}) =>
m = text.match /^queryUrl(\(1,.*\))\s*$/ # XXX: sometimes it returns queryUrl(0,...)?
if m
[_, cid, tsize, btname, _, names, sizes_, sizes, _, types, findexes, timestamp, _] = @parse_queryUrl text
callback
ok: true
done: false
info_hash: cid
name: btname
size: tsize
files: (name: name, id: findexes[i], size: sizes[i] for name, i in names)
else
m = text.match /^queryUrl\(-1,'([^']{40})/
if m
callback ok: true, done: true, reason: 'BT task alrady exists', info_hash: m[1]
else
callback ok: false, reason: 'Failed to add bt task', response: text
add_bt_task_by_query_url: (url, callback) ->
@query_bt_task_by_url url, (result) =>
if result.ok and not result.done
@commit_bt_task result, callback
else
callback result
add_bt_task_by_info_hash: (hash, callback) ->
hash = hash.toUpperCase()
@with_id (id) =>
url = "http://dynamic.cloud.vip.xunlei.com/interface/get_torrent?userid=#{id}&infoid=#{hash}"
@add_bt_task_by_query_url url, callback
add_magnet_task: (url, callback) ->
@login_check =>
# TODO: check response for session timeout
@add_bt_task_by_query_url url, callback
add_task: (url, callback) ->
throw new Error("Not Implemented: add_task")
add_batch_tasks: (urls, callback) ->
urls = (url for url in urls when url.match(/^(http|https|ftp|ed2k|thunder):/i))
if not urls
callback ok: false, reason: 'No valid URL found'
return
form = {}
for url, i in urls
form["cid[#{i}]"] = ''
form["url[#{i}]"] = url
form['batch_old_taskid'] = '0' + ('' for [0...urls.length]).join(',')
try_add = =>
jsonp = "jsonp#{current_timestamp()}"
url = "/interface/batch_task_commit?callback=#{jsonp}"
# @post url, form, callback
@auto_relogin_for
url: url
form: form
pattern: '''<script>document.cookie ="sessionid=; path=/; domain=xunlei.com"; document.cookie ="lx_sessionid=; path=/; domain=vip.xunlei.com";top.location='http://lixian.vip.xunlei.com/task.html?error=1'</script>'''
callback: (result) =>
if result.ok
text = result.text
code = @parse_jsonp_response text, jsonp
if code? and code not in [-12, -11]
callback ok: true
else if code in [-12, -11]
if @require_verification_code
@require_verification_code (verification_code) ->
form.verify_code = verification_code
try_add()
else
callback ok: false, reason: 'Verification code required', response: text
else
callback ok: false, reason: 'jsonp', detail: text, response: text
else
callback result
try_add()
########
# list #
########
set_page_size_in_cokie: (size) ->
@set_cookie '.vip.xunlei.com', 'pagenum', size
to_page_url: (type_id, page_index, page_size) ->
# type_id: 1 for downloading, 2 for completed, 4 for downloading+completed+expired, 11 for deleted, 13 for expired
if type_id == 0
type_id = 4
page = page_index + 1
p = 1 # XXX: what is it?
url = no_cache "/interface/showtask_unfresh?type_id=#{type_id}&page=#{page}&tasknum=#{page_size}&p=#{p}&interfrom=task"
return url
parse_rebuild: (text) ->
m = text.match /^rebuild\((\{(.+)\})\)$/
if m
result = JSON.parse(m[1])
if result.rtcode == 0
info = result.info
info.ok = true
info.tasks = (new Task(t) for t in info.tasks)
info.total = info.total_num
info
else
ok: false
reason: "rtcode: #{result.rtcode}"
response: text
else
ok: false
reason: "Can't parse response"
response: text
list_tasks_by: (type_id, page_index, page_size, callback) ->
url = @to_page_url type_id, page_index, page_size
@auto_relogin_for
url: url
pattern: 'rebuild({"rtcode":-1,"list":[]})'
callback: (result) =>
if result.ok
callback @parse_rebuild result.text
else
callback result
list_tasks_by_page: (page_index, callback) ->
@list_tasks_by 4, page_index, @page_size, callback
parse_fill_bt_list: (text) ->
m = text.match /^fill_bt_list\((\{(.+)\})\)$/
if m
json = JSON.parse(m[1])
if json.Result?.Record?
ok: true
files: (new TaskFile(f) for f in json.Result.Record)
total: json.Result.btnum
json: json
else
ok: false
reason: "Can't find Result.Record"
response: text
else
ok: false
reason: "Can't parse response"
response: text
list_bt: (task, callback) ->
if task.type != 'bt'
callback ok: false, reason: 'Not a bt task'
return
@with_id (id) =>
url = no_cache "/interface/fill_bt_list?callback=fill_bt_list&tid=#{task.id}&infoid=#{task.bt_hash}&g_net=1&p=1&uid=#{id}"
@set_page_size_in_cokie 9999
@get url, ({text}) =>
result = @parse_fill_bt_list text
{ok, files} = result
if ok
unless files.length == 1 and files[0].name == task.name
for file in files
file.dirs.unshift task.name
# file.dirname = file.dirs.join '/'
file.full_path = task.name + '/' + file.full_path
callback result
##########
# delete #
##########
delete_tasks_by_id: (ids, callback) ->
jsonp = "jsonp#{current_timestamp()}"
form =
taskids: ids.join(',')+','
databases: '0,'
url = no_cache "/interface/task_delete?callback=#{jsonp}&type=2" # XXX: what is 'type'?
@post url, form, (result) ->
if result.ok
if result.text == """#{jsonp}({"result":1,"type":2})"""
callback ok: true
else
callback
ok: false
reason: "Can't parse response"
response: result.text
else
callback result
delete_task_by_id: (id, callback) ->
@delete_tasks_by_id [id], callback
################################################################################
# export
################################################################################
module.exports =
XunleiClient: XunleiClient
utils: utils
|
[
{
"context": "# Droplet editor view.\n#\n# Copyright (c) 2015 Anthony Bau (dab1998@gmail.com)\n# MIT License\n\nhelper = requi",
"end": 57,
"score": 0.9998606443405151,
"start": 46,
"tag": "NAME",
"value": "Anthony Bau"
},
{
"context": " editor view.\n#\n# Copyright (c) 2015 Anthony ... | src/view.coffee | sanyaade-teachings/spresensedroplet | 0 | # Droplet editor view.
#
# Copyright (c) 2015 Anthony Bau (dab1998@gmail.com)
# MIT License
helper = require './helper.coffee'
draw = require './draw.coffee'
model = require './model.coffee'
NO_MULTILINE = 0
MULTILINE_START = 1
MULTILINE_MIDDLE = 2
MULTILINE_END = 3
MULTILINE_END_START = 4
ANY_DROP = helper.ANY_DROP
BLOCK_ONLY = helper.BLOCK_ONLY
MOSTLY_BLOCK = helper.MOSTLY_BLOCK
MOSTLY_VALUE = helper.MOSTLY_VALUE
VALUE_ONLY = helper.VALUE_ONLY
CARRIAGE_ARROW_SIDEALONG = 0
CARRIAGE_ARROW_INDENT = 1
CARRIAGE_ARROW_NONE = 2
CARRIAGE_GROW_DOWN = 3
DROPDOWN_ARROW_HEIGHT = 8
DROP_TRIANGLE_COLOR = '#555'
DROP_TRIANGLE_INVERT_COLOR = '#CCC'
BUTTON_GLYPH_COLOR = 'rgba(0, 0, 0, 0.3)'
BUTTON_GLYPH_INVERT_COLOR = 'rgba(255, 255, 255, 0.5)'
SVG_STANDARD = helper.SVG_STANDARD
DEFAULT_OPTIONS =
buttonWidth: 15
lockedSocketButtonWidth: 15
buttonHeight: 15
extraLeft: 0
buttonVertPadding: 6
buttonHorizPadding: 3
minIndentTongueWidth: 150
showDropdowns: true
padding: 5
indentWidth: 20
indentTongueHeight: 20
tabOffset: 10
tabWidth: 15
tabHeight: 5
tabSideWidth: 0.125
dropAreaHeight: 20
indentDropAreaMinWidth: 50
minSocketWidth: 10
invisibleSocketWidth: 5
textHeight: 15
textPadding: 1
emptyLineWidth: 50
highlightAreaHeight: 10
bevelClip: 3
shadowBlur: 5
colors:
error: '#ff0000'
comment: '#c0c0c0' # gray
return: '#fff59d' # yellow
control: '#ffcc80' # orange
value: '#a5d6a7' # green
command: '#90caf9' # blue
red: '#ef9a9a'
pink: '#f48fb1'
purple: '#ce93d8'
deeppurple: '#b39ddb'
indigo: '#9fa8da'
blue: '#90caf9'
lightblue: '#81d4fa'
cyan: '#80deea'
teal: '#80cbc4'
green: '#a5d6a7'
lightgreen: '#c5e1a5'
darkgreen: '#008000'
lime: '#e6ee9c'
yellow: '#fff59d'
amber: '#ffe082'
orange: '#ffcc80'
deeporange: '#ffab91'
brown: '#bcaaa4'
grey: '#eeeeee'
bluegrey: '#b0bec5'
function: '#90caf9'
declaration: '#e6ee9c'
value: '#a5d6a7'
logic: '#ffab91'
assign: '#fff59d'
functionCall: '#90caf9'
control: '#ffab91'
YES = -> yes
NO = -> no
arrayEq = (a, b) ->
return false if a.length isnt b.length
return false if k isnt b[i] for k, i in a
return true
# # View
# The View class contains options and caches
# for rendering. The controller instantiates a View
# and interacts with things through it.
#
# Inner classes in the View correspond to Model
# types (e.g. SocketViewNode, etc.) all of which
# will have access to their View's caches
# and options object.
exports.View = class View
constructor: (@ctx, @opts = {}) ->
@ctx ?= document.createElementNS SVG_STANDARD, 'svg'
# @map maps Model objects
# to corresponding View objects,
# so that rerendering the same model
# can be fast
@map = {}
@oldRoots = {}
@newRoots = {}
@auxiliaryMap = {}
@flaggedToDelete = {}
@unflaggedToDelete = {}
@marks = {}
@draw = new draw.Draw(@ctx)
# Apply default options
for option of DEFAULT_OPTIONS
unless option of @opts
@opts[option] = DEFAULT_OPTIONS[option]
for color of DEFAULT_OPTIONS.colors
unless color of @opts.colors
@opts.colors[color] = DEFAULT_OPTIONS.colors[color]
if @opts.invert
@opts.colors['comment'] = '#606060'
# Simple method for clearing caches
clearCache: ->
for id of @map
@map[id].destroy()
@destroy id
# Remove everything from the canvas
clearFromCanvas: ->
@beginDraw()
@cleanupDraw()
# ## getViewNodeFor
# Given a model object,
# give the corresponding renderer object
# under this View. If one does not exist,
# create one, then preserve it in our map.
getViewNodeFor: (model) ->
if model.id of @map
return @map[model.id]
else
return @createView(model)
registerMark: (id) ->
@marks[id] = true
clearMarks: ->
for key, val of @marks
@map[key].unmark()
@marks = {}
beginDraw: ->
@newRoots = {}
hasViewNodeFor: (model) ->
model? and model.id of @map
getAuxiliaryNode: (node) ->
if node.id of @auxiliaryMap
return @auxiliaryMap[node.id]
else
return @auxiliaryMap[node.id] = new AuxiliaryViewNode(@, node)
registerRoot: (node) ->
if node instanceof model.List and not (
node instanceof model.Container)
node.traverseOneLevel (head) =>
unless head instanceof model.NewlineToken
@registerRoot head
return
for id, aux of @newRoots
if aux.model.hasParent(node)
delete @newRoots[id]
else if node.hasParent(aux.model)
return
@newRoots[node.id] = @getAuxiliaryNode(node)
cleanupDraw: ->
@flaggedToDelete = {}
@unflaggedToDelete = {}
for id, el of @oldRoots
unless id of @newRoots
@flag el
for id, el of @newRoots
el.cleanup()
for id, el of @flaggedToDelete when id of @unflaggedToDelete
delete @flaggedToDelete[id]
for id, el of @flaggedToDelete when id of @map
@map[id].hide()
@oldRoots = @newRoots
flag: (auxiliaryNode) ->
@flaggedToDelete[auxiliaryNode.model.id] = auxiliaryNode
unflag: (auxiliaryNode) ->
@unflaggedToDelete[auxiliaryNode.model.id] = auxiliaryNode
garbageCollect: ->
@cleanupDraw()
for id, el of @flaggedToDelete when id of @map
@map[id].destroy()
@destroy id
for id, el of @newRoots
el.update()
destroy: (id) ->
for child in @map[id].children
if @map[child.child.id]? and not @unflaggedToDelete[child.child.id]
@destroy child.child.id
delete @map[id]
delete @auxiliaryMap[id]
delete @flaggedToDelete[id]
hasViewNodeFor: (model) -> model? and model.id of @map
# ## createView
# Given a model object, create a renderer object
# of the appropriate type.
createView: (entity) ->
if (entity instanceof model.List) and not
(entity instanceof model.Container)
return new ListViewNode entity, this
switch entity.type
when 'text' then new TextViewNode entity, this
when 'block' then new BlockViewNode entity, this
when 'indent' then new IndentViewNode entity, this
when 'socket' then new SocketViewNode entity, this
when 'buttonContainer' then new ContainerViewNode entity, this
when 'lockedSocket' then new ContainerViewNode entity, this # LockedSocketViewNode entity, this
when 'document' then new DocumentViewNode entity, this
# Looks up a color name, or passes through a #hex color.
getColor: (model) ->
if model?.color instanceof Function
color = model.color(model)
else if model?
color = model.color
else
color = ""
if color and '#' is color.charAt(0)
color
else
@opts.colors[color] ? '#ffffff'
class AuxiliaryViewNode
constructor: (@view, @model) ->
@children = {}
@computedVersion = -1
cleanup: ->
@view.unflag @
if @model.version is @computedVersion
return
children = {}
if @model instanceof model.Container
@model.traverseOneLevel (head) =>
if head instanceof model.NewlineToken
return
else
children[head.id] = @view.getAuxiliaryNode head
for id, child of @children
unless id of children
@view.flag child
for id, child of children
@children[id] = child
child.cleanup()
update: ->
@view.unflag @
if @model.version is @computedVersion
return
children = {}
if @model instanceof model.Container
@model.traverseOneLevel (head) =>
if head instanceof model.NewlineToken
return
else
children[head.id] = @view.getAuxiliaryNode head
@children = children
for id, child of @children
child.update()
@computedVersion = @model.version
# # GenericViewNode
# Class from which all renderer classes will
# extend.
class GenericViewNode
constructor: (@model, @view) ->
# Record ourselves in the map
# from model to renderer
@view.map[@model.id] = this
@view.registerRoot @model
@lastCoordinate = new @view.draw.Point 0, 0
@invalidate = false
# *Zeroth pass variables*
# computeChildren
@lineLength = 0 # How many lines does this take up?
@children = [] # All children, flat
@oldChildren = [] # Previous children, for removing
@lineChildren = [] # Children who own each line
@multilineChildrenData = [] # Where do indents start/end?
# *First pass variables*
# computeMargins
@margins = {left:0, right:0, top:0, bottom:0}
@topLineSticksToBottom = false
@bottomLineSticksToTop = false
# *Pre-second pass variables*
# computeMinDimensions
# @view.draw.Size type, {width:n, height:m}
@minDimensions = [] # Dimensions on each line
@minDistanceToBase = [] # {above:n, below:n}
# *Second pass variables*
# computeDimensions
# @view.draw.Size type, {width:n, height:m}
@dimensions = [] # Dimensions on each line
@distanceToBase = [] # {above:n, below:n}
@carriageArrow = CARRIAGE_ARROW_NONE
@bevels =
top: false
bottom: false
# *Third/fifth pass variables*
# computeBoundingBoxX, computeBoundingBoxY
# @view.draw.Rectangle type, {x:0, y:0, width:200, height:100}
@bounds = [] # Bounding boxes on each line
@changedBoundingBox = true # Did any bounding boxes change just now?
# *Fourth pass variables*
# computeGlue
# {height:2, draw:true}
@glue = {}
@elements = []
@activeElements = []
# Versions. The corresponding
# Model will keep corresponding version
# numbers, and each of our passes can
# become a no-op when we are up-to-date (so
# that rerendering is fast when there are
# few or no changes to the Model).
@computedVersion = -1
draw: (boundingRect, style = {}, parent = null) ->
@drawSelf style, parent
root: ->
for element in @elements
element.setParent @view.draw.ctx
serialize: (line) ->
result = []
for prop in [
'lineLength'
'margins'
'topLineSticksToBottom'
'bottomLineSticksToTop'
'changedBoundingBox'
'path'
'highlightArea'
'computedVersion'
'carriageArrow'
'bevels']
result.push(prop + ': ' + JSON.stringify(@[prop]))
for child, i in @children
result.push("child #{i}: {startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}")
if line?
for prop in [
'multilineChildrenData'
'minDimensions'
'minDistanceToBase'
'dimensions'
'distanceToBase'
'bounds'
'glue']
result.push("#{prop} #{line}: #{JSON.stringify(@[prop][line])}")
for child, i in @lineChildren[line]
result.push("line #{line} child #{i}: " +
"{startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}}")
else
for line in [0...@lineLength]
for prop in [
'multilineChildrenData'
'minDimensions'
'minDistanceToBase'
'dimensions'
'distanceToBase'
'bounds'
'glue']
result.push("#{prop} #{line}: #{JSON.stringify(@[prop][line])}")
for child, i in @lineChildren[line]
result.push("line #{line} child #{i}: " +
"{startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}}")
return result.join('\n')
# ## computeChildren (GenericViewNode)
# Find out which of our children lie on each line that we
# own, and also how many lines we own.
#
# Return the number of lines we own.
#
# This is basically a void computeChildren that should be
# overridden.
computeChildren: -> @lineLength
focusAll: ->
@group.focus()
computeCarriageArrow: ->
for childObj in @children
@view.getViewNodeFor(childObj.child).computeCarriageArrow()
return @carriageArrow
# ## computeMargins (GenericViewNode)
# Compute the amount of margin required outside the child
# on the top, bottom, left, and right.
#
# This is a void computeMargins that should be overridden.
computeMargins: ->
if @computedVersion is @model.version and
(not @model.parent? or not @view.hasViewNodeFor(@model.parent) or
@model.parent.version is @view.getViewNodeFor(@model.parent).computedVersion)
return @margins
# the margins I need depend on the type of my parent
parenttype = @model.parent?.type
padding = @view.opts.padding
left = if @model.isFirstOnLine() or @lineLength > 1 then padding else 0
right = if @model.isLastOnLine() or @lineLength > 1 then padding else 0
if parenttype is 'block' and @model.type is 'indent'
@margins =
top: 0
bottom: if @lineLength > 1 then @view.opts.indentTongueHeight else padding
firstLeft: padding
midLeft: @view.opts.indentWidth
lastLeft: @view.opts.indentWidth
firstRight: 0
midRight: 0
lastRight: padding
else if @model.type is 'text' and parenttype is 'socket'
@margins =
top: @view.opts.textPadding
bottom: @view.opts.textPadding
firstLeft: @view.opts.textPadding
midLeft: @view.opts.textPadding
lastLeft: @view.opts.textPadding
firstRight: @view.opts.textPadding
midRight: @view.opts.textPadding
lastRight: @view.opts.textPadding
else if @model.type is 'text' and parenttype is 'block'
if @model.prev?.type is 'newline' and @model.next?.type in ['newline', 'indentStart'] or @model.prev?.prev?.type is 'indentEnd'
textPadding = padding / 2
else
textPadding = padding
@margins =
top: textPadding
bottom: textPadding #padding
firstLeft: left
midLeft: left
lastLeft: left
firstRight: right
midRight: right
lastRight: right
else if parenttype is 'block'
@margins =
top: padding
bottom: padding
firstLeft: left
midLeft: padding
lastLeft: padding
firstRight: right
midRight: 0
lastRight: right
else
@margins = {
firstLeft: 0, midLeft:0, lastLeft: 0
firstRight: 0, midRight:0, lastRight: 0
top:0, bottom:0
}
@firstMargins =
left: @margins.firstLeft
right: @margins.firstRight
top: @margins.top
bottom: if @lineLength is 1 then @margins.bottom else 0
@midMargins =
left: @margins.midLeft
right: @margins.midRight
top: 0
bottom: 0
@lastMargins =
left: @margins.lastLeft
right: @margins.lastRight
top: if @lineLength is 1 then @margins.top else 0
bottom: @margins.bottom
for childObj in @children
@view.getViewNodeFor(childObj.child).computeMargins()
return null
getMargins: (line) ->
if line is 0 then @firstMargins
else if line is @lineLength - 1 then @lastMargins
else @midMargins
computeBevels: ->
for childObj in @children
@view.getViewNodeFor(childObj.child).computeBevels()
return @bevels
# ## computeMinDimensions (GenericViewNode)
# Compute the size of our bounding box on each
# line that we contain.
#
# Return child node.
#
# This is a void computeDimensinos that should be overridden.
computeMinDimensions: ->
if @minDimensions.length > @lineLength
@minDimensions.length = @minDistanceToBase.length = @lineLength
else
until @minDimensions.length is @lineLength
@minDimensions.push new @view.draw.Size 0, 0
@minDistanceToBase.push {above: 0, below: 0}
for i in [0...@lineLength]
@minDimensions[i].width = @minDimensions[i].height = 0
@minDistanceToBase[i].above = @minDistanceToBase[i].below = 0
return null
# ## computeDimensions (GenericViewNode)
# Compute the size of our bounding box on each
# line that we contain.
#
# Return child node.
computeDimensions: (force, root = false) ->
if @computedVersion is @model.version and not force and not @invalidate
return
oldDimensions = @dimensions
oldDistanceToBase = @distanceToBase
@dimensions = (new @view.draw.Size 0, 0 for [0...@lineLength])
@distanceToBase = ({above: 0, below: 0} for [0...@lineLength])
for size, i in @minDimensions
@dimensions[i].width = size.width; @dimensions[i].height = size.height
@distanceToBase[i].above = @minDistanceToBase[i].above
@distanceToBase[i].below = @minDistanceToBase[i].below
if @model.parent? and @view.hasViewNodeFor(@model.parent) and not root and
(@topLineSticksToBottom or @bottomLineSticksToTop or
(@lineLength > 1 and not @model.isLastOnLine()))
parentNode = @view.getViewNodeFor @model.parent
startLine = @model.getLinesToParent()
# grow below if "stick to bottom" is set.
if @topLineSticksToBottom
distance = @distanceToBase[0]
distance.below = Math.max(distance.below,
parentNode.distanceToBase[startLine].below)
@dimensions[0] = new @view.draw.Size(
@dimensions[0].width,
distance.below + distance.above)
# grow above if "stick to top" is set.
if @bottomLineSticksToTop
lineCount = @distanceToBase.length
distance = @distanceToBase[lineCount - 1]
distance.above = Math.max(distance.above,
parentNode.distanceToBase[startLine + lineCount - 1].above)
@dimensions[lineCount - 1] = new @view.draw.Size(
@dimensions[lineCount - 1].width,
distance.below + distance.above)
if @lineLength > 1 and not @model.isLastOnLine() and @model.type is 'block'
distance = @distanceToBase[@lineLength - 1]
distance.below = parentNode.distanceToBase[startLine + @lineLength - 1].below
@dimensions[lineCount - 1] = new @view.draw.Size(
@dimensions[lineCount - 1].width,
distance.below + distance.above)
changed = (oldDimensions.length != @lineLength)
if not changed then for line in [0...@lineLength]
if !oldDimensions[line].equals(@dimensions[line]) or
oldDistanceToBase[line].above != @distanceToBase[line].above or
oldDistanceToBase[line].below != @distanceToBase[line].below
changed = true
break
@changedBoundingBox or= changed
for childObj in @children
if childObj in @lineChildren[0] or childObj in @lineChildren[@lineLength - 1]
@view.getViewNodeFor(childObj.child).computeDimensions(changed, not (@model instanceof model.Container)) #(hack)
else
@view.getViewNodeFor(childObj.child).computeDimensions(false, not (@model instanceof model.Container)) #(hack)
return null
# ## computeBoundingBoxX (GenericViewNode)
# Given the left edge coordinate for our bounding box on
# this line, recursively layout the x-coordinates of us
# and all our children on this line.
computeBoundingBoxX: (left, line) ->
# Attempt to use our cache. Because modifications in the parent
# can affect the shape of child blocks, we can't only rely
# on versioning. For instance, changing `fd 10` to `forward 10`
# does not update the version on `10`, but the bounding box for
# `10` still needs to change. So we must also check
# that the coordinate we are given to begin the bounding box on matches.
if @computedVersion is @model.version and
left is @bounds[line]?.x and not @changedBoundingBox or
@bounds[line]?.x is left and
@bounds[line]?.width is @dimensions[line].width
return @bounds[line]
@changedBoundingBox = true
# Avoid re-instantiating a Rectangle object,
# if possible.
if @bounds[line]?
@bounds[line].x = left
@bounds[line].width = @dimensions[line].width
# If not, create one.
else
@bounds[line] = new @view.draw.Rectangle(
left, 0
@dimensions[line].width, 0
)
return @bounds[line]
# ## computeAllBoundingBoxX (GenericViewNode)
# Call `@computeBoundingBoxX` on all lines,
# thus laying out the entire document horizontally.
computeAllBoundingBoxX: (left = 0) ->
for size, line in @dimensions
@computeBoundingBoxX left, line
return @bounds
# ## computeGlue (GenericViewNode)
# If there are disconnected bounding boxes
# that belong to the same block,
# insert "glue" spacers between lines
# to connect them. For instance:
#
# ```
# someLongFunctionName ''' hello
# world '''
# ```
#
# would require glue between 'hello' and 'world'.
#
# This is a void function that should be overridden.
computeGlue: ->
@glue = {}
# ## computeBoundingBoxY (GenericViewNode)
# Like computeBoundingBoxX. We must separate
# these passes because glue spacers from `computeGlue`
# affect computeBoundingBoxY.
computeBoundingBoxY: (top, line) ->
# Again, we need to check to make sure that the coordinate
# we are given matches, since we cannot only rely on
# versioning (see computeBoundingBoxX).
if @computedVersion is @model.version and
top is @bounds[line]?.y and not @changedBoundingBox or
@bounds[line].y is top and
@bounds[line].height is @dimensions[line].height
return @bounds[line]
@changedBoundingBox = true
# Accept the bounding box edge we were given.
# We assume here that computeBoundingBoxX was
# already run for this version, so we
# should be guaranteed that `@bounds[line]` exists.
@bounds[line].y = top
@bounds[line].height = @dimensions[line].height
return @bounds[line]
# ## computeAllBoundingBoxY (GenericViewNode)
# Call `@computeBoundingBoxY` on all lines,
# thus laying out the entire document vertically.
#
# Account for glue spacing between lines.
computeAllBoundingBoxY: (top = 0) ->
for size, line in @dimensions
@computeBoundingBoxY top, line
top += size.height
if line of @glue then top += @glue[line].height
return @bounds
# ## getBounds (GenericViewNode)
# Deprecated. Access `@totalBounds` directly instead.
getBounds: -> @totalBounds
# ## computeOwnPath
# Using bounding box data, compute the vertices
# of the polygon that will wrap them. This function
# will be called from `computePath`, which does this
# recursively so as to draw the entire tree.
#
# Many nodes do not have paths at all,
# and so need not override this function.
computeOwnPath: ->
# ## computePath (GenericViewNode)
# Call `@computeOwnPath` and recurse. This function
# should never need to be overridden; override `@computeOwnPath`
# instead.
computePath: ->
# Here, we cannot just rely on versioning either.
# We need to know if any bounding box data changed. So,
# look at `@changedBoundingBox`, which should be set
# to `true` whenever a bounding box changed on the bounding box
# passes.
if @computedVersion is @model.version and
(@model.isLastOnLine() is @lastComputedLinePredicate) and
not @changedBoundingBox
return null
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computePath()
# It is possible that we have a version increment
# without changing bounding boxes. If this is the case,
# we don't need to recompute our own path.
if @changedBoundingBox or (@model.isLastOnLine() isnt @lastComputedLinePredicate)
@computeOwnPath()
# Recompute `totalBounds`, which is used
# to avoid re*drawing* polygons that
# are not on-screen. `totalBounds` is the AABB
# of the everything that has to do with the element,
# and we redraw iff it overlaps the AABB of the viewport.
@totalBounds = new @view.draw.NoRectangle()
if @bounds.length > 0
@totalBounds.unite @bounds[0]
@totalBounds.unite @bounds[@bounds.length - 1]
# Figure out our total bounding box however is faster.
if @bounds.length > @children.length
for child in @children
@totalBounds.unite @view.getViewNodeFor(child.child).totalBounds
else
maxRight = @totalBounds.right()
for bound in @bounds
@totalBounds.x = Math.min @totalBounds.x, bound.x
maxRight = Math.max maxRight, bound.right()
@totalBounds.width = maxRight - @totalBounds.x
if @path?
@totalBounds.unite @path.bounds()
@lastComputedLinePredicate = @model.isLastOnLine()
return null
# ## computeOwnDropArea (GenericViewNode)
# Using bounding box data, compute the drop area
# for drag-and-drop blocks, if it exists.
#
# If we cannot drop something on this node
# (e.g. a socket that already contains a block),
# set `@dropArea` to null.
#
# Simultaneously, compute `@highlightArea`, which
# is the white polygon that lights up
# when we hover over a drop area.
computeOwnDropArea: ->
# ## computeDropAreas (GenericViewNode)
# Call `@computeOwnDropArea`, and recurse.
#
# This should never have to be overridden;
# override `@computeOwnDropArea` instead.
computeDropAreas: ->
# Like with `@computePath`, we cannot rely solely on versioning,
# so we check the bounding box flag.
if @computedVersion is @model.version and
not @changedBoundingBox
return null
# Compute drop and highlight areas for ourself
@computeOwnDropArea()
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computeDropAreas()
return null
computeNewVersionNumber: ->
if @computedVersion is @model.version and
not @changedBoundingBox
return null
@changedBoundingBox = false
@invalidate = false
@computedVersion = @model.version
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computeNewVersionNumber()
return null
# ## drawSelf (GenericViewNode)
# Draw our own polygon on a canvas context.
# May require special effects, like graying-out
# or blueing for lasso select.
drawSelf: (style = {}) ->
hide: ->
for element in @elements
element?.deactivate?()
@activeElements = []
destroy: (root = true) ->
if root
for element in @elements
element?.destroy?()
else if @highlightArea?
@highlightArea.destroy()
@activeElements = []
for child in @children
@view.getViewNodeFor(child.child).destroy(false)
class ListViewNode extends GenericViewNode
constructor: (@model, @view) ->
super
draw: (boundingRect, style = {}, parent = null) ->
super
for childObj in @children
@view.getViewNodeFor(childObj.child).draw boundingRect, style, @group
root: ->
for child in @children
@view.getViewNodeFor(child.child).root()
destroy: (root = true) ->
for child in @children
@view.getViewNodeFor(child.child).destroy()
# ## computeChildren (ListViewNode)
# Figure out which children lie on each line,
# and compute `@multilineChildrenData` simultaneously.
#
# We will do this by going to all of our immediate children,
# recursing, then calculating their starting and ending lines
# based on their computing line lengths.
computeChildren: ->
# If we can, use our cached information.
if @computedVersion is @model.version
return @lineLength
# Otherwise, recompute.
@lineLength = 0
@lineChildren = [[]]
@children = []
@multilineChildrenData = []
@topLineSticksToBottom = false
@bottomLineSticksToTop = false
line = 0
# Go to all our immediate children.
@model.traverseOneLevel (head) =>
# If the child is a newline, simply advance the
# line counter.
if head.type is 'newline'
line += 1
@lineChildren[line] ?= []
# Otherwise, get the view object associated
# with this model, and ask it to
# compute children.
else
view = @view.getViewNodeFor(head)
childLength = view.computeChildren()
# Construct a childObject,
# which will remember starting and endling lines.
childObject =
child: head
startLine: line
endLine: line + childLength - 1
# Put it into `@children`.
@children.push childObject
# Put it into `@lineChildren`.
for i in [line...line + childLength]
@lineChildren[i] ?= []
# We don't want to store cursor tokens
# in `@lineChildren`, as they are inconvenient
# to deal with in layout, which is the only
# thing `@lineChildren` is used for.
unless head.type is 'cursor'
@lineChildren[i].push childObject
# If this object is a multiline child,
# update our multiline child data to reflect
# where it started and ended.
if view.lineLength > 1
if @multilineChildrenData[line] is MULTILINE_END
@multilineChildrenData[line] = MULTILINE_END_START
else
@multilineChildrenData[line] = MULTILINE_START
@multilineChildrenData[i] = MULTILINE_MIDDLE for i in [line + 1...line + childLength - 1]
@multilineChildrenData[line + childLength - 1] = MULTILINE_END
# Advance our line counter
# by however long the child was
# (i.e. however many newlines
# we skipped).
line += childLength - 1
# Set @lineLength to reflect
# what we just found out.
@lineLength = line + 1
# If we have changed in line length,
# there has obviously been a bounding box change.
# The bounding box pass as it stands only deals
# with lines it knows exists, so we need to chop off
# the end of the array.
if @bounds.length isnt @lineLength
@changedBoundingBox = true
@bounds = @bounds[...@lineLength]
# Fill in gaps in @multilineChildrenData with NO_MULTILINE
@multilineChildrenData[i] ?= NO_MULTILINE for i in [0...@lineLength]
if @lineLength > 1
@topLineSticksToBottom = true
@bottomLineSticksToTop = true
return @lineLength
# ## computeDimensions (ListViewNode)
# Compute the size of our bounding box on each line.
computeMinDimensions: ->
# If we can, use cached data.
if @computedVersion is @model.version
return null
# start at zero min dimensions
super
# Lines immediately after the end of Indents
# have to be extended to a minimum width.
# Record the lines that need to be extended here.
linesToExtend = []
preIndentLines = []
# Recurse on our children, updating
# our dimensions as we go to contain them.
for childObject in @children
# Ask the child to compute dimensions
childNode = @view.getViewNodeFor(childObject.child)
childNode.computeMinDimensions()
minDimensions = childNode.minDimensions
minDistanceToBase = childNode.minDistanceToBase
# Horizontal margins get added to every line.
for size, line in minDimensions
desiredLine = line + childObject.startLine
margins = childNode.getMargins line
# Unless we are in the middle of an indent,
# add padding on the right of the child.
#
# Exception: Children with invisible bounding boxes
# should remain invisible. This matters
# mainly for indents starting at the end of a line.
@minDimensions[desiredLine].width += size.width +
margins.left +
margins.right
# Compute max distance above and below text
#
# Exception: do not add the bottom padding on an
# Indent if we own the next line as well.
if childObject.child.type is 'indent' and
line is minDimensions.length - 1 and
desiredLine < @lineLength - 1
bottomMargin = 0
linesToExtend.push desiredLine + 1
else if childObject.child.type is 'indent' and
line is 0
preIndentLines.push desiredLine
bottomMargin = margins.bottom
else
bottomMargin = margins.bottom
@minDistanceToBase[desiredLine].above = Math.max(
@minDistanceToBase[desiredLine].above,
minDistanceToBase[line].above + margins.top)
@minDistanceToBase[desiredLine].below = Math.max(
@minDistanceToBase[desiredLine].below,
minDistanceToBase[line].below + Math.max(bottomMargin, (
if @model.buttons? and @model.buttons.length > 0 and
desiredLine is @lineLength - 1 and
@multilineChildrenData[line] is MULTILINE_END and
@lineChildren[line].length is 1
@view.opts.buttonVertPadding + @view.opts.buttonHeight
else
0
)))
# Height is just the sum of the above-base and below-base counts.
# Empty lines should have some height.
for minDimension, line in @minDimensions
if @lineChildren[line].length is 0
# Socket should be shorter than other blocks
if @model.type is 'socket'
@minDistanceToBase[line].above = @view.opts.textHeight + @view.opts.textPadding
@minDistanceToBase[line].below = @view.opts.textPadding
# Text should not claim any padding
else if @model.type is 'text'
@minDistanceToBase[line].above = @view.opts.textHeight
@minDistanceToBase[line].below = 0
# The first line of an indent is often empty; this is the desired behavior
else if @model.type is 'indent' and line is 0
@minDistanceToBase[line].above = 0
@minDistanceToBase[line].below = 0
# Empty blocks should be the height of lines with text
else
@minDistanceToBase[line].above = @view.opts.textHeight + @view.opts.padding
@minDistanceToBase[line].below = @view.opts.padding
minDimension.height =
@minDistanceToBase[line].above +
@minDistanceToBase[line].below
# Make space for mutation buttons. In lockedSocket,
# these will go on the left; otherwise they will go on the right.
@extraLeft = 0
@extraWidth = 0
if @model.type in ['block', 'buttonContainer']
if @model.buttons? then for {key} in @model.buttons
@extraWidth += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
@minDimensions[@minDimensions.length - 1].width += @extraWidth
if @model.type is 'lockedSocket'
if @model.buttons? then for {key} in @model.buttons
@extraLeft += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
@minDimensions[@minDimensions.length - 1].width += @extraLeft
# Go through and adjust the width of rectangles
# immediately after the end of an indent to
# be as long as necessary
for line in linesToExtend
@minDimensions[line].width = Math.max(
@minDimensions[line].width, Math.max(
@view.opts.minIndentTongueWidth,
@view.opts.indentWidth + @view.opts.tabWidth + @view.opts.tabOffset + @view.opts.bevelClip
))
for line in preIndentLines
@minDimensions[line].width = Math.max(
@minDimensions[line].width, Math.max(
@view.opts.minIndentTongueWidth,
@view.opts.indentWidth + @view.opts.tabWidth + @view.opts.tabOffset + @view.opts.bevelClip
))
# Add space for carriage arrow
for lineChild in @lineChildren[@lineLength - 1]
lineChildView = @view.getViewNodeFor lineChild.child
if lineChildView.carriageArrow isnt CARRIAGE_ARROW_NONE
@minDistanceToBase[@lineLength - 1].below += @view.opts.padding
@minDimensions[@lineLength - 1].height =
@minDistanceToBase[@lineLength - 1].above +
@minDistanceToBase[@lineLength - 1].below
break
return null
# ## computeBoundingBoxX (ListViewNode)
# Layout bounding box positions horizontally.
# This needs to be separate from y-coordinate computation
# because of glue spacing (the space between lines
# that keeps weird-shaped blocks continuous), which
# can shift y-coordinates around.
computeBoundingBoxX: (left, line, offset = 0) ->
# Use cached data if possible
if @computedVersion is @model.version and
left is @bounds[line]?.x and not @changedBoundingBox
return @bounds[line]
offset += @extraLeft
# If the bounding box we're being asked
# to layout is exactly the same,
# avoid setting `@changedBoundingBox`
# for performance reasons (also, trivially,
# avoid changing bounding box coords).
unless @bounds[line]?.x is left and
@bounds[line]?.width is @dimensions[line].width
# Assign our own bounding box given
# this center-left coordinate
if @bounds[line]?
@bounds[line].x = left
@bounds[line].width = @dimensions[line].width
else
@bounds[line] = new @view.draw.Rectangle(
left, 0
@dimensions[line].width, 0
)
@changedBoundingBox = true
# Now recurse. We will keep track
# of a "cursor" as we go along,
# placing children down and
# adding padding and sizes
# to make them not overlap.
childLeft = left + offset
# Get rendering info on each of these children
for lineChild, i in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
childMargins = childView.getMargins childLine
childLeft += childMargins.left
childView.computeBoundingBoxX childLeft, childLine
childLeft +=
childView.dimensions[childLine].width + childMargins.right
# Return the bounds we just
# computed.
return @bounds[line]
# ## computeBoundingBoxY
# Layout a line vertically.
computeBoundingBoxY: (top, line) ->
# Use our cache if possible.
if @computedVersion is @model.version and
top is @bounds[line]?.y and not @changedBoundingBox
return @bounds[line]
# Avoid setting `@changedBoundingBox` if our
# bounding box has not actually changed,
# for performance reasons. (Still need to
# recurse, in case children have changed
# but not us)
unless @bounds[line]?.y is top and
@bounds[line]?.height is @dimensions[line].height
# Assign our own bounding box given
# this center-left coordinate
@bounds[line].y = top
@bounds[line].height = @dimensions[line].height
@changedBoundingBox = true
# Go to each child and lay them out so that their distanceToBase
# lines up.
above = @distanceToBase[line].above
for lineChild, i in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
childAbove = childView.distanceToBase[childLine].above
childView.computeBoundingBoxY top + above - childAbove, childLine
# Return the bounds we just computed.
return @bounds[line]
# ## layout
# Run all of these layout steps in order.
#
# Takes two arguments, which can be changed
# to translate the entire document from the upper-left corner.
layout: (left = @lastCoordinate.x, top = @lastCoordinate.y) ->
@view.registerRoot @model
@lastCoordinate = new @view.draw.Point left, top
@computeChildren()
@computeCarriageArrow true
@computeMargins()
@computeBevels()
@computeMinDimensions()
@computeDimensions 0, true
@computeAllBoundingBoxX left
@computeGlue()
@computeAllBoundingBoxY top
@computePath()
@computeDropAreas()
changedBoundingBox = @changedBoundingBox
@computeNewVersionNumber()
return changedBoundingBox
# ## absorbCache
# A hacky thing to get a view node of a new List
# to acquire all the properties of its children
# TODO re-examine
absorbCache: ->
@view.registerRoot @model
@computeChildren()
@computeCarriageArrow true
@computeMargins()
@computeBevels()
@computeMinDimensions()
# Replacement for computeDimensions
for size, line in @minDimensions
@distanceToBase[line] = {
above: @lineChildren[line].map((child) => @view.getViewNodeFor(child.child).distanceToBase[line - child.startLine].above).reduce((a, b) -> Math.max(a, b))
below: @lineChildren[line].map((child) => @view.getViewNodeFor(child.child).distanceToBase[line - child.startLine].below).reduce((a, b) -> Math.max(a, b))
}
@dimensions[line] = new draw.Size @minDimensions[line].width, @minDimensions[line].height
#@computeDimensions false, true
# Replacement for computeAllBoundingBoxX
for size, line in @dimensions
child = @lineChildren[line][0]
childView = @view.getViewNodeFor child.child
left = childView.bounds[line - child.startLine].x
@computeBoundingBoxX left, line
@computeGlue()
# Replacement for computeAllBoundingBoxY
for size, line in @dimensions
child = @lineChildren[line][0]
childView = @view.getViewNodeFor child.child
oldY = childView.bounds[line - child.startLine].y
top = childView.bounds[line - child.startLine].y +
childView.distanceToBase[line - child.startLine].above -
@distanceToBase[line].above
@computeBoundingBoxY top, line
@computePath()
@computeDropAreas()
return true
# ## computeGlue
# Compute the necessary glue spacing between lines.
#
# If a block has disconnected blocks, e.g.
# ```
# someLongFunctionName '''hello
# world'''
# ```
#
# it requires glue spacing. Then, any surrounding blocks
# must add their padding to that glue spacing, until we
# reach an Indent, at which point we can stop.
#
# Parents outside the indent must stil know that there is
# a space between these line, but they wil not have
# to colour in that space. This will be flaged
# by the `draw` flag on the glue objects.
computeGlue: ->
# Use our cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
# Immediately recurse, as we will
# need to know child glue info in order
# to compute our own (adding padding, etc.).
for childObj in @children
@view.getViewNodeFor(childObj.child).computeGlue()
@glue = {}
# Go through every pair of adjacent bounding boxes
# to see if they overlap or not
for box, line in @bounds when line < @bounds.length - 1
@glue[line] = {
type: 'normal'
height: 0
draw: false
}
# We will always have glue spacing at least as big
# as the biggest child's glue spacing.
for lineChild in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
if childLine of childView.glue
# Either add padding or not, depending
# on whether there is an indent between us.
@glue[line].height = Math.max @glue[line].height, childView.glue[childLine].height
if childView.carriageArrow isnt CARRIAGE_ARROW_NONE
@glue[line].height = Math.max @glue[line].height, @view.opts.padding
# Return the glue we just computed.
return @glue
# # ContainerViewNode
# Class from which `socketView`, `indentView`, `blockView`, and `documentView` extend.
# Contains function for dealing with multiple children, making polygons to wrap
# multiple lines, etc.
class ContainerViewNode extends ListViewNode
constructor: (@model, @view) ->
super
# *Sixth pass variables*
# computePath
@group = @view.draw.group('droplet-container-group')
if @model.type is 'block'
@path = @view.draw.path([], true, {
cssClass: 'droplet-block-path'
})
else
@path = @view.draw.path([], false, {
cssClass: "droplet-#{@model.type}-path"
})
@totalBounds = new @view.draw.NoRectangle()
@path.setParent @group
# *Seventh pass variables*
# computeDropAreas
# each one is a @view.draw.Path (or null)
@dropPoint = null
@highlightArea = @view.draw.path([], false, {
fillColor: '#FF0'
strokeColor: '#FF0'
lineWidth: 1
})
@highlightArea.deactivate()
@buttonGroups = {}
@buttonTexts = {}
@buttonPaths = {}
@buttonRects = {}
if @model.buttons? then for {key, glyph} in @model.buttons
@buttonGroups[key] = @view.draw.group()
@buttonPaths[key] = @view.draw.path([
new @view.draw.Point 0, 0
new @view.draw.Point @view.opts.buttonWidth, 0
new @view.draw.Point @view.opts.buttonWidth, @view.opts.buttonHeight
new @view.draw.Point 0, @view.opts.buttonHeight
], false, {
fillColor: 'none'
cssClass: 'droplet-button-path'
})
###
new @view.draw.Point 0, @view.opts.bevelClip
new @view.draw.Point @view.opts.bevelClip, 0
new @view.draw.Point @view.opts.buttonWidth - @view.opts.bevelClip, 0
new @view.draw.Point @view.opts.buttonWidth, @view.opts.bevelClip
new @view.draw.Point @view.opts.buttonWidth, @view.opts.buttonHeight - @view.opts.bevelClip
new @view.draw.Point @view.opts.buttonWidth - @view.opts.bevelClip, @view.opts.buttonHeight
new @view.draw.Point @view.opts.bevelClip, @view.opts.buttonHeight
new @view.draw.Point 0, @view.opts.buttonHeight - @view.opts.bevelClip
###
@buttonGroups[key].style = {}
@buttonTexts[key] = @view.draw.text(new @view.draw.Point(
(@view.opts.buttonWidth - @view.draw.measureCtx.measureText(glyph).width)/ 2,
(@view.opts.buttonHeight - @view.opts.textHeight) / 2
), glyph, if @view.opts.invert then BUTTON_GLYPH_INVERT_COLOR else BUTTON_GLYPH_COLOR)
@buttonPaths[key].setParent @buttonGroups[key]
@buttonTexts[key].setParent @buttonGroups[key]
@buttonGroups[key].setParent @group
@elements.push @buttonGroups[key]
@activeElements.push @buttonPaths[key]
@activeElements.push @buttonTexts[key]
@activeElements.push @buttonGroups[key]
@elements.push @group
@elements.push @path
@elements.push @highlightArea
destroy: (root = true) ->
if root
for element in @elements
element?.destroy?()
else if @highlightArea?
@highlightArea.destroy()
for child in @children
@view.getViewNodeFor(child.child).destroy(false)
root: ->
@group.setParent @view.draw.ctx
# ## draw (GenericViewNode)
# Call `drawSelf` and recurse, if we are in the viewport.
draw: (boundingRect, style = {}, parent = null) ->
if not boundingRect? or @totalBounds.overlap boundingRect
@drawSelf style, parent
@group.activate(); @path.activate()
for element in @activeElements
element.activate()
if @highlightArea?
@highlightArea.setParent @view.draw.ctx
if parent?
@group.setParent parent
for childObj in @children
@view.getViewNodeFor(childObj.child).draw boundingRect, style, @group
else
@group.destroy()
if @highlightArea?
@highlightArea.destroy()
computeCarriageArrow: (root = false) ->
oldCarriageArrow = @carriageArrow
@carriageArrow = CARRIAGE_ARROW_NONE
parent = @model.parent
if (not root) and parent?.type is 'indent' and @view.hasViewNodeFor(parent) and
@view.getViewNodeFor(parent).lineLength > 1 and
@lineLength is 1
head = @model.start
until head is parent.start or head.type is 'newline'
head = head.prev
if head is parent.start
if @model.isLastOnLine()
@carriageArrow = CARRIAGE_ARROW_INDENT
else
@carriageArrow = CARRIAGE_GROW_DOWN
else unless @model.isFirstOnLine()
@carriageArrow = CARRIAGE_ARROW_SIDEALONG
if @carriageArrow isnt oldCarriageArrow
@changedBoundingBox = true
if @computedVersion is @model.version and
(not @model.parent? or not @view.hasViewNodeFor(@model.parent) or
@model.parent.version is @view.getViewNodeFor(@model.parent).computedVersion)
return null
super
computeGlue: ->
# Use our cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
super
for box, line in @bounds when line < @bounds.length - 1
# Additionally, we add glue spacing padding if we are disconnected
# from the bounding box on the next line.
unless @multilineChildrenData[line] is MULTILINE_MIDDLE
# Find the horizontal overlap between these two bounding rectangles,
# which is our right edge minus their left, or vice versa.
overlap = Math.min @bounds[line].right() - @bounds[line + 1].x, @bounds[line + 1].right() - @bounds[line].x
# If we are starting an indent, then our "bounding box"
# on the next line is not actually how we will be visualized;
# instead, we must connect to the small rectangle
# on the left of a C-shaped indent thing. So,
# compute overlap with that as well.
if @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
overlap = Math.min overlap, @bounds[line + 1].x + @view.opts.indentWidth - @bounds[line].x
# If the overlap is too small, demand glue.
if overlap < @view.opts.padding and @model.type isnt 'indent'
@glue[line].height += @view.opts.padding
@glue[line].draw = true
return @glue
computeBevels: ->
oldBevels = @bevels
@bevels =
top: true
bottom: true
if (@model.parent?.type in ['indent', 'document']) and
@model.start.prev?.type is 'newline' and
@model.start.prev?.prev isnt @model.parent.start
@bevels.top = false
if (@model.parent?.type in ['indent', 'document']) and
@model.end.next?.type is 'newline'
@bevels.bottom = false
unless oldBevels.top is @bevels.top and
oldBevels.bottom is @bevels.bottom
@changedBoundingBox = true
if @computedVersion is @model.version
return null
super
# ## computeOwnPath
# Using bounding box data, compute the polygon
# that represents us. This contains a lot of special cases
# for glue and multiline starts and ends.
computeOwnPath: ->
# There are four kinds of line,
# for the purposes of computing the path.
#
# 1. Normal block line; we surround the bounding rectangle.
# 2. Beginning of a multiline block. Avoid that block on the right and bottom.
# 3. Middle of a multiline block. We avoid to the left side
# 4. End of a multiline block. We make a G-shape if necessary. If it is an Indent,
# this will leave a thick tongue due to things done in dimension
# computation.
# We will keep track of two sets of coordinates,
# the left side of the polygon and the right side.
#
# At the end, we will reverse `left` and concatenate these
# so as to create a counterclockwise path.
left = []
right = []
# If necessary, add tab
# at the top.
if @shouldAddTab() and @model.isFirstOnLine() and
@carriageArrow isnt CARRIAGE_ARROW_SIDEALONG
@addTabReverse right, new @view.draw.Point @bounds[0].x + @view.opts.tabOffset, @bounds[0].y
for bounds, line in @bounds
# Case 1. Normal rendering.
if @multilineChildrenData[line] is NO_MULTILINE
# Draw the left edge of the bounding box.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Draw the right edge of the bounding box.
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# Case 2. Start of a multiline block.
if @multilineChildrenData[line] is MULTILINE_START
# Draw the left edge of the bounding box.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Find the multiline child that's starting on this line,
# so that we can know its bounds
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineView = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineView.bounds[line - multilineChild.startLine]
# If the multiline child here is invisible,
# draw the line just normally.
if multilineBounds.width is 0
right.push new @view.draw.Point bounds.right(), bounds.y
# Otherwise, avoid the block by tracing out its
# top and left edges, then going to our bound's bottom.
else
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), multilineBounds.y
if multilineChild.child.type is 'indent'
@addTab right, new @view.draw.Point multilineBounds.x + @view.opts.tabOffset, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
# Case 3. Middle of an indent.
if @multilineChildrenData[line] is MULTILINE_MIDDLE
multilineChild = @lineChildren[line][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[line - multilineChild.startLine]
# Draw the left edge normally.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Draw the right edge straight down,
# exactly to the left of the multiline child.
unless @multilineChildrenData[line - 1] in [MULTILINE_START, MULTILINE_END_START] and
multilineChild.child.type is 'indent'
right.push new @view.draw.Point multilineBounds.x, bounds.y
right.push new @view.draw.Point multilineBounds.x, bounds.bottom()
# Case 4. End of an indent.
if @multilineChildrenData[line] in [MULTILINE_END, MULTILINE_END_START]
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Find the child that is the indent
multilineChild = @lineChildren[line][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[line - multilineChild.startLine]
# Avoid the indented area
unless @multilineChildrenData[line - 1] in [MULTILINE_START, MULTILINE_END_START] and
multilineChild.child.type is 'indent'
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
if multilineChild.child.type is 'indent'
@addTabReverse right, new @view.draw.Point multilineBounds.x + @view.opts.tabOffset, multilineBounds.bottom()
right.push new @view.draw.Point multilineBounds.right(), multilineBounds.bottom()
# If we must, make the "G"-shape
if @lineChildren[line].length > 1
right.push new @view.draw.Point multilineBounds.right(), multilineBounds.y
if @multilineChildrenData[line] is MULTILINE_END
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
else
# Find the multiline child that's starting on this line,
# so that we can know its bounds
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineView = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineView.bounds[line - multilineChild.startLine]
# Draw the upper-right corner
right.push new @view.draw.Point bounds.right(), bounds.y
# If the multiline child here is invisible,
# draw the line just normally.
if multilineBounds.width is 0
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# Otherwise, avoid the block by tracing out its
# top and left edges, then going to our bound's bottom.
else
right.push new @view.draw.Point bounds.right(), multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
# Otherwise, don't.
else
right.push new @view.draw.Point bounds.right(), multilineBounds.bottom()
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# "Glue" phase
# Here we use our glue spacing data
# to draw glue, if necessary.
#
# If we are being told to draw some glue here,
# do so.
if line < @lineLength - 1 and line of @glue and @glue[line].draw
# Extract information from the glue spacing
# and bounding box data combined.
#
# `glueTop` will be the top of the "glue" box.
# `leftmost` and `rightmost` are the leftmost
# and rightmost extremes of this and the next line's
# bounding boxes.
glueTop = @bounds[line + 1].y - @glue[line].height
leftmost = Math.min @bounds[line + 1].x, @bounds[line].x
rightmost = Math.max @bounds[line + 1].right(), @bounds[line].right()
# Bring the left down to the glue top line, then down to the
# level of the next line's bounding box. This prepares
# it to go straight horizontally over
# to the top of the next bounding box,
# once the loop reaches that point.
left.push new @view.draw.Point @bounds[line].x, glueTop
left.push new @view.draw.Point leftmost, glueTop
left.push new @view.draw.Point leftmost, glueTop + @view.opts.padding
# Do the same for the right side, unless we can't
# because we're avoiding intersections with a multiline child that's
# in the way.
unless @multilineChildrenData[line] is MULTILINE_START
right.push new @view.draw.Point @bounds[line].right(), glueTop
right.push new @view.draw.Point rightmost, glueTop
right.push new @view.draw.Point rightmost, glueTop + @view.opts.padding
# Otherwise, bring us gracefully to the next line
# without lots of glue (minimize the extra colour).
else if @bounds[line + 1]? and @multilineChildrenData[line] isnt MULTILINE_MIDDLE
# Instead of outward extremes, we take inner extremes this time,
# to minimize extra colour between lines.
innerLeft = Math.max @bounds[line + 1].x, @bounds[line].x
innerRight = Math.min @bounds[line + 1].right(), @bounds[line].right()
# Drop down to the next line on the left, minimizing extra colour
left.push new @view.draw.Point innerLeft, @bounds[line].bottom()
left.push new @view.draw.Point innerLeft, @bounds[line + 1].y
# Do the same on the right, unless we need to avoid
# a multiline block that's starting here.
unless @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
right.push new @view.draw.Point innerRight, @bounds[line].bottom()
right.push new @view.draw.Point innerRight, @bounds[line + 1].y
else if @carriageArrow is CARRIAGE_GROW_DOWN
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point @bounds[line].x, destinationBounds.y - @view.opts.padding
else if @carriageArrow is CARRIAGE_ARROW_INDENT
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.y
right.push new @view.draw.Point destinationBounds.x + @view.opts.tabOffset + @view.opts.tabWidth, destinationBounds.y
left.push new @view.draw.Point @bounds[line].x, destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point destinationBounds.x, destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point destinationBounds.x, destinationBounds.y
@addTab right, new @view.draw.Point destinationBounds.x + @view.opts.tabOffset, destinationBounds.y
else if @carriageArrow is CARRIAGE_ARROW_SIDEALONG and @model.isLastOnLine()
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[@model.getLinesToParent()]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.bottom() + @view.opts.padding
right.push new @view.draw.Point destinationBounds.x + @view.opts.tabOffset + @view.opts.tabWidth,
destinationBounds.bottom() + @view.opts.padding
left.push new @view.draw.Point @bounds[line].x, destinationBounds.bottom()
left.push new @view.draw.Point destinationBounds.x, destinationBounds.bottom()
left.push new @view.draw.Point destinationBounds.x, destinationBounds.bottom() + @view.opts.padding
@addTab right, new @view.draw.Point destinationBounds.x + @view.opts.tabOffset,
destinationBounds.bottom() + @view.opts.padding
# If we're avoiding intersections with a multiline child in the way,
# bring us gracefully to the next line's top. We had to keep avoiding
# using bounding box right-edge data earlier, because it would have overlapped;
# instead, we want to use the left edge of the multiline block that's
# starting here.
if @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineNode = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineNode.bounds[line - multilineChild.startLine]
if @glue[line]?.draw
glueTop = @bounds[line + 1].y - @glue[line].height + @view.opts.padding
else
glueTop = @bounds[line].bottom()
# Special case for indents that start with newlines;
# don't do any of the same-line-start multiline stuff.
if multilineChild.child.type is 'indent' and multilineChild.child.start.next.type is 'newline'
right.push new @view.draw.Point @bounds[line].right(), glueTop
@addTab right, new @view.draw.Point(@bounds[line + 1].x +
@view.opts.indentWidth +
@extraLeft +
@view.opts.tabOffset, glueTop), true
else
right.push new @view.draw.Point multilineBounds.x, glueTop
unless glueTop is @bounds[line + 1].y
right.push new @view.draw.Point multilineNode.bounds[line - multilineChild.startLine + 1].x, glueTop
right.push new @view.draw.Point multilineNode.bounds[line - multilineChild.startLine + 1].x, @bounds[line + 1].y
# If necessary, add tab
# at the bottom.
if @shouldAddTab() and @model.isLastOnLine() and
@carriageArrow is CARRIAGE_ARROW_NONE
@addTab right, new @view.draw.Point @bounds[@lineLength - 1].x + @view.opts.tabOffset,
@bounds[@lineLength - 1].bottom()
topLeftPoint = left[0]
# Reverse the left and concatenate it with the right
# to make a counterclockwise path
path = dedupe left.reverse().concat right
newPath = []
for point, i in path
if i is 0 and not @bevels.bottom
newPath.push point
continue
if (not @bevels.top) and point.almostEquals(topLeftPoint)
newPath.push point
continue
next = path[(i + 1) %% path.length]
prev = path[(i - 1) %% path.length]
if (point.x is next.x) isnt (point.y is next.y) and
(point.x is prev.x) isnt (point.y is prev.y) and
point.from(prev).magnitude() >= @view.opts.bevelClip * 2 and
point.from(next).magnitude() >= @view.opts.bevelClip * 2
newPath.push point.plus(point.from(prev).toMagnitude(-@view.opts.bevelClip))
newPath.push point.plus(point.from(next).toMagnitude(-@view.opts.bevelClip))
else
newPath.push point
# Make a Path object out of these points
@path.setPoints newPath
if @model.type is 'block'
@path.style.fillColor = @view.getColor @model
if @model.buttons? and @model.type is 'lockedSocket'
# Add the add button if necessary
firstRect = @bounds[0]
start = firstRect.x
top = firstRect.y + firstRect.height / 2 - @view.opts.buttonHeight / 2
for {key} in @model.buttons
@buttonGroups[key].style.transform = "translate(#{start}, #{top})"
@buttonGroups[key].update()
@buttonPaths[key].update()
@buttonRects[key] = new @view.draw.Rectangle start, top, @view.opts.buttonWidth, @view.opts.buttonHeight
@elements.push @buttonPaths[key]
start += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
else if @model.buttons?
# Add the add button if necessary
lastLine = @bounds.length - 1
lastRect = @bounds[lastLine]
if @model.type is 'block'
start = lastRect.x + lastRect.width - @extraWidth - @view.opts.buttonHorizPadding
else
start = lastRect.x + lastRect.width - @extraWidth + @view.opts.buttonHorizPadding
top = lastRect.y + lastRect.height / 2 - @view.opts.buttonHeight / 2
for {key} in @model.buttons
# Cases when last line is MULTILINE
if @multilineChildrenData[lastLine] is MULTILINE_END
multilineChild = @lineChildren[lastLine][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[lastLine - multilineChild.startLine]
# If it is a G-Shape
if @lineChildren[lastLine].length > 1
height = multilineBounds.bottom() - lastRect.y
top = lastRect.y + height / 2 - @view.opts.buttonHeight/2
else
height = lastRect.bottom() - multilineBounds.bottom()
top = multilineBounds.bottom() + height/2 - @view.opts.buttonHeight/2
@buttonGroups[key].style.transform = "translate(#{start}, #{top})"
@buttonGroups[key].update()
@buttonPaths[key].update()
@buttonRects[key] = new @view.draw.Rectangle start, top, @view.opts.buttonWidth, @view.opts.buttonHeight
@elements.push @buttonPaths[key]
start += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
# Return it.
return @path
# ## addTab
# Add the tab graphic to a path in a given location.
addTab: (array, point) ->
# Rightmost point of the tab, where it begins to dip down.
array.push new @view.draw.Point(point.x + @view.opts.tabWidth,
point.y)
# Dip down.
array.push new @view.draw.Point point.x + @view.opts.tabWidth * (1 - @view.opts.tabSideWidth),
point.y + @view.opts.tabHeight
# Bottom plateau.
array.push new @view.draw.Point point.x + @view.opts.tabWidth * @view.opts.tabSideWidth,
point.y + @view.opts.tabHeight
# Rise back up.
array.push new @view.draw.Point point.x, point.y
# Move over to the given corner itself.
array.push point
# ## addTabReverse
# Add the tab in reverse order
addTabReverse: (array, point) ->
array.push point
array.push new @view.draw.Point point.x, point.y
array.push new @view.draw.Point point.x + @view.opts.tabWidth * @view.opts.tabSideWidth,
point.y + @view.opts.tabHeight
array.push new @view.draw.Point point.x + @view.opts.tabWidth * (1 - @view.opts.tabSideWidth),
point.y + @view.opts.tabHeight
array.push new @view.draw.Point(point.x + @view.opts.tabWidth,
point.y)
mark: (style) ->
@view.registerMark @model.id
@markStyle = style
@focusAll()
unmark: -> @markStyle = null
# ## drawSelf
# Draw our path, with applied
# styles if necessary.
drawSelf: (style = {}) ->
# We might want to apply some
# temporary color changes,
# so store the old colors
oldFill = @path.style.fillColor
oldStroke = @path.style.strokeColor
if style.grayscale
# Change path color
if @path.style.fillColor isnt 'none'
@path.style.fillColor = avgColor @path.style.fillColor, 0.5, '#888'
if @path.style.strokeColor isnt 'none'
@path.style.strokeColor = avgColor @path.style.strokeColor, 0.5, '#888'
if style.selected
# Change path color
if @path.style.fillColor isnt 'none'
@path.style.fillColor = avgColor @path.style.fillColor, 0.7, '#00F'
if @path.style.strokeColor isnt 'none'
@path.style.strokeColor = avgColor @path.style.strokeColor, 0.7, '#00F'
@path.setMarkStyle @markStyle
@path.update()
if @model.buttons? then for {key} in @model.buttons
@buttonPaths[key].update()
@buttonGroups[key].update()
for element in [@buttonPaths[key], @buttonGroups[key], @buttonTexts[key]]
unless element in @activeElements # TODO unlikely but might be performance chokehold?
@activeElements.push element # Possibly replace activeElements with a more set-like structure.
# Unset all the things we changed
@path.style.fillColor = oldFill
@path.style.strokeColor = oldStroke
if @model.buttons? then for {key} in @model.buttons
if @buttonPaths[key].active
@buttonPaths[key].style.fillColor = oldFill
@buttonPaths[key].style.strokeColor = oldStroke
return null
# ## computeOwnDropArea
# By default, we will not have a
# drop area (not be droppable).
computeOwnDropArea: ->
@dropPoint = null
if @highlightArea?
@elements = @elements.filter (x) -> x isnt @highlightArea
@highlightArea.destroy()
@highlightArea = null
# ## shouldAddTab
# By default, we will ask
# not to have a tab.
shouldAddTab: NO
# # BlockViewNode
class BlockViewNode extends ContainerViewNode
constructor: ->
super
computeMinDimensions: ->
if @computedVersion is @model.version
return null
super
# Blocks have a shape including a lego nubby "tab", and so
# they need to be at least wide enough for tabWidth+tabOffset.
for size, i in @minDimensions
size.width = Math.max size.width,
@view.opts.tabWidth + @view.opts.tabOffset
size.width += @extraLeft
return null
shouldAddTab: ->
if @model.parent? and @view.hasViewNodeFor(@model.parent) and not
(@model.parent.type is 'document' and @model.parent.opts.roundedSingletons and
@model.start.prev is @model.parent.start and @model.end.next is @model.parent.end)
return @model.parent?.type isnt 'socket'
else
return not (@model.shape in [helper.MOSTLY_VALUE, helper.VALUE_ONLY])
computeOwnDropArea: ->
unless @model.parent?.type in ['indent', 'document']
@dropPoint = null
return
# Our drop area is a puzzle-piece shaped path
# of height opts.highlightAreaHeight and width
# equal to our last line width,
# positioned at the bottom of our last line.
if @carriageArrow is CARRIAGE_ARROW_INDENT
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
@dropPoint = new @view.draw.Point destinationBounds.x, destinationBounds.y
lastBoundsLeft = destinationBounds.x
lastBoundsRight = destinationBounds.right()
else if @carriageArrow is CARRIAGE_ARROW_SIDEALONG
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
@dropPoint = new @view.draw.Point destinationBounds.x,
@bounds[@lineLength - 1].bottom() + @view.opts.padding
lastBoundsLeft = destinationBounds.x
lastBoundsRight = @bounds[@lineLength - 1].right()
else
@dropPoint = new @view.draw.Point @bounds[@lineLength - 1].x, @bounds[@lineLength - 1].bottom()
lastBoundsLeft = @bounds[@lineLength - 1].x
lastBoundsRight = @bounds[@lineLength - 1].right()
# Our highlight area is the a rectangle in the same place,
# with a height that can be given by a different option.
highlightAreaPoints = []
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft, @dropPoint.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft + @view.opts.bevelClip, @dropPoint.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBoundsLeft + @view.opts.tabOffset, @dropPoint.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsRight - @view.opts.bevelClip, @dropPoint.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsRight, @dropPoint.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsRight, @dropPoint.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsRight - @view.opts.bevelClip, @dropPoint.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBoundsLeft + @view.opts.tabOffset, @dropPoint.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft + @view.opts.bevelClip, @dropPoint.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft, @dropPoint.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
# # SocketViewNode
class SocketViewNode extends ContainerViewNode
constructor: ->
super
if @view.opts.showDropdowns and @model.dropdown?
@dropdownElement ?= @view.draw.path([], false, {
fillColor: (if @view.opts.invert then DROP_TRIANGLE_INVERT_COLOR else DROP_TRIANGLE_COLOR),
cssClass: 'droplet-dropdown-arrow'
})
@dropdownElement.deactivate()
@dropdownElement.setParent @group
@elements.push @dropdownElement
@activeElements.push @dropdownElement
shouldAddTab: NO
isInvisibleSocket: ->
'' is @model.emptyString and @model.start?.next is @model.end
# ## computeDimensions (SocketViewNode)
# Sockets have a couple exceptions to normal dimension computation.
#
# 1. Sockets have minimum dimensions even if empty.
# 2. Sockets containing blocks mimic the block exactly.
computeMinDimensions: ->
# Use cache if possible.
if @computedVersion is @model.version
return null
super
@minDistanceToBase[0].above = Math.max(@minDistanceToBase[0].above,
@view.opts.textHeight + @view.opts.textPadding)
@minDistanceToBase[0].below = Math.max(@minDistanceToBase[0].below,
@view.opts.textPadding)
@minDimensions[0].height =
@minDistanceToBase[0].above + @minDistanceToBase[0].below
for dimension in @minDimensions
dimension.width = Math.max(dimension.width,
if @isInvisibleSocket()
@view.opts.invisibleSocketWidth
else
@view.opts.minSocketWidth)
if @model.hasDropdown() and @view.opts.showDropdowns
dimension.width += helper.DROPDOWN_ARROW_WIDTH
return null
# ## computeBoundingBoxX (SocketViewNode)
computeBoundingBoxX: (left, line) ->
super left, line, (
if @model.hasDropdown() and @view.opts.showDropdowns
helper.DROPDOWN_ARROW_WIDTH
else 0
)
# ## computeGlue
# Sockets have one exception to normal glue spacing computation:
# sockets containing a block should **not** add padding to
# the glue.
computeGlue: ->
# Use cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
# Do not add padding to the glue
# if our child is a block.
if @model.start.next.type is 'blockStart'
view = @view.getViewNodeFor @model.start.next.container
@glue = view.computeGlue()
# Otherwise, decrement the glue version
# to force super to recompute,
# and call super.
else
super
# ## computeOwnPath (SocketViewNode)
# Again, exception: sockets containing block
# should mimic blocks exactly.
#
# Under normal circumstances this shouldn't
# actually be an issue, but if we decide
# to change the Block's path,
# the socket should not have stuff sticking out,
# and should hit-test properly.
computeOwnPath: ->
# Use cache if possible.
if @computedVersion is @model.version and
not @changedBoundingBox
return @path
@path.style.fillColor = if @view.opts.invert then '#333' else '#FFF'
if @model.start.next.type is 'blockStart'
@path.style.fillColor = 'none'
# Otherwise, call super.
else
super
# If the socket is empty, make it invisible except
# for mouseover
if '' is @model.emptyString and @model.start?.next is @model.end
@path.style.cssClass = 'droplet-socket-path droplet-empty-socket-path'
@path.style.fillColor = 'none'
else
@path.style.cssClass = 'droplet-socket-path'
return @path
# ## drawSelf (SocketViewNode)
drawSelf: (style = {}) ->
super
if @model.hasDropdown() and @view.opts.showDropdowns
@dropdownElement.setPoints([new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_PADDING,
@bounds[0].y + (@bounds[0].height - DROPDOWN_ARROW_HEIGHT) / 2),
new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_WIDTH - helper.DROPDOWN_ARROW_PADDING,
@bounds[0].y + (@bounds[0].height - DROPDOWN_ARROW_HEIGHT) / 2),
new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_WIDTH / 2,
@bounds[0].y + (@bounds[0].height + DROPDOWN_ARROW_HEIGHT) / 2)
])
@dropdownElement.update()
unless @dropdownElement in @activeElements
@activeElements.push @dropdownElement
else if @dropdownElement?
@activeElements = @activeElements.filter (x) -> x isnt @dropdownElement
@dropdownElement.deactivate()
# ## computeOwnDropArea (SocketViewNode)
# Socket drop areas are actually the same
# shape as the sockets themselves, which
# is different from most other
# things.
computeOwnDropArea: ->
if @model.start.next.type is 'blockStart'
@dropPoint = null
@highlightArea.deactivate()
else
@dropPoint = @bounds[0].upperLeftCorner()
@highlightArea.setPoints @path._points
@highlightArea.style.strokeColor = '#FF0'
@highlightArea.style.fillColor = 'none'
@highlightArea.style.lineWidth = @view.opts.highlightAreaHeight / 2
@highlightArea.update()
@highlightArea.deactivate()
# # IndentViewNode
class IndentViewNode extends ContainerViewNode
constructor: ->
super
@lastFirstChildren = []
@lastLastChildren = []
# ## computeOwnPath
# An Indent should also have no drawn
# or hit-tested path.
computeOwnPath: ->
# ## computeChildren
computeChildren: ->
super
unless arrayEq(@lineChildren[0], @lastFirstChildren) and
arrayEq(@lineChildren[@lineLength - 1], @lastLastChildren)
for childObj in @children
childView = @view.getViewNodeFor childObj.child
if childView.topLineSticksToBottom or childView.bottomLineSticksToTop
childView.invalidate = true
if childView.lineLength is 1
childView.topLineSticksToBottom =
childView.bottomLineSticksToTop = false
for childRef in @lineChildren[0]
childView = @view.getViewNodeFor(childRef.child)
unless childView.topLineSticksToBottom
childView.invalidate = true
childView.topLineSticksToBottom = true
for childRef in @lineChildren[@lineChildren.length - 1]
childView = @view.getViewNodeFor(childRef.child)
unless childView.bottomLineSticksToTop
childView.invalidate = true
childView.bottomLineSticksToTop = true
return @lineLength
# ## computeDimensions (IndentViewNode)
#
# Give width to any empty lines
# in the Indent.
computeMinDimensions: ->
super
for size, line in @minDimensions[1..] when size.width is 0
size.width = @view.opts.emptyLineWidth
# ## drawSelf
#
# Again, an Indent should draw nothing.
drawSelf: ->
# ## computeOwnDropArea
#
# Our drop area is a rectangle of
# height dropAreaHeight and a width
# equal to our first line width,
# positioned at the top of our firs tline
computeOwnDropArea: ->
lastBounds = new @view.draw.NoRectangle()
if @model.start.next.type is 'newline'
@dropPoint = @bounds[1].upperLeftCorner()
lastBounds.copy @bounds[1]
else
@dropPoint = @bounds[0].upperLeftCorner()
lastBounds.copy @bounds[0]
lastBounds.width = Math.max lastBounds.width, @view.opts.indentDropAreaMinWidth
# Our highlight area is the a rectangle in the same place,
# with a height that can be given by a different option.
highlightAreaPoints = []
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
# # DocumentViewNode
# Represents a Document. Draws little, but
# recurses.
class DocumentViewNode extends ContainerViewNode
constructor: -> super
# ## computeOwnPath
#
computeOwnPath: ->
# ## computeOwnDropArea
#
# Root documents
# can be dropped at their beginning.
computeOwnDropArea: ->
@dropPoint = @bounds[0].upperLeftCorner()
highlightAreaPoints = []
lastBounds = new @view.draw.NoRectangle()
lastBounds.copy @bounds[0]
lastBounds.width = Math.max lastBounds.width, @view.opts.indentDropAreaMinWidth
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
return null
# # TextViewNode
#
# TextViewNode does not extend ContainerViewNode.
# We contain a @view.draw.TextElement to measure
# bounding boxes and draw text.
class TextViewNode extends GenericViewNode
constructor: (@model, @view) ->
super
@textElement = @view.draw.text(
new @view.draw.Point(0, 0),
@model.value,
if @view.opts.invert then '#FFF' else '#000'
)
@textElement.destroy()
@elements.push @textElement
# ## computeChildren
#
# Text elements are one line
# and contain no children (and thus
# no multiline children, either)
computeChildren: ->
@multilineChildrenData = [NO_MULTILINE]
return @lineLength = 1
# ## computeMinDimensions (TextViewNode)
#
# Set our dimensions to the measured dimensinos
# of our text value.
computeMinDimensions: ->
if @computedVersion is @model.version
return null
@textElement.point = new @view.draw.Point 0, 0
@textElement.value = @model.value
height = @view.opts.textHeight
@minDimensions[0] = new @view.draw.Size(@textElement.bounds().width, height)
@minDistanceToBase[0] = {above: height, below: 0}
return null
# ## computeBoundingBox (x and y)
#
# Assign the position of our textElement
# to match our laid out bounding box position.
computeBoundingBoxX: (left, line) ->
@textElement.point.x = left; super
computeBoundingBoxY: (top, line) ->
@textElement.point.y = top; super
# ## drawSelf
#
# Draw the text element itself.
drawSelf: (style = {}, parent = null) ->
@textElement.update()
if style.noText
@textElement.deactivate()
else
@textElement.activate()
if parent?
@textElement.setParent parent
toRGB = (hex) ->
# Convert to 6-char hex if not already there
if hex.length is 4
hex = (c + c for c in hex).join('')[1..]
# Extract integers from hex
r = parseInt hex[1..2], 16
g = parseInt hex[3..4], 16
b = parseInt hex[5..6], 16
return [r, g, b]
zeroPad = (str, len) ->
if str.length < len
('0' for [str.length...len]).join('') + str
else
str
twoDigitHex = (n) -> zeroPad Math.round(n).toString(16), 2
toHex = (rgb) ->
return '#' + (twoDigitHex(k) for k in rgb).join ''
avgColor = (a, factor, b) ->
a = toRGB a
b = toRGB b
newRGB = (a[i] * factor + b[i] * (1 - factor) for k, i in a)
return toHex newRGB
dedupe = (path) ->
path = path.filter((x, i) ->
not x.equals(path[(i - 1) %% path.length])
)
path = path.filter((x, i) ->
not draw._collinear(path[(i - 1) %% path.length], x, path[(i + 1) %% path.length])
)
return path
| 209288 | # Droplet editor view.
#
# Copyright (c) 2015 <NAME> (<EMAIL>)
# MIT License
helper = require './helper.coffee'
draw = require './draw.coffee'
model = require './model.coffee'
NO_MULTILINE = 0
MULTILINE_START = 1
MULTILINE_MIDDLE = 2
MULTILINE_END = 3
MULTILINE_END_START = 4
ANY_DROP = helper.ANY_DROP
BLOCK_ONLY = helper.BLOCK_ONLY
MOSTLY_BLOCK = helper.MOSTLY_BLOCK
MOSTLY_VALUE = helper.MOSTLY_VALUE
VALUE_ONLY = helper.VALUE_ONLY
CARRIAGE_ARROW_SIDEALONG = 0
CARRIAGE_ARROW_INDENT = 1
CARRIAGE_ARROW_NONE = 2
CARRIAGE_GROW_DOWN = 3
DROPDOWN_ARROW_HEIGHT = 8
DROP_TRIANGLE_COLOR = '#555'
DROP_TRIANGLE_INVERT_COLOR = '#CCC'
BUTTON_GLYPH_COLOR = 'rgba(0, 0, 0, 0.3)'
BUTTON_GLYPH_INVERT_COLOR = 'rgba(255, 255, 255, 0.5)'
SVG_STANDARD = helper.SVG_STANDARD
DEFAULT_OPTIONS =
buttonWidth: 15
lockedSocketButtonWidth: 15
buttonHeight: 15
extraLeft: 0
buttonVertPadding: 6
buttonHorizPadding: 3
minIndentTongueWidth: 150
showDropdowns: true
padding: 5
indentWidth: 20
indentTongueHeight: 20
tabOffset: 10
tabWidth: 15
tabHeight: 5
tabSideWidth: 0.125
dropAreaHeight: 20
indentDropAreaMinWidth: 50
minSocketWidth: 10
invisibleSocketWidth: 5
textHeight: 15
textPadding: 1
emptyLineWidth: 50
highlightAreaHeight: 10
bevelClip: 3
shadowBlur: 5
colors:
error: '#ff0000'
comment: '#c0c0c0' # gray
return: '#fff59d' # yellow
control: '#ffcc80' # orange
value: '#a5d6a7' # green
command: '#90caf9' # blue
red: '#ef9a9a'
pink: '#f48fb1'
purple: '#ce93d8'
deeppurple: '#b39ddb'
indigo: '#9fa8da'
blue: '#90caf9'
lightblue: '#81d4fa'
cyan: '#80deea'
teal: '#80cbc4'
green: '#a5d6a7'
lightgreen: '#c5e1a5'
darkgreen: '#008000'
lime: '#e6ee9c'
yellow: '#fff59d'
amber: '#ffe082'
orange: '#ffcc80'
deeporange: '#ffab91'
brown: '#bcaaa4'
grey: '#eeeeee'
bluegrey: '#b0bec5'
function: '#90caf9'
declaration: '#e6ee9c'
value: '#a5d6a7'
logic: '#ffab91'
assign: '#fff59d'
functionCall: '#90caf9'
control: '#ffab91'
YES = -> yes
NO = -> no
arrayEq = (a, b) ->
return false if a.length isnt b.length
return false if k isnt b[i] for k, i in a
return true
# # View
# The View class contains options and caches
# for rendering. The controller instantiates a View
# and interacts with things through it.
#
# Inner classes in the View correspond to Model
# types (e.g. SocketViewNode, etc.) all of which
# will have access to their View's caches
# and options object.
exports.View = class View
constructor: (@ctx, @opts = {}) ->
@ctx ?= document.createElementNS SVG_STANDARD, 'svg'
# @map maps Model objects
# to corresponding View objects,
# so that rerendering the same model
# can be fast
@map = {}
@oldRoots = {}
@newRoots = {}
@auxiliaryMap = {}
@flaggedToDelete = {}
@unflaggedToDelete = {}
@marks = {}
@draw = new draw.Draw(@ctx)
# Apply default options
for option of DEFAULT_OPTIONS
unless option of @opts
@opts[option] = DEFAULT_OPTIONS[option]
for color of DEFAULT_OPTIONS.colors
unless color of @opts.colors
@opts.colors[color] = DEFAULT_OPTIONS.colors[color]
if @opts.invert
@opts.colors['comment'] = '#606060'
# Simple method for clearing caches
clearCache: ->
for id of @map
@map[id].destroy()
@destroy id
# Remove everything from the canvas
clearFromCanvas: ->
@beginDraw()
@cleanupDraw()
# ## getViewNodeFor
# Given a model object,
# give the corresponding renderer object
# under this View. If one does not exist,
# create one, then preserve it in our map.
getViewNodeFor: (model) ->
if model.id of @map
return @map[model.id]
else
return @createView(model)
registerMark: (id) ->
@marks[id] = true
clearMarks: ->
for key, val of @marks
@map[key].unmark()
@marks = {}
beginDraw: ->
@newRoots = {}
hasViewNodeFor: (model) ->
model? and model.id of @map
getAuxiliaryNode: (node) ->
if node.id of @auxiliaryMap
return @auxiliaryMap[node.id]
else
return @auxiliaryMap[node.id] = new AuxiliaryViewNode(@, node)
registerRoot: (node) ->
if node instanceof model.List and not (
node instanceof model.Container)
node.traverseOneLevel (head) =>
unless head instanceof model.NewlineToken
@registerRoot head
return
for id, aux of @newRoots
if aux.model.hasParent(node)
delete @newRoots[id]
else if node.hasParent(aux.model)
return
@newRoots[node.id] = @getAuxiliaryNode(node)
cleanupDraw: ->
@flaggedToDelete = {}
@unflaggedToDelete = {}
for id, el of @oldRoots
unless id of @newRoots
@flag el
for id, el of @newRoots
el.cleanup()
for id, el of @flaggedToDelete when id of @unflaggedToDelete
delete @flaggedToDelete[id]
for id, el of @flaggedToDelete when id of @map
@map[id].hide()
@oldRoots = @newRoots
flag: (auxiliaryNode) ->
@flaggedToDelete[auxiliaryNode.model.id] = auxiliaryNode
unflag: (auxiliaryNode) ->
@unflaggedToDelete[auxiliaryNode.model.id] = auxiliaryNode
garbageCollect: ->
@cleanupDraw()
for id, el of @flaggedToDelete when id of @map
@map[id].destroy()
@destroy id
for id, el of @newRoots
el.update()
destroy: (id) ->
for child in @map[id].children
if @map[child.child.id]? and not @unflaggedToDelete[child.child.id]
@destroy child.child.id
delete @map[id]
delete @auxiliaryMap[id]
delete @flaggedToDelete[id]
hasViewNodeFor: (model) -> model? and model.id of @map
# ## createView
# Given a model object, create a renderer object
# of the appropriate type.
createView: (entity) ->
if (entity instanceof model.List) and not
(entity instanceof model.Container)
return new ListViewNode entity, this
switch entity.type
when 'text' then new TextViewNode entity, this
when 'block' then new BlockViewNode entity, this
when 'indent' then new IndentViewNode entity, this
when 'socket' then new SocketViewNode entity, this
when 'buttonContainer' then new ContainerViewNode entity, this
when 'lockedSocket' then new ContainerViewNode entity, this # LockedSocketViewNode entity, this
when 'document' then new DocumentViewNode entity, this
# Looks up a color name, or passes through a #hex color.
getColor: (model) ->
if model?.color instanceof Function
color = model.color(model)
else if model?
color = model.color
else
color = ""
if color and '#' is color.charAt(0)
color
else
@opts.colors[color] ? '#ffffff'
class AuxiliaryViewNode
constructor: (@view, @model) ->
@children = {}
@computedVersion = -1
cleanup: ->
@view.unflag @
if @model.version is @computedVersion
return
children = {}
if @model instanceof model.Container
@model.traverseOneLevel (head) =>
if head instanceof model.NewlineToken
return
else
children[head.id] = @view.getAuxiliaryNode head
for id, child of @children
unless id of children
@view.flag child
for id, child of children
@children[id] = child
child.cleanup()
update: ->
@view.unflag @
if @model.version is @computedVersion
return
children = {}
if @model instanceof model.Container
@model.traverseOneLevel (head) =>
if head instanceof model.NewlineToken
return
else
children[head.id] = @view.getAuxiliaryNode head
@children = children
for id, child of @children
child.update()
@computedVersion = @model.version
# # GenericViewNode
# Class from which all renderer classes will
# extend.
class GenericViewNode
constructor: (@model, @view) ->
# Record ourselves in the map
# from model to renderer
@view.map[@model.id] = this
@view.registerRoot @model
@lastCoordinate = new @view.draw.Point 0, 0
@invalidate = false
# *Zeroth pass variables*
# computeChildren
@lineLength = 0 # How many lines does this take up?
@children = [] # All children, flat
@oldChildren = [] # Previous children, for removing
@lineChildren = [] # Children who own each line
@multilineChildrenData = [] # Where do indents start/end?
# *First pass variables*
# computeMargins
@margins = {left:0, right:0, top:0, bottom:0}
@topLineSticksToBottom = false
@bottomLineSticksToTop = false
# *Pre-second pass variables*
# computeMinDimensions
# @view.draw.Size type, {width:n, height:m}
@minDimensions = [] # Dimensions on each line
@minDistanceToBase = [] # {above:n, below:n}
# *Second pass variables*
# computeDimensions
# @view.draw.Size type, {width:n, height:m}
@dimensions = [] # Dimensions on each line
@distanceToBase = [] # {above:n, below:n}
@carriageArrow = CARRIAGE_ARROW_NONE
@bevels =
top: false
bottom: false
# *Third/fifth pass variables*
# computeBoundingBoxX, computeBoundingBoxY
# @view.draw.Rectangle type, {x:0, y:0, width:200, height:100}
@bounds = [] # Bounding boxes on each line
@changedBoundingBox = true # Did any bounding boxes change just now?
# *Fourth pass variables*
# computeGlue
# {height:2, draw:true}
@glue = {}
@elements = []
@activeElements = []
# Versions. The corresponding
# Model will keep corresponding version
# numbers, and each of our passes can
# become a no-op when we are up-to-date (so
# that rerendering is fast when there are
# few or no changes to the Model).
@computedVersion = -1
draw: (boundingRect, style = {}, parent = null) ->
@drawSelf style, parent
root: ->
for element in @elements
element.setParent @view.draw.ctx
serialize: (line) ->
result = []
for prop in [
'lineLength'
'margins'
'topLineSticksToBottom'
'bottomLineSticksToTop'
'changedBoundingBox'
'path'
'highlightArea'
'computedVersion'
'carriageArrow'
'bevels']
result.push(prop + ': ' + JSON.stringify(@[prop]))
for child, i in @children
result.push("child #{i}: {startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}")
if line?
for prop in [
'multilineChildrenData'
'minDimensions'
'minDistanceToBase'
'dimensions'
'distanceToBase'
'bounds'
'glue']
result.push("#{prop} #{line}: #{JSON.stringify(@[prop][line])}")
for child, i in @lineChildren[line]
result.push("line #{line} child #{i}: " +
"{startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}}")
else
for line in [0...@lineLength]
for prop in [
'multilineChildrenData'
'minDimensions'
'minDistanceToBase'
'dimensions'
'distanceToBase'
'bounds'
'glue']
result.push("#{prop} #{line}: #{JSON.stringify(@[prop][line])}")
for child, i in @lineChildren[line]
result.push("line #{line} child #{i}: " +
"{startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}}")
return result.join('\n')
# ## computeChildren (GenericViewNode)
# Find out which of our children lie on each line that we
# own, and also how many lines we own.
#
# Return the number of lines we own.
#
# This is basically a void computeChildren that should be
# overridden.
computeChildren: -> @lineLength
focusAll: ->
@group.focus()
computeCarriageArrow: ->
for childObj in @children
@view.getViewNodeFor(childObj.child).computeCarriageArrow()
return @carriageArrow
# ## computeMargins (GenericViewNode)
# Compute the amount of margin required outside the child
# on the top, bottom, left, and right.
#
# This is a void computeMargins that should be overridden.
computeMargins: ->
if @computedVersion is @model.version and
(not @model.parent? or not @view.hasViewNodeFor(@model.parent) or
@model.parent.version is @view.getViewNodeFor(@model.parent).computedVersion)
return @margins
# the margins I need depend on the type of my parent
parenttype = @model.parent?.type
padding = @view.opts.padding
left = if @model.isFirstOnLine() or @lineLength > 1 then padding else 0
right = if @model.isLastOnLine() or @lineLength > 1 then padding else 0
if parenttype is 'block' and @model.type is 'indent'
@margins =
top: 0
bottom: if @lineLength > 1 then @view.opts.indentTongueHeight else padding
firstLeft: padding
midLeft: @view.opts.indentWidth
lastLeft: @view.opts.indentWidth
firstRight: 0
midRight: 0
lastRight: padding
else if @model.type is 'text' and parenttype is 'socket'
@margins =
top: @view.opts.textPadding
bottom: @view.opts.textPadding
firstLeft: @view.opts.textPadding
midLeft: @view.opts.textPadding
lastLeft: @view.opts.textPadding
firstRight: @view.opts.textPadding
midRight: @view.opts.textPadding
lastRight: @view.opts.textPadding
else if @model.type is 'text' and parenttype is 'block'
if @model.prev?.type is 'newline' and @model.next?.type in ['newline', 'indentStart'] or @model.prev?.prev?.type is 'indentEnd'
textPadding = padding / 2
else
textPadding = padding
@margins =
top: textPadding
bottom: textPadding #padding
firstLeft: left
midLeft: left
lastLeft: left
firstRight: right
midRight: right
lastRight: right
else if parenttype is 'block'
@margins =
top: padding
bottom: padding
firstLeft: left
midLeft: padding
lastLeft: padding
firstRight: right
midRight: 0
lastRight: right
else
@margins = {
firstLeft: 0, midLeft:0, lastLeft: 0
firstRight: 0, midRight:0, lastRight: 0
top:0, bottom:0
}
@firstMargins =
left: @margins.firstLeft
right: @margins.firstRight
top: @margins.top
bottom: if @lineLength is 1 then @margins.bottom else 0
@midMargins =
left: @margins.midLeft
right: @margins.midRight
top: 0
bottom: 0
@lastMargins =
left: @margins.lastLeft
right: @margins.lastRight
top: if @lineLength is 1 then @margins.top else 0
bottom: @margins.bottom
for childObj in @children
@view.getViewNodeFor(childObj.child).computeMargins()
return null
getMargins: (line) ->
if line is 0 then @firstMargins
else if line is @lineLength - 1 then @lastMargins
else @midMargins
computeBevels: ->
for childObj in @children
@view.getViewNodeFor(childObj.child).computeBevels()
return @bevels
# ## computeMinDimensions (GenericViewNode)
# Compute the size of our bounding box on each
# line that we contain.
#
# Return child node.
#
# This is a void computeDimensinos that should be overridden.
computeMinDimensions: ->
if @minDimensions.length > @lineLength
@minDimensions.length = @minDistanceToBase.length = @lineLength
else
until @minDimensions.length is @lineLength
@minDimensions.push new @view.draw.Size 0, 0
@minDistanceToBase.push {above: 0, below: 0}
for i in [0...@lineLength]
@minDimensions[i].width = @minDimensions[i].height = 0
@minDistanceToBase[i].above = @minDistanceToBase[i].below = 0
return null
# ## computeDimensions (GenericViewNode)
# Compute the size of our bounding box on each
# line that we contain.
#
# Return child node.
computeDimensions: (force, root = false) ->
if @computedVersion is @model.version and not force and not @invalidate
return
oldDimensions = @dimensions
oldDistanceToBase = @distanceToBase
@dimensions = (new @view.draw.Size 0, 0 for [0...@lineLength])
@distanceToBase = ({above: 0, below: 0} for [0...@lineLength])
for size, i in @minDimensions
@dimensions[i].width = size.width; @dimensions[i].height = size.height
@distanceToBase[i].above = @minDistanceToBase[i].above
@distanceToBase[i].below = @minDistanceToBase[i].below
if @model.parent? and @view.hasViewNodeFor(@model.parent) and not root and
(@topLineSticksToBottom or @bottomLineSticksToTop or
(@lineLength > 1 and not @model.isLastOnLine()))
parentNode = @view.getViewNodeFor @model.parent
startLine = @model.getLinesToParent()
# grow below if "stick to bottom" is set.
if @topLineSticksToBottom
distance = @distanceToBase[0]
distance.below = Math.max(distance.below,
parentNode.distanceToBase[startLine].below)
@dimensions[0] = new @view.draw.Size(
@dimensions[0].width,
distance.below + distance.above)
# grow above if "stick to top" is set.
if @bottomLineSticksToTop
lineCount = @distanceToBase.length
distance = @distanceToBase[lineCount - 1]
distance.above = Math.max(distance.above,
parentNode.distanceToBase[startLine + lineCount - 1].above)
@dimensions[lineCount - 1] = new @view.draw.Size(
@dimensions[lineCount - 1].width,
distance.below + distance.above)
if @lineLength > 1 and not @model.isLastOnLine() and @model.type is 'block'
distance = @distanceToBase[@lineLength - 1]
distance.below = parentNode.distanceToBase[startLine + @lineLength - 1].below
@dimensions[lineCount - 1] = new @view.draw.Size(
@dimensions[lineCount - 1].width,
distance.below + distance.above)
changed = (oldDimensions.length != @lineLength)
if not changed then for line in [0...@lineLength]
if !oldDimensions[line].equals(@dimensions[line]) or
oldDistanceToBase[line].above != @distanceToBase[line].above or
oldDistanceToBase[line].below != @distanceToBase[line].below
changed = true
break
@changedBoundingBox or= changed
for childObj in @children
if childObj in @lineChildren[0] or childObj in @lineChildren[@lineLength - 1]
@view.getViewNodeFor(childObj.child).computeDimensions(changed, not (@model instanceof model.Container)) #(hack)
else
@view.getViewNodeFor(childObj.child).computeDimensions(false, not (@model instanceof model.Container)) #(hack)
return null
# ## computeBoundingBoxX (GenericViewNode)
# Given the left edge coordinate for our bounding box on
# this line, recursively layout the x-coordinates of us
# and all our children on this line.
computeBoundingBoxX: (left, line) ->
# Attempt to use our cache. Because modifications in the parent
# can affect the shape of child blocks, we can't only rely
# on versioning. For instance, changing `fd 10` to `forward 10`
# does not update the version on `10`, but the bounding box for
# `10` still needs to change. So we must also check
# that the coordinate we are given to begin the bounding box on matches.
if @computedVersion is @model.version and
left is @bounds[line]?.x and not @changedBoundingBox or
@bounds[line]?.x is left and
@bounds[line]?.width is @dimensions[line].width
return @bounds[line]
@changedBoundingBox = true
# Avoid re-instantiating a Rectangle object,
# if possible.
if @bounds[line]?
@bounds[line].x = left
@bounds[line].width = @dimensions[line].width
# If not, create one.
else
@bounds[line] = new @view.draw.Rectangle(
left, 0
@dimensions[line].width, 0
)
return @bounds[line]
# ## computeAllBoundingBoxX (GenericViewNode)
# Call `@computeBoundingBoxX` on all lines,
# thus laying out the entire document horizontally.
computeAllBoundingBoxX: (left = 0) ->
for size, line in @dimensions
@computeBoundingBoxX left, line
return @bounds
# ## computeGlue (GenericViewNode)
# If there are disconnected bounding boxes
# that belong to the same block,
# insert "glue" spacers between lines
# to connect them. For instance:
#
# ```
# someLongFunctionName ''' hello
# world '''
# ```
#
# would require glue between 'hello' and 'world'.
#
# This is a void function that should be overridden.
computeGlue: ->
@glue = {}
# ## computeBoundingBoxY (GenericViewNode)
# Like computeBoundingBoxX. We must separate
# these passes because glue spacers from `computeGlue`
# affect computeBoundingBoxY.
computeBoundingBoxY: (top, line) ->
# Again, we need to check to make sure that the coordinate
# we are given matches, since we cannot only rely on
# versioning (see computeBoundingBoxX).
if @computedVersion is @model.version and
top is @bounds[line]?.y and not @changedBoundingBox or
@bounds[line].y is top and
@bounds[line].height is @dimensions[line].height
return @bounds[line]
@changedBoundingBox = true
# Accept the bounding box edge we were given.
# We assume here that computeBoundingBoxX was
# already run for this version, so we
# should be guaranteed that `@bounds[line]` exists.
@bounds[line].y = top
@bounds[line].height = @dimensions[line].height
return @bounds[line]
# ## computeAllBoundingBoxY (GenericViewNode)
# Call `@computeBoundingBoxY` on all lines,
# thus laying out the entire document vertically.
#
# Account for glue spacing between lines.
computeAllBoundingBoxY: (top = 0) ->
for size, line in @dimensions
@computeBoundingBoxY top, line
top += size.height
if line of @glue then top += @glue[line].height
return @bounds
# ## getBounds (GenericViewNode)
# Deprecated. Access `@totalBounds` directly instead.
getBounds: -> @totalBounds
# ## computeOwnPath
# Using bounding box data, compute the vertices
# of the polygon that will wrap them. This function
# will be called from `computePath`, which does this
# recursively so as to draw the entire tree.
#
# Many nodes do not have paths at all,
# and so need not override this function.
computeOwnPath: ->
# ## computePath (GenericViewNode)
# Call `@computeOwnPath` and recurse. This function
# should never need to be overridden; override `@computeOwnPath`
# instead.
computePath: ->
# Here, we cannot just rely on versioning either.
# We need to know if any bounding box data changed. So,
# look at `@changedBoundingBox`, which should be set
# to `true` whenever a bounding box changed on the bounding box
# passes.
if @computedVersion is @model.version and
(@model.isLastOnLine() is @lastComputedLinePredicate) and
not @changedBoundingBox
return null
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computePath()
# It is possible that we have a version increment
# without changing bounding boxes. If this is the case,
# we don't need to recompute our own path.
if @changedBoundingBox or (@model.isLastOnLine() isnt @lastComputedLinePredicate)
@computeOwnPath()
# Recompute `totalBounds`, which is used
# to avoid re*drawing* polygons that
# are not on-screen. `totalBounds` is the AABB
# of the everything that has to do with the element,
# and we redraw iff it overlaps the AABB of the viewport.
@totalBounds = new @view.draw.NoRectangle()
if @bounds.length > 0
@totalBounds.unite @bounds[0]
@totalBounds.unite @bounds[@bounds.length - 1]
# Figure out our total bounding box however is faster.
if @bounds.length > @children.length
for child in @children
@totalBounds.unite @view.getViewNodeFor(child.child).totalBounds
else
maxRight = @totalBounds.right()
for bound in @bounds
@totalBounds.x = Math.min @totalBounds.x, bound.x
maxRight = Math.max maxRight, bound.right()
@totalBounds.width = maxRight - @totalBounds.x
if @path?
@totalBounds.unite @path.bounds()
@lastComputedLinePredicate = @model.isLastOnLine()
return null
# ## computeOwnDropArea (GenericViewNode)
# Using bounding box data, compute the drop area
# for drag-and-drop blocks, if it exists.
#
# If we cannot drop something on this node
# (e.g. a socket that already contains a block),
# set `@dropArea` to null.
#
# Simultaneously, compute `@highlightArea`, which
# is the white polygon that lights up
# when we hover over a drop area.
computeOwnDropArea: ->
# ## computeDropAreas (GenericViewNode)
# Call `@computeOwnDropArea`, and recurse.
#
# This should never have to be overridden;
# override `@computeOwnDropArea` instead.
computeDropAreas: ->
# Like with `@computePath`, we cannot rely solely on versioning,
# so we check the bounding box flag.
if @computedVersion is @model.version and
not @changedBoundingBox
return null
# Compute drop and highlight areas for ourself
@computeOwnDropArea()
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computeDropAreas()
return null
computeNewVersionNumber: ->
if @computedVersion is @model.version and
not @changedBoundingBox
return null
@changedBoundingBox = false
@invalidate = false
@computedVersion = @model.version
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computeNewVersionNumber()
return null
# ## drawSelf (GenericViewNode)
# Draw our own polygon on a canvas context.
# May require special effects, like graying-out
# or blueing for lasso select.
drawSelf: (style = {}) ->
hide: ->
for element in @elements
element?.deactivate?()
@activeElements = []
destroy: (root = true) ->
if root
for element in @elements
element?.destroy?()
else if @highlightArea?
@highlightArea.destroy()
@activeElements = []
for child in @children
@view.getViewNodeFor(child.child).destroy(false)
class ListViewNode extends GenericViewNode
constructor: (@model, @view) ->
super
draw: (boundingRect, style = {}, parent = null) ->
super
for childObj in @children
@view.getViewNodeFor(childObj.child).draw boundingRect, style, @group
root: ->
for child in @children
@view.getViewNodeFor(child.child).root()
destroy: (root = true) ->
for child in @children
@view.getViewNodeFor(child.child).destroy()
# ## computeChildren (ListViewNode)
# Figure out which children lie on each line,
# and compute `@multilineChildrenData` simultaneously.
#
# We will do this by going to all of our immediate children,
# recursing, then calculating their starting and ending lines
# based on their computing line lengths.
computeChildren: ->
# If we can, use our cached information.
if @computedVersion is @model.version
return @lineLength
# Otherwise, recompute.
@lineLength = 0
@lineChildren = [[]]
@children = []
@multilineChildrenData = []
@topLineSticksToBottom = false
@bottomLineSticksToTop = false
line = 0
# Go to all our immediate children.
@model.traverseOneLevel (head) =>
# If the child is a newline, simply advance the
# line counter.
if head.type is 'newline'
line += 1
@lineChildren[line] ?= []
# Otherwise, get the view object associated
# with this model, and ask it to
# compute children.
else
view = @view.getViewNodeFor(head)
childLength = view.computeChildren()
# Construct a childObject,
# which will remember starting and endling lines.
childObject =
child: head
startLine: line
endLine: line + childLength - 1
# Put it into `@children`.
@children.push childObject
# Put it into `@lineChildren`.
for i in [line...line + childLength]
@lineChildren[i] ?= []
# We don't want to store cursor tokens
# in `@lineChildren`, as they are inconvenient
# to deal with in layout, which is the only
# thing `@lineChildren` is used for.
unless head.type is 'cursor'
@lineChildren[i].push childObject
# If this object is a multiline child,
# update our multiline child data to reflect
# where it started and ended.
if view.lineLength > 1
if @multilineChildrenData[line] is MULTILINE_END
@multilineChildrenData[line] = MULTILINE_END_START
else
@multilineChildrenData[line] = MULTILINE_START
@multilineChildrenData[i] = MULTILINE_MIDDLE for i in [line + 1...line + childLength - 1]
@multilineChildrenData[line + childLength - 1] = MULTILINE_END
# Advance our line counter
# by however long the child was
# (i.e. however many newlines
# we skipped).
line += childLength - 1
# Set @lineLength to reflect
# what we just found out.
@lineLength = line + 1
# If we have changed in line length,
# there has obviously been a bounding box change.
# The bounding box pass as it stands only deals
# with lines it knows exists, so we need to chop off
# the end of the array.
if @bounds.length isnt @lineLength
@changedBoundingBox = true
@bounds = @bounds[...@lineLength]
# Fill in gaps in @multilineChildrenData with NO_MULTILINE
@multilineChildrenData[i] ?= NO_MULTILINE for i in [0...@lineLength]
if @lineLength > 1
@topLineSticksToBottom = true
@bottomLineSticksToTop = true
return @lineLength
# ## computeDimensions (ListViewNode)
# Compute the size of our bounding box on each line.
computeMinDimensions: ->
# If we can, use cached data.
if @computedVersion is @model.version
return null
# start at zero min dimensions
super
# Lines immediately after the end of Indents
# have to be extended to a minimum width.
# Record the lines that need to be extended here.
linesToExtend = []
preIndentLines = []
# Recurse on our children, updating
# our dimensions as we go to contain them.
for childObject in @children
# Ask the child to compute dimensions
childNode = @view.getViewNodeFor(childObject.child)
childNode.computeMinDimensions()
minDimensions = childNode.minDimensions
minDistanceToBase = childNode.minDistanceToBase
# Horizontal margins get added to every line.
for size, line in minDimensions
desiredLine = line + childObject.startLine
margins = childNode.getMargins line
# Unless we are in the middle of an indent,
# add padding on the right of the child.
#
# Exception: Children with invisible bounding boxes
# should remain invisible. This matters
# mainly for indents starting at the end of a line.
@minDimensions[desiredLine].width += size.width +
margins.left +
margins.right
# Compute max distance above and below text
#
# Exception: do not add the bottom padding on an
# Indent if we own the next line as well.
if childObject.child.type is 'indent' and
line is minDimensions.length - 1 and
desiredLine < @lineLength - 1
bottomMargin = 0
linesToExtend.push desiredLine + 1
else if childObject.child.type is 'indent' and
line is 0
preIndentLines.push desiredLine
bottomMargin = margins.bottom
else
bottomMargin = margins.bottom
@minDistanceToBase[desiredLine].above = Math.max(
@minDistanceToBase[desiredLine].above,
minDistanceToBase[line].above + margins.top)
@minDistanceToBase[desiredLine].below = Math.max(
@minDistanceToBase[desiredLine].below,
minDistanceToBase[line].below + Math.max(bottomMargin, (
if @model.buttons? and @model.buttons.length > 0 and
desiredLine is @lineLength - 1 and
@multilineChildrenData[line] is MULTILINE_END and
@lineChildren[line].length is 1
@view.opts.buttonVertPadding + @view.opts.buttonHeight
else
0
)))
# Height is just the sum of the above-base and below-base counts.
# Empty lines should have some height.
for minDimension, line in @minDimensions
if @lineChildren[line].length is 0
# Socket should be shorter than other blocks
if @model.type is 'socket'
@minDistanceToBase[line].above = @view.opts.textHeight + @view.opts.textPadding
@minDistanceToBase[line].below = @view.opts.textPadding
# Text should not claim any padding
else if @model.type is 'text'
@minDistanceToBase[line].above = @view.opts.textHeight
@minDistanceToBase[line].below = 0
# The first line of an indent is often empty; this is the desired behavior
else if @model.type is 'indent' and line is 0
@minDistanceToBase[line].above = 0
@minDistanceToBase[line].below = 0
# Empty blocks should be the height of lines with text
else
@minDistanceToBase[line].above = @view.opts.textHeight + @view.opts.padding
@minDistanceToBase[line].below = @view.opts.padding
minDimension.height =
@minDistanceToBase[line].above +
@minDistanceToBase[line].below
# Make space for mutation buttons. In lockedSocket,
# these will go on the left; otherwise they will go on the right.
@extraLeft = 0
@extraWidth = 0
if @model.type in ['block', 'buttonContainer']
if @model.buttons? then for {key} in @model.buttons
@extraWidth += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
@minDimensions[@minDimensions.length - 1].width += @extraWidth
if @model.type is 'lockedSocket'
if @model.buttons? then for {key} in @model.buttons
@extraLeft += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
@minDimensions[@minDimensions.length - 1].width += @extraLeft
# Go through and adjust the width of rectangles
# immediately after the end of an indent to
# be as long as necessary
for line in linesToExtend
@minDimensions[line].width = Math.max(
@minDimensions[line].width, Math.max(
@view.opts.minIndentTongueWidth,
@view.opts.indentWidth + @view.opts.tabWidth + @view.opts.tabOffset + @view.opts.bevelClip
))
for line in preIndentLines
@minDimensions[line].width = Math.max(
@minDimensions[line].width, Math.max(
@view.opts.minIndentTongueWidth,
@view.opts.indentWidth + @view.opts.tabWidth + @view.opts.tabOffset + @view.opts.bevelClip
))
# Add space for carriage arrow
for lineChild in @lineChildren[@lineLength - 1]
lineChildView = @view.getViewNodeFor lineChild.child
if lineChildView.carriageArrow isnt CARRIAGE_ARROW_NONE
@minDistanceToBase[@lineLength - 1].below += @view.opts.padding
@minDimensions[@lineLength - 1].height =
@minDistanceToBase[@lineLength - 1].above +
@minDistanceToBase[@lineLength - 1].below
break
return null
# ## computeBoundingBoxX (ListViewNode)
# Layout bounding box positions horizontally.
# This needs to be separate from y-coordinate computation
# because of glue spacing (the space between lines
# that keeps weird-shaped blocks continuous), which
# can shift y-coordinates around.
computeBoundingBoxX: (left, line, offset = 0) ->
# Use cached data if possible
if @computedVersion is @model.version and
left is @bounds[line]?.x and not @changedBoundingBox
return @bounds[line]
offset += @extraLeft
# If the bounding box we're being asked
# to layout is exactly the same,
# avoid setting `@changedBoundingBox`
# for performance reasons (also, trivially,
# avoid changing bounding box coords).
unless @bounds[line]?.x is left and
@bounds[line]?.width is @dimensions[line].width
# Assign our own bounding box given
# this center-left coordinate
if @bounds[line]?
@bounds[line].x = left
@bounds[line].width = @dimensions[line].width
else
@bounds[line] = new @view.draw.Rectangle(
left, 0
@dimensions[line].width, 0
)
@changedBoundingBox = true
# Now recurse. We will keep track
# of a "cursor" as we go along,
# placing children down and
# adding padding and sizes
# to make them not overlap.
childLeft = left + offset
# Get rendering info on each of these children
for lineChild, i in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
childMargins = childView.getMargins childLine
childLeft += childMargins.left
childView.computeBoundingBoxX childLeft, childLine
childLeft +=
childView.dimensions[childLine].width + childMargins.right
# Return the bounds we just
# computed.
return @bounds[line]
# ## computeBoundingBoxY
# Layout a line vertically.
computeBoundingBoxY: (top, line) ->
# Use our cache if possible.
if @computedVersion is @model.version and
top is @bounds[line]?.y and not @changedBoundingBox
return @bounds[line]
# Avoid setting `@changedBoundingBox` if our
# bounding box has not actually changed,
# for performance reasons. (Still need to
# recurse, in case children have changed
# but not us)
unless @bounds[line]?.y is top and
@bounds[line]?.height is @dimensions[line].height
# Assign our own bounding box given
# this center-left coordinate
@bounds[line].y = top
@bounds[line].height = @dimensions[line].height
@changedBoundingBox = true
# Go to each child and lay them out so that their distanceToBase
# lines up.
above = @distanceToBase[line].above
for lineChild, i in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
childAbove = childView.distanceToBase[childLine].above
childView.computeBoundingBoxY top + above - childAbove, childLine
# Return the bounds we just computed.
return @bounds[line]
# ## layout
# Run all of these layout steps in order.
#
# Takes two arguments, which can be changed
# to translate the entire document from the upper-left corner.
layout: (left = @lastCoordinate.x, top = @lastCoordinate.y) ->
@view.registerRoot @model
@lastCoordinate = new @view.draw.Point left, top
@computeChildren()
@computeCarriageArrow true
@computeMargins()
@computeBevels()
@computeMinDimensions()
@computeDimensions 0, true
@computeAllBoundingBoxX left
@computeGlue()
@computeAllBoundingBoxY top
@computePath()
@computeDropAreas()
changedBoundingBox = @changedBoundingBox
@computeNewVersionNumber()
return changedBoundingBox
# ## absorbCache
# A hacky thing to get a view node of a new List
# to acquire all the properties of its children
# TODO re-examine
absorbCache: ->
@view.registerRoot @model
@computeChildren()
@computeCarriageArrow true
@computeMargins()
@computeBevels()
@computeMinDimensions()
# Replacement for computeDimensions
for size, line in @minDimensions
@distanceToBase[line] = {
above: @lineChildren[line].map((child) => @view.getViewNodeFor(child.child).distanceToBase[line - child.startLine].above).reduce((a, b) -> Math.max(a, b))
below: @lineChildren[line].map((child) => @view.getViewNodeFor(child.child).distanceToBase[line - child.startLine].below).reduce((a, b) -> Math.max(a, b))
}
@dimensions[line] = new draw.Size @minDimensions[line].width, @minDimensions[line].height
#@computeDimensions false, true
# Replacement for computeAllBoundingBoxX
for size, line in @dimensions
child = @lineChildren[line][0]
childView = @view.getViewNodeFor child.child
left = childView.bounds[line - child.startLine].x
@computeBoundingBoxX left, line
@computeGlue()
# Replacement for computeAllBoundingBoxY
for size, line in @dimensions
child = @lineChildren[line][0]
childView = @view.getViewNodeFor child.child
oldY = childView.bounds[line - child.startLine].y
top = childView.bounds[line - child.startLine].y +
childView.distanceToBase[line - child.startLine].above -
@distanceToBase[line].above
@computeBoundingBoxY top, line
@computePath()
@computeDropAreas()
return true
# ## computeGlue
# Compute the necessary glue spacing between lines.
#
# If a block has disconnected blocks, e.g.
# ```
# someLongFunctionName '''hello
# world'''
# ```
#
# it requires glue spacing. Then, any surrounding blocks
# must add their padding to that glue spacing, until we
# reach an Indent, at which point we can stop.
#
# Parents outside the indent must stil know that there is
# a space between these line, but they wil not have
# to colour in that space. This will be flaged
# by the `draw` flag on the glue objects.
computeGlue: ->
# Use our cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
# Immediately recurse, as we will
# need to know child glue info in order
# to compute our own (adding padding, etc.).
for childObj in @children
@view.getViewNodeFor(childObj.child).computeGlue()
@glue = {}
# Go through every pair of adjacent bounding boxes
# to see if they overlap or not
for box, line in @bounds when line < @bounds.length - 1
@glue[line] = {
type: 'normal'
height: 0
draw: false
}
# We will always have glue spacing at least as big
# as the biggest child's glue spacing.
for lineChild in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
if childLine of childView.glue
# Either add padding or not, depending
# on whether there is an indent between us.
@glue[line].height = Math.max @glue[line].height, childView.glue[childLine].height
if childView.carriageArrow isnt CARRIAGE_ARROW_NONE
@glue[line].height = Math.max @glue[line].height, @view.opts.padding
# Return the glue we just computed.
return @glue
# # ContainerViewNode
# Class from which `socketView`, `indentView`, `blockView`, and `documentView` extend.
# Contains function for dealing with multiple children, making polygons to wrap
# multiple lines, etc.
class ContainerViewNode extends ListViewNode
constructor: (@model, @view) ->
super
# *Sixth pass variables*
# computePath
@group = @view.draw.group('droplet-container-group')
if @model.type is 'block'
@path = @view.draw.path([], true, {
cssClass: 'droplet-block-path'
})
else
@path = @view.draw.path([], false, {
cssClass: "droplet-#{@model.type}-path"
})
@totalBounds = new @view.draw.NoRectangle()
@path.setParent @group
# *Seventh pass variables*
# computeDropAreas
# each one is a @view.draw.Path (or null)
@dropPoint = null
@highlightArea = @view.draw.path([], false, {
fillColor: '#FF0'
strokeColor: '#FF0'
lineWidth: 1
})
@highlightArea.deactivate()
@buttonGroups = {}
@buttonTexts = {}
@buttonPaths = {}
@buttonRects = {}
if @model.buttons? then for {key, glyph} in @model.buttons
@buttonGroups[key] = @view.draw.group()
@buttonPaths[key] = @view.draw.path([
new @view.draw.Point 0, 0
new @view.draw.Point @view.opts.buttonWidth, 0
new @view.draw.Point @view.opts.buttonWidth, @view.opts.buttonHeight
new @view.draw.Point 0, @view.opts.buttonHeight
], false, {
fillColor: 'none'
cssClass: 'droplet-button-path'
})
###
new @view.draw.Point 0, @view.opts.bevelClip
new @view.draw.Point @view.opts.bevelClip, 0
new @view.draw.Point @view.opts.buttonWidth - @view.opts.bevelClip, 0
new @view.draw.Point @view.opts.buttonWidth, @view.opts.bevelClip
new @view.draw.Point @view.opts.buttonWidth, @view.opts.buttonHeight - @view.opts.bevelClip
new @view.draw.Point @view.opts.buttonWidth - @view.opts.bevelClip, @view.opts.buttonHeight
new @view.draw.Point @view.opts.bevelClip, @view.opts.buttonHeight
new @view.draw.Point 0, @view.opts.buttonHeight - @view.opts.bevelClip
###
@buttonGroups[key].style = {}
@buttonTexts[key] = @view.draw.text(new @view.draw.Point(
(@view.opts.buttonWidth - @view.draw.measureCtx.measureText(glyph).width)/ 2,
(@view.opts.buttonHeight - @view.opts.textHeight) / 2
), glyph, if @view.opts.invert then BUTTON_GLYPH_INVERT_COLOR else BUTTON_GLYPH_COLOR)
@buttonPaths[key].setParent @buttonGroups[key]
@buttonTexts[key].setParent @buttonGroups[key]
@buttonGroups[key].setParent @group
@elements.push @buttonGroups[key]
@activeElements.push @buttonPaths[key]
@activeElements.push @buttonTexts[key]
@activeElements.push @buttonGroups[key]
@elements.push @group
@elements.push @path
@elements.push @highlightArea
destroy: (root = true) ->
if root
for element in @elements
element?.destroy?()
else if @highlightArea?
@highlightArea.destroy()
for child in @children
@view.getViewNodeFor(child.child).destroy(false)
root: ->
@group.setParent @view.draw.ctx
# ## draw (GenericViewNode)
# Call `drawSelf` and recurse, if we are in the viewport.
draw: (boundingRect, style = {}, parent = null) ->
if not boundingRect? or @totalBounds.overlap boundingRect
@drawSelf style, parent
@group.activate(); @path.activate()
for element in @activeElements
element.activate()
if @highlightArea?
@highlightArea.setParent @view.draw.ctx
if parent?
@group.setParent parent
for childObj in @children
@view.getViewNodeFor(childObj.child).draw boundingRect, style, @group
else
@group.destroy()
if @highlightArea?
@highlightArea.destroy()
computeCarriageArrow: (root = false) ->
oldCarriageArrow = @carriageArrow
@carriageArrow = CARRIAGE_ARROW_NONE
parent = @model.parent
if (not root) and parent?.type is 'indent' and @view.hasViewNodeFor(parent) and
@view.getViewNodeFor(parent).lineLength > 1 and
@lineLength is 1
head = @model.start
until head is parent.start or head.type is 'newline'
head = head.prev
if head is parent.start
if @model.isLastOnLine()
@carriageArrow = CARRIAGE_ARROW_INDENT
else
@carriageArrow = CARRIAGE_GROW_DOWN
else unless @model.isFirstOnLine()
@carriageArrow = CARRIAGE_ARROW_SIDEALONG
if @carriageArrow isnt oldCarriageArrow
@changedBoundingBox = true
if @computedVersion is @model.version and
(not @model.parent? or not @view.hasViewNodeFor(@model.parent) or
@model.parent.version is @view.getViewNodeFor(@model.parent).computedVersion)
return null
super
computeGlue: ->
# Use our cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
super
for box, line in @bounds when line < @bounds.length - 1
# Additionally, we add glue spacing padding if we are disconnected
# from the bounding box on the next line.
unless @multilineChildrenData[line] is MULTILINE_MIDDLE
# Find the horizontal overlap between these two bounding rectangles,
# which is our right edge minus their left, or vice versa.
overlap = Math.min @bounds[line].right() - @bounds[line + 1].x, @bounds[line + 1].right() - @bounds[line].x
# If we are starting an indent, then our "bounding box"
# on the next line is not actually how we will be visualized;
# instead, we must connect to the small rectangle
# on the left of a C-shaped indent thing. So,
# compute overlap with that as well.
if @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
overlap = Math.min overlap, @bounds[line + 1].x + @view.opts.indentWidth - @bounds[line].x
# If the overlap is too small, demand glue.
if overlap < @view.opts.padding and @model.type isnt 'indent'
@glue[line].height += @view.opts.padding
@glue[line].draw = true
return @glue
computeBevels: ->
oldBevels = @bevels
@bevels =
top: true
bottom: true
if (@model.parent?.type in ['indent', 'document']) and
@model.start.prev?.type is 'newline' and
@model.start.prev?.prev isnt @model.parent.start
@bevels.top = false
if (@model.parent?.type in ['indent', 'document']) and
@model.end.next?.type is 'newline'
@bevels.bottom = false
unless oldBevels.top is @bevels.top and
oldBevels.bottom is @bevels.bottom
@changedBoundingBox = true
if @computedVersion is @model.version
return null
super
# ## computeOwnPath
# Using bounding box data, compute the polygon
# that represents us. This contains a lot of special cases
# for glue and multiline starts and ends.
computeOwnPath: ->
# There are four kinds of line,
# for the purposes of computing the path.
#
# 1. Normal block line; we surround the bounding rectangle.
# 2. Beginning of a multiline block. Avoid that block on the right and bottom.
# 3. Middle of a multiline block. We avoid to the left side
# 4. End of a multiline block. We make a G-shape if necessary. If it is an Indent,
# this will leave a thick tongue due to things done in dimension
# computation.
# We will keep track of two sets of coordinates,
# the left side of the polygon and the right side.
#
# At the end, we will reverse `left` and concatenate these
# so as to create a counterclockwise path.
left = []
right = []
# If necessary, add tab
# at the top.
if @shouldAddTab() and @model.isFirstOnLine() and
@carriageArrow isnt CARRIAGE_ARROW_SIDEALONG
@addTabReverse right, new @view.draw.Point @bounds[0].x + @view.opts.tabOffset, @bounds[0].y
for bounds, line in @bounds
# Case 1. Normal rendering.
if @multilineChildrenData[line] is NO_MULTILINE
# Draw the left edge of the bounding box.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Draw the right edge of the bounding box.
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# Case 2. Start of a multiline block.
if @multilineChildrenData[line] is MULTILINE_START
# Draw the left edge of the bounding box.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Find the multiline child that's starting on this line,
# so that we can know its bounds
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineView = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineView.bounds[line - multilineChild.startLine]
# If the multiline child here is invisible,
# draw the line just normally.
if multilineBounds.width is 0
right.push new @view.draw.Point bounds.right(), bounds.y
# Otherwise, avoid the block by tracing out its
# top and left edges, then going to our bound's bottom.
else
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), multilineBounds.y
if multilineChild.child.type is 'indent'
@addTab right, new @view.draw.Point multilineBounds.x + @view.opts.tabOffset, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
# Case 3. Middle of an indent.
if @multilineChildrenData[line] is MULTILINE_MIDDLE
multilineChild = @lineChildren[line][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[line - multilineChild.startLine]
# Draw the left edge normally.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Draw the right edge straight down,
# exactly to the left of the multiline child.
unless @multilineChildrenData[line - 1] in [MULTILINE_START, MULTILINE_END_START] and
multilineChild.child.type is 'indent'
right.push new @view.draw.Point multilineBounds.x, bounds.y
right.push new @view.draw.Point multilineBounds.x, bounds.bottom()
# Case 4. End of an indent.
if @multilineChildrenData[line] in [MULTILINE_END, MULTILINE_END_START]
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Find the child that is the indent
multilineChild = @lineChildren[line][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[line - multilineChild.startLine]
# Avoid the indented area
unless @multilineChildrenData[line - 1] in [MULTILINE_START, MULTILINE_END_START] and
multilineChild.child.type is 'indent'
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
if multilineChild.child.type is 'indent'
@addTabReverse right, new @view.draw.Point multilineBounds.x + @view.opts.tabOffset, multilineBounds.bottom()
right.push new @view.draw.Point multilineBounds.right(), multilineBounds.bottom()
# If we must, make the "G"-shape
if @lineChildren[line].length > 1
right.push new @view.draw.Point multilineBounds.right(), multilineBounds.y
if @multilineChildrenData[line] is MULTILINE_END
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
else
# Find the multiline child that's starting on this line,
# so that we can know its bounds
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineView = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineView.bounds[line - multilineChild.startLine]
# Draw the upper-right corner
right.push new @view.draw.Point bounds.right(), bounds.y
# If the multiline child here is invisible,
# draw the line just normally.
if multilineBounds.width is 0
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# Otherwise, avoid the block by tracing out its
# top and left edges, then going to our bound's bottom.
else
right.push new @view.draw.Point bounds.right(), multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
# Otherwise, don't.
else
right.push new @view.draw.Point bounds.right(), multilineBounds.bottom()
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# "Glue" phase
# Here we use our glue spacing data
# to draw glue, if necessary.
#
# If we are being told to draw some glue here,
# do so.
if line < @lineLength - 1 and line of @glue and @glue[line].draw
# Extract information from the glue spacing
# and bounding box data combined.
#
# `glueTop` will be the top of the "glue" box.
# `leftmost` and `rightmost` are the leftmost
# and rightmost extremes of this and the next line's
# bounding boxes.
glueTop = @bounds[line + 1].y - @glue[line].height
leftmost = Math.min @bounds[line + 1].x, @bounds[line].x
rightmost = Math.max @bounds[line + 1].right(), @bounds[line].right()
# Bring the left down to the glue top line, then down to the
# level of the next line's bounding box. This prepares
# it to go straight horizontally over
# to the top of the next bounding box,
# once the loop reaches that point.
left.push new @view.draw.Point @bounds[line].x, glueTop
left.push new @view.draw.Point leftmost, glueTop
left.push new @view.draw.Point leftmost, glueTop + @view.opts.padding
# Do the same for the right side, unless we can't
# because we're avoiding intersections with a multiline child that's
# in the way.
unless @multilineChildrenData[line] is MULTILINE_START
right.push new @view.draw.Point @bounds[line].right(), glueTop
right.push new @view.draw.Point rightmost, glueTop
right.push new @view.draw.Point rightmost, glueTop + @view.opts.padding
# Otherwise, bring us gracefully to the next line
# without lots of glue (minimize the extra colour).
else if @bounds[line + 1]? and @multilineChildrenData[line] isnt MULTILINE_MIDDLE
# Instead of outward extremes, we take inner extremes this time,
# to minimize extra colour between lines.
innerLeft = Math.max @bounds[line + 1].x, @bounds[line].x
innerRight = Math.min @bounds[line + 1].right(), @bounds[line].right()
# Drop down to the next line on the left, minimizing extra colour
left.push new @view.draw.Point innerLeft, @bounds[line].bottom()
left.push new @view.draw.Point innerLeft, @bounds[line + 1].y
# Do the same on the right, unless we need to avoid
# a multiline block that's starting here.
unless @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
right.push new @view.draw.Point innerRight, @bounds[line].bottom()
right.push new @view.draw.Point innerRight, @bounds[line + 1].y
else if @carriageArrow is CARRIAGE_GROW_DOWN
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point @bounds[line].x, destinationBounds.y - @view.opts.padding
else if @carriageArrow is CARRIAGE_ARROW_INDENT
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.y
right.push new @view.draw.Point destinationBounds.x + @view.opts.tabOffset + @view.opts.tabWidth, destinationBounds.y
left.push new @view.draw.Point @bounds[line].x, destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point destinationBounds.x, destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point destinationBounds.x, destinationBounds.y
@addTab right, new @view.draw.Point destinationBounds.x + @view.opts.tabOffset, destinationBounds.y
else if @carriageArrow is CARRIAGE_ARROW_SIDEALONG and @model.isLastOnLine()
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[@model.getLinesToParent()]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.bottom() + @view.opts.padding
right.push new @view.draw.Point destinationBounds.x + @view.opts.tabOffset + @view.opts.tabWidth,
destinationBounds.bottom() + @view.opts.padding
left.push new @view.draw.Point @bounds[line].x, destinationBounds.bottom()
left.push new @view.draw.Point destinationBounds.x, destinationBounds.bottom()
left.push new @view.draw.Point destinationBounds.x, destinationBounds.bottom() + @view.opts.padding
@addTab right, new @view.draw.Point destinationBounds.x + @view.opts.tabOffset,
destinationBounds.bottom() + @view.opts.padding
# If we're avoiding intersections with a multiline child in the way,
# bring us gracefully to the next line's top. We had to keep avoiding
# using bounding box right-edge data earlier, because it would have overlapped;
# instead, we want to use the left edge of the multiline block that's
# starting here.
if @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineNode = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineNode.bounds[line - multilineChild.startLine]
if @glue[line]?.draw
glueTop = @bounds[line + 1].y - @glue[line].height + @view.opts.padding
else
glueTop = @bounds[line].bottom()
# Special case for indents that start with newlines;
# don't do any of the same-line-start multiline stuff.
if multilineChild.child.type is 'indent' and multilineChild.child.start.next.type is 'newline'
right.push new @view.draw.Point @bounds[line].right(), glueTop
@addTab right, new @view.draw.Point(@bounds[line + 1].x +
@view.opts.indentWidth +
@extraLeft +
@view.opts.tabOffset, glueTop), true
else
right.push new @view.draw.Point multilineBounds.x, glueTop
unless glueTop is @bounds[line + 1].y
right.push new @view.draw.Point multilineNode.bounds[line - multilineChild.startLine + 1].x, glueTop
right.push new @view.draw.Point multilineNode.bounds[line - multilineChild.startLine + 1].x, @bounds[line + 1].y
# If necessary, add tab
# at the bottom.
if @shouldAddTab() and @model.isLastOnLine() and
@carriageArrow is CARRIAGE_ARROW_NONE
@addTab right, new @view.draw.Point @bounds[@lineLength - 1].x + @view.opts.tabOffset,
@bounds[@lineLength - 1].bottom()
topLeftPoint = left[0]
# Reverse the left and concatenate it with the right
# to make a counterclockwise path
path = dedupe left.reverse().concat right
newPath = []
for point, i in path
if i is 0 and not @bevels.bottom
newPath.push point
continue
if (not @bevels.top) and point.almostEquals(topLeftPoint)
newPath.push point
continue
next = path[(i + 1) %% path.length]
prev = path[(i - 1) %% path.length]
if (point.x is next.x) isnt (point.y is next.y) and
(point.x is prev.x) isnt (point.y is prev.y) and
point.from(prev).magnitude() >= @view.opts.bevelClip * 2 and
point.from(next).magnitude() >= @view.opts.bevelClip * 2
newPath.push point.plus(point.from(prev).toMagnitude(-@view.opts.bevelClip))
newPath.push point.plus(point.from(next).toMagnitude(-@view.opts.bevelClip))
else
newPath.push point
# Make a Path object out of these points
@path.setPoints newPath
if @model.type is 'block'
@path.style.fillColor = @view.getColor @model
if @model.buttons? and @model.type is 'lockedSocket'
# Add the add button if necessary
firstRect = @bounds[0]
start = firstRect.x
top = firstRect.y + firstRect.height / 2 - @view.opts.buttonHeight / 2
for {key} in @model.buttons
@buttonGroups[key].style.transform = "translate(#{start}, #{top})"
@buttonGroups[key].update()
@buttonPaths[key].update()
@buttonRects[key] = new @view.draw.Rectangle start, top, @view.opts.buttonWidth, @view.opts.buttonHeight
@elements.push @buttonPaths[key]
start += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
else if @model.buttons?
# Add the add button if necessary
lastLine = @bounds.length - 1
lastRect = @bounds[lastLine]
if @model.type is 'block'
start = lastRect.x + lastRect.width - @extraWidth - @view.opts.buttonHorizPadding
else
start = lastRect.x + lastRect.width - @extraWidth + @view.opts.buttonHorizPadding
top = lastRect.y + lastRect.height / 2 - @view.opts.buttonHeight / 2
for {key} in @model.buttons
# Cases when last line is MULTILINE
if @multilineChildrenData[lastLine] is MULTILINE_END
multilineChild = @lineChildren[lastLine][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[lastLine - multilineChild.startLine]
# If it is a G-Shape
if @lineChildren[lastLine].length > 1
height = multilineBounds.bottom() - lastRect.y
top = lastRect.y + height / 2 - @view.opts.buttonHeight/2
else
height = lastRect.bottom() - multilineBounds.bottom()
top = multilineBounds.bottom() + height/2 - @view.opts.buttonHeight/2
@buttonGroups[key].style.transform = "translate(#{start}, #{top})"
@buttonGroups[key].update()
@buttonPaths[key].update()
@buttonRects[key] = new @view.draw.Rectangle start, top, @view.opts.buttonWidth, @view.opts.buttonHeight
@elements.push @buttonPaths[key]
start += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
# Return it.
return @path
# ## addTab
# Add the tab graphic to a path in a given location.
addTab: (array, point) ->
# Rightmost point of the tab, where it begins to dip down.
array.push new @view.draw.Point(point.x + @view.opts.tabWidth,
point.y)
# Dip down.
array.push new @view.draw.Point point.x + @view.opts.tabWidth * (1 - @view.opts.tabSideWidth),
point.y + @view.opts.tabHeight
# Bottom plateau.
array.push new @view.draw.Point point.x + @view.opts.tabWidth * @view.opts.tabSideWidth,
point.y + @view.opts.tabHeight
# Rise back up.
array.push new @view.draw.Point point.x, point.y
# Move over to the given corner itself.
array.push point
# ## addTabReverse
# Add the tab in reverse order
addTabReverse: (array, point) ->
array.push point
array.push new @view.draw.Point point.x, point.y
array.push new @view.draw.Point point.x + @view.opts.tabWidth * @view.opts.tabSideWidth,
point.y + @view.opts.tabHeight
array.push new @view.draw.Point point.x + @view.opts.tabWidth * (1 - @view.opts.tabSideWidth),
point.y + @view.opts.tabHeight
array.push new @view.draw.Point(point.x + @view.opts.tabWidth,
point.y)
mark: (style) ->
@view.registerMark @model.id
@markStyle = style
@focusAll()
unmark: -> @markStyle = null
# ## drawSelf
# Draw our path, with applied
# styles if necessary.
drawSelf: (style = {}) ->
# We might want to apply some
# temporary color changes,
# so store the old colors
oldFill = @path.style.fillColor
oldStroke = @path.style.strokeColor
if style.grayscale
# Change path color
if @path.style.fillColor isnt 'none'
@path.style.fillColor = avgColor @path.style.fillColor, 0.5, '#888'
if @path.style.strokeColor isnt 'none'
@path.style.strokeColor = avgColor @path.style.strokeColor, 0.5, '#888'
if style.selected
# Change path color
if @path.style.fillColor isnt 'none'
@path.style.fillColor = avgColor @path.style.fillColor, 0.7, '#00F'
if @path.style.strokeColor isnt 'none'
@path.style.strokeColor = avgColor @path.style.strokeColor, 0.7, '#00F'
@path.setMarkStyle @markStyle
@path.update()
if @model.buttons? then for {key} in @model.buttons
@buttonPaths[key].update()
@buttonGroups[key].update()
for element in [@buttonPaths[key], @buttonGroups[key], @buttonTexts[key]]
unless element in @activeElements # TODO unlikely but might be performance chokehold?
@activeElements.push element # Possibly replace activeElements with a more set-like structure.
# Unset all the things we changed
@path.style.fillColor = oldFill
@path.style.strokeColor = oldStroke
if @model.buttons? then for {key} in @model.buttons
if @buttonPaths[key].active
@buttonPaths[key].style.fillColor = oldFill
@buttonPaths[key].style.strokeColor = oldStroke
return null
# ## computeOwnDropArea
# By default, we will not have a
# drop area (not be droppable).
computeOwnDropArea: ->
@dropPoint = null
if @highlightArea?
@elements = @elements.filter (x) -> x isnt @highlightArea
@highlightArea.destroy()
@highlightArea = null
# ## shouldAddTab
# By default, we will ask
# not to have a tab.
shouldAddTab: NO
# # BlockViewNode
class BlockViewNode extends ContainerViewNode
constructor: ->
super
computeMinDimensions: ->
if @computedVersion is @model.version
return null
super
# Blocks have a shape including a lego nubby "tab", and so
# they need to be at least wide enough for tabWidth+tabOffset.
for size, i in @minDimensions
size.width = Math.max size.width,
@view.opts.tabWidth + @view.opts.tabOffset
size.width += @extraLeft
return null
shouldAddTab: ->
if @model.parent? and @view.hasViewNodeFor(@model.parent) and not
(@model.parent.type is 'document' and @model.parent.opts.roundedSingletons and
@model.start.prev is @model.parent.start and @model.end.next is @model.parent.end)
return @model.parent?.type isnt 'socket'
else
return not (@model.shape in [helper.MOSTLY_VALUE, helper.VALUE_ONLY])
computeOwnDropArea: ->
unless @model.parent?.type in ['indent', 'document']
@dropPoint = null
return
# Our drop area is a puzzle-piece shaped path
# of height opts.highlightAreaHeight and width
# equal to our last line width,
# positioned at the bottom of our last line.
if @carriageArrow is CARRIAGE_ARROW_INDENT
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
@dropPoint = new @view.draw.Point destinationBounds.x, destinationBounds.y
lastBoundsLeft = destinationBounds.x
lastBoundsRight = destinationBounds.right()
else if @carriageArrow is CARRIAGE_ARROW_SIDEALONG
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
@dropPoint = new @view.draw.Point destinationBounds.x,
@bounds[@lineLength - 1].bottom() + @view.opts.padding
lastBoundsLeft = destinationBounds.x
lastBoundsRight = @bounds[@lineLength - 1].right()
else
@dropPoint = new @view.draw.Point @bounds[@lineLength - 1].x, @bounds[@lineLength - 1].bottom()
lastBoundsLeft = @bounds[@lineLength - 1].x
lastBoundsRight = @bounds[@lineLength - 1].right()
# Our highlight area is the a rectangle in the same place,
# with a height that can be given by a different option.
highlightAreaPoints = []
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft, @dropPoint.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft + @view.opts.bevelClip, @dropPoint.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBoundsLeft + @view.opts.tabOffset, @dropPoint.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsRight - @view.opts.bevelClip, @dropPoint.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsRight, @dropPoint.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsRight, @dropPoint.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsRight - @view.opts.bevelClip, @dropPoint.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBoundsLeft + @view.opts.tabOffset, @dropPoint.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft + @view.opts.bevelClip, @dropPoint.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft, @dropPoint.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
# # SocketViewNode
class SocketViewNode extends ContainerViewNode
constructor: ->
super
if @view.opts.showDropdowns and @model.dropdown?
@dropdownElement ?= @view.draw.path([], false, {
fillColor: (if @view.opts.invert then DROP_TRIANGLE_INVERT_COLOR else DROP_TRIANGLE_COLOR),
cssClass: 'droplet-dropdown-arrow'
})
@dropdownElement.deactivate()
@dropdownElement.setParent @group
@elements.push @dropdownElement
@activeElements.push @dropdownElement
shouldAddTab: NO
isInvisibleSocket: ->
'' is @model.emptyString and @model.start?.next is @model.end
# ## computeDimensions (SocketViewNode)
# Sockets have a couple exceptions to normal dimension computation.
#
# 1. Sockets have minimum dimensions even if empty.
# 2. Sockets containing blocks mimic the block exactly.
computeMinDimensions: ->
# Use cache if possible.
if @computedVersion is @model.version
return null
super
@minDistanceToBase[0].above = Math.max(@minDistanceToBase[0].above,
@view.opts.textHeight + @view.opts.textPadding)
@minDistanceToBase[0].below = Math.max(@minDistanceToBase[0].below,
@view.opts.textPadding)
@minDimensions[0].height =
@minDistanceToBase[0].above + @minDistanceToBase[0].below
for dimension in @minDimensions
dimension.width = Math.max(dimension.width,
if @isInvisibleSocket()
@view.opts.invisibleSocketWidth
else
@view.opts.minSocketWidth)
if @model.hasDropdown() and @view.opts.showDropdowns
dimension.width += helper.DROPDOWN_ARROW_WIDTH
return null
# ## computeBoundingBoxX (SocketViewNode)
computeBoundingBoxX: (left, line) ->
super left, line, (
if @model.hasDropdown() and @view.opts.showDropdowns
helper.DROPDOWN_ARROW_WIDTH
else 0
)
# ## computeGlue
# Sockets have one exception to normal glue spacing computation:
# sockets containing a block should **not** add padding to
# the glue.
computeGlue: ->
# Use cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
# Do not add padding to the glue
# if our child is a block.
if @model.start.next.type is 'blockStart'
view = @view.getViewNodeFor @model.start.next.container
@glue = view.computeGlue()
# Otherwise, decrement the glue version
# to force super to recompute,
# and call super.
else
super
# ## computeOwnPath (SocketViewNode)
# Again, exception: sockets containing block
# should mimic blocks exactly.
#
# Under normal circumstances this shouldn't
# actually be an issue, but if we decide
# to change the Block's path,
# the socket should not have stuff sticking out,
# and should hit-test properly.
computeOwnPath: ->
# Use cache if possible.
if @computedVersion is @model.version and
not @changedBoundingBox
return @path
@path.style.fillColor = if @view.opts.invert then '#333' else '#FFF'
if @model.start.next.type is 'blockStart'
@path.style.fillColor = 'none'
# Otherwise, call super.
else
super
# If the socket is empty, make it invisible except
# for mouseover
if '' is @model.emptyString and @model.start?.next is @model.end
@path.style.cssClass = 'droplet-socket-path droplet-empty-socket-path'
@path.style.fillColor = 'none'
else
@path.style.cssClass = 'droplet-socket-path'
return @path
# ## drawSelf (SocketViewNode)
drawSelf: (style = {}) ->
super
if @model.hasDropdown() and @view.opts.showDropdowns
@dropdownElement.setPoints([new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_PADDING,
@bounds[0].y + (@bounds[0].height - DROPDOWN_ARROW_HEIGHT) / 2),
new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_WIDTH - helper.DROPDOWN_ARROW_PADDING,
@bounds[0].y + (@bounds[0].height - DROPDOWN_ARROW_HEIGHT) / 2),
new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_WIDTH / 2,
@bounds[0].y + (@bounds[0].height + DROPDOWN_ARROW_HEIGHT) / 2)
])
@dropdownElement.update()
unless @dropdownElement in @activeElements
@activeElements.push @dropdownElement
else if @dropdownElement?
@activeElements = @activeElements.filter (x) -> x isnt @dropdownElement
@dropdownElement.deactivate()
# ## computeOwnDropArea (SocketViewNode)
# Socket drop areas are actually the same
# shape as the sockets themselves, which
# is different from most other
# things.
computeOwnDropArea: ->
if @model.start.next.type is 'blockStart'
@dropPoint = null
@highlightArea.deactivate()
else
@dropPoint = @bounds[0].upperLeftCorner()
@highlightArea.setPoints @path._points
@highlightArea.style.strokeColor = '#FF0'
@highlightArea.style.fillColor = 'none'
@highlightArea.style.lineWidth = @view.opts.highlightAreaHeight / 2
@highlightArea.update()
@highlightArea.deactivate()
# # IndentViewNode
class IndentViewNode extends ContainerViewNode
constructor: ->
super
@lastFirstChildren = []
@lastLastChildren = []
# ## computeOwnPath
# An Indent should also have no drawn
# or hit-tested path.
computeOwnPath: ->
# ## computeChildren
computeChildren: ->
super
unless arrayEq(@lineChildren[0], @lastFirstChildren) and
arrayEq(@lineChildren[@lineLength - 1], @lastLastChildren)
for childObj in @children
childView = @view.getViewNodeFor childObj.child
if childView.topLineSticksToBottom or childView.bottomLineSticksToTop
childView.invalidate = true
if childView.lineLength is 1
childView.topLineSticksToBottom =
childView.bottomLineSticksToTop = false
for childRef in @lineChildren[0]
childView = @view.getViewNodeFor(childRef.child)
unless childView.topLineSticksToBottom
childView.invalidate = true
childView.topLineSticksToBottom = true
for childRef in @lineChildren[@lineChildren.length - 1]
childView = @view.getViewNodeFor(childRef.child)
unless childView.bottomLineSticksToTop
childView.invalidate = true
childView.bottomLineSticksToTop = true
return @lineLength
# ## computeDimensions (IndentViewNode)
#
# Give width to any empty lines
# in the Indent.
computeMinDimensions: ->
super
for size, line in @minDimensions[1..] when size.width is 0
size.width = @view.opts.emptyLineWidth
# ## drawSelf
#
# Again, an Indent should draw nothing.
drawSelf: ->
# ## computeOwnDropArea
#
# Our drop area is a rectangle of
# height dropAreaHeight and a width
# equal to our first line width,
# positioned at the top of our firs tline
computeOwnDropArea: ->
lastBounds = new @view.draw.NoRectangle()
if @model.start.next.type is 'newline'
@dropPoint = @bounds[1].upperLeftCorner()
lastBounds.copy @bounds[1]
else
@dropPoint = @bounds[0].upperLeftCorner()
lastBounds.copy @bounds[0]
lastBounds.width = Math.max lastBounds.width, @view.opts.indentDropAreaMinWidth
# Our highlight area is the a rectangle in the same place,
# with a height that can be given by a different option.
highlightAreaPoints = []
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
# # DocumentViewNode
# Represents a Document. Draws little, but
# recurses.
class DocumentViewNode extends ContainerViewNode
constructor: -> super
# ## computeOwnPath
#
computeOwnPath: ->
# ## computeOwnDropArea
#
# Root documents
# can be dropped at their beginning.
computeOwnDropArea: ->
@dropPoint = @bounds[0].upperLeftCorner()
highlightAreaPoints = []
lastBounds = new @view.draw.NoRectangle()
lastBounds.copy @bounds[0]
lastBounds.width = Math.max lastBounds.width, @view.opts.indentDropAreaMinWidth
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
return null
# # TextViewNode
#
# TextViewNode does not extend ContainerViewNode.
# We contain a @view.draw.TextElement to measure
# bounding boxes and draw text.
class TextViewNode extends GenericViewNode
constructor: (@model, @view) ->
super
@textElement = @view.draw.text(
new @view.draw.Point(0, 0),
@model.value,
if @view.opts.invert then '#FFF' else '#000'
)
@textElement.destroy()
@elements.push @textElement
# ## computeChildren
#
# Text elements are one line
# and contain no children (and thus
# no multiline children, either)
computeChildren: ->
@multilineChildrenData = [NO_MULTILINE]
return @lineLength = 1
# ## computeMinDimensions (TextViewNode)
#
# Set our dimensions to the measured dimensinos
# of our text value.
computeMinDimensions: ->
if @computedVersion is @model.version
return null
@textElement.point = new @view.draw.Point 0, 0
@textElement.value = @model.value
height = @view.opts.textHeight
@minDimensions[0] = new @view.draw.Size(@textElement.bounds().width, height)
@minDistanceToBase[0] = {above: height, below: 0}
return null
# ## computeBoundingBox (x and y)
#
# Assign the position of our textElement
# to match our laid out bounding box position.
computeBoundingBoxX: (left, line) ->
@textElement.point.x = left; super
computeBoundingBoxY: (top, line) ->
@textElement.point.y = top; super
# ## drawSelf
#
# Draw the text element itself.
drawSelf: (style = {}, parent = null) ->
@textElement.update()
if style.noText
@textElement.deactivate()
else
@textElement.activate()
if parent?
@textElement.setParent parent
toRGB = (hex) ->
# Convert to 6-char hex if not already there
if hex.length is 4
hex = (c + c for c in hex).join('')[1..]
# Extract integers from hex
r = parseInt hex[1..2], 16
g = parseInt hex[3..4], 16
b = parseInt hex[5..6], 16
return [r, g, b]
zeroPad = (str, len) ->
if str.length < len
('0' for [str.length...len]).join('') + str
else
str
twoDigitHex = (n) -> zeroPad Math.round(n).toString(16), 2
toHex = (rgb) ->
return '#' + (twoDigitHex(k) for k in rgb).join ''
avgColor = (a, factor, b) ->
a = toRGB a
b = toRGB b
newRGB = (a[i] * factor + b[i] * (1 - factor) for k, i in a)
return toHex newRGB
dedupe = (path) ->
path = path.filter((x, i) ->
not x.equals(path[(i - 1) %% path.length])
)
path = path.filter((x, i) ->
not draw._collinear(path[(i - 1) %% path.length], x, path[(i + 1) %% path.length])
)
return path
| true | # Droplet editor view.
#
# Copyright (c) 2015 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# MIT License
helper = require './helper.coffee'
draw = require './draw.coffee'
model = require './model.coffee'
NO_MULTILINE = 0
MULTILINE_START = 1
MULTILINE_MIDDLE = 2
MULTILINE_END = 3
MULTILINE_END_START = 4
ANY_DROP = helper.ANY_DROP
BLOCK_ONLY = helper.BLOCK_ONLY
MOSTLY_BLOCK = helper.MOSTLY_BLOCK
MOSTLY_VALUE = helper.MOSTLY_VALUE
VALUE_ONLY = helper.VALUE_ONLY
CARRIAGE_ARROW_SIDEALONG = 0
CARRIAGE_ARROW_INDENT = 1
CARRIAGE_ARROW_NONE = 2
CARRIAGE_GROW_DOWN = 3
DROPDOWN_ARROW_HEIGHT = 8
DROP_TRIANGLE_COLOR = '#555'
DROP_TRIANGLE_INVERT_COLOR = '#CCC'
BUTTON_GLYPH_COLOR = 'rgba(0, 0, 0, 0.3)'
BUTTON_GLYPH_INVERT_COLOR = 'rgba(255, 255, 255, 0.5)'
SVG_STANDARD = helper.SVG_STANDARD
DEFAULT_OPTIONS =
buttonWidth: 15
lockedSocketButtonWidth: 15
buttonHeight: 15
extraLeft: 0
buttonVertPadding: 6
buttonHorizPadding: 3
minIndentTongueWidth: 150
showDropdowns: true
padding: 5
indentWidth: 20
indentTongueHeight: 20
tabOffset: 10
tabWidth: 15
tabHeight: 5
tabSideWidth: 0.125
dropAreaHeight: 20
indentDropAreaMinWidth: 50
minSocketWidth: 10
invisibleSocketWidth: 5
textHeight: 15
textPadding: 1
emptyLineWidth: 50
highlightAreaHeight: 10
bevelClip: 3
shadowBlur: 5
colors:
error: '#ff0000'
comment: '#c0c0c0' # gray
return: '#fff59d' # yellow
control: '#ffcc80' # orange
value: '#a5d6a7' # green
command: '#90caf9' # blue
red: '#ef9a9a'
pink: '#f48fb1'
purple: '#ce93d8'
deeppurple: '#b39ddb'
indigo: '#9fa8da'
blue: '#90caf9'
lightblue: '#81d4fa'
cyan: '#80deea'
teal: '#80cbc4'
green: '#a5d6a7'
lightgreen: '#c5e1a5'
darkgreen: '#008000'
lime: '#e6ee9c'
yellow: '#fff59d'
amber: '#ffe082'
orange: '#ffcc80'
deeporange: '#ffab91'
brown: '#bcaaa4'
grey: '#eeeeee'
bluegrey: '#b0bec5'
function: '#90caf9'
declaration: '#e6ee9c'
value: '#a5d6a7'
logic: '#ffab91'
assign: '#fff59d'
functionCall: '#90caf9'
control: '#ffab91'
YES = -> yes
NO = -> no
arrayEq = (a, b) ->
return false if a.length isnt b.length
return false if k isnt b[i] for k, i in a
return true
# # View
# The View class contains options and caches
# for rendering. The controller instantiates a View
# and interacts with things through it.
#
# Inner classes in the View correspond to Model
# types (e.g. SocketViewNode, etc.) all of which
# will have access to their View's caches
# and options object.
exports.View = class View
constructor: (@ctx, @opts = {}) ->
@ctx ?= document.createElementNS SVG_STANDARD, 'svg'
# @map maps Model objects
# to corresponding View objects,
# so that rerendering the same model
# can be fast
@map = {}
@oldRoots = {}
@newRoots = {}
@auxiliaryMap = {}
@flaggedToDelete = {}
@unflaggedToDelete = {}
@marks = {}
@draw = new draw.Draw(@ctx)
# Apply default options
for option of DEFAULT_OPTIONS
unless option of @opts
@opts[option] = DEFAULT_OPTIONS[option]
for color of DEFAULT_OPTIONS.colors
unless color of @opts.colors
@opts.colors[color] = DEFAULT_OPTIONS.colors[color]
if @opts.invert
@opts.colors['comment'] = '#606060'
# Simple method for clearing caches
clearCache: ->
for id of @map
@map[id].destroy()
@destroy id
# Remove everything from the canvas
clearFromCanvas: ->
@beginDraw()
@cleanupDraw()
# ## getViewNodeFor
# Given a model object,
# give the corresponding renderer object
# under this View. If one does not exist,
# create one, then preserve it in our map.
getViewNodeFor: (model) ->
if model.id of @map
return @map[model.id]
else
return @createView(model)
registerMark: (id) ->
@marks[id] = true
clearMarks: ->
for key, val of @marks
@map[key].unmark()
@marks = {}
beginDraw: ->
@newRoots = {}
hasViewNodeFor: (model) ->
model? and model.id of @map
getAuxiliaryNode: (node) ->
if node.id of @auxiliaryMap
return @auxiliaryMap[node.id]
else
return @auxiliaryMap[node.id] = new AuxiliaryViewNode(@, node)
registerRoot: (node) ->
if node instanceof model.List and not (
node instanceof model.Container)
node.traverseOneLevel (head) =>
unless head instanceof model.NewlineToken
@registerRoot head
return
for id, aux of @newRoots
if aux.model.hasParent(node)
delete @newRoots[id]
else if node.hasParent(aux.model)
return
@newRoots[node.id] = @getAuxiliaryNode(node)
cleanupDraw: ->
@flaggedToDelete = {}
@unflaggedToDelete = {}
for id, el of @oldRoots
unless id of @newRoots
@flag el
for id, el of @newRoots
el.cleanup()
for id, el of @flaggedToDelete when id of @unflaggedToDelete
delete @flaggedToDelete[id]
for id, el of @flaggedToDelete when id of @map
@map[id].hide()
@oldRoots = @newRoots
flag: (auxiliaryNode) ->
@flaggedToDelete[auxiliaryNode.model.id] = auxiliaryNode
unflag: (auxiliaryNode) ->
@unflaggedToDelete[auxiliaryNode.model.id] = auxiliaryNode
garbageCollect: ->
@cleanupDraw()
for id, el of @flaggedToDelete when id of @map
@map[id].destroy()
@destroy id
for id, el of @newRoots
el.update()
destroy: (id) ->
for child in @map[id].children
if @map[child.child.id]? and not @unflaggedToDelete[child.child.id]
@destroy child.child.id
delete @map[id]
delete @auxiliaryMap[id]
delete @flaggedToDelete[id]
hasViewNodeFor: (model) -> model? and model.id of @map
# ## createView
# Given a model object, create a renderer object
# of the appropriate type.
createView: (entity) ->
if (entity instanceof model.List) and not
(entity instanceof model.Container)
return new ListViewNode entity, this
switch entity.type
when 'text' then new TextViewNode entity, this
when 'block' then new BlockViewNode entity, this
when 'indent' then new IndentViewNode entity, this
when 'socket' then new SocketViewNode entity, this
when 'buttonContainer' then new ContainerViewNode entity, this
when 'lockedSocket' then new ContainerViewNode entity, this # LockedSocketViewNode entity, this
when 'document' then new DocumentViewNode entity, this
# Looks up a color name, or passes through a #hex color.
getColor: (model) ->
if model?.color instanceof Function
color = model.color(model)
else if model?
color = model.color
else
color = ""
if color and '#' is color.charAt(0)
color
else
@opts.colors[color] ? '#ffffff'
class AuxiliaryViewNode
constructor: (@view, @model) ->
@children = {}
@computedVersion = -1
cleanup: ->
@view.unflag @
if @model.version is @computedVersion
return
children = {}
if @model instanceof model.Container
@model.traverseOneLevel (head) =>
if head instanceof model.NewlineToken
return
else
children[head.id] = @view.getAuxiliaryNode head
for id, child of @children
unless id of children
@view.flag child
for id, child of children
@children[id] = child
child.cleanup()
update: ->
@view.unflag @
if @model.version is @computedVersion
return
children = {}
if @model instanceof model.Container
@model.traverseOneLevel (head) =>
if head instanceof model.NewlineToken
return
else
children[head.id] = @view.getAuxiliaryNode head
@children = children
for id, child of @children
child.update()
@computedVersion = @model.version
# # GenericViewNode
# Class from which all renderer classes will
# extend.
class GenericViewNode
constructor: (@model, @view) ->
# Record ourselves in the map
# from model to renderer
@view.map[@model.id] = this
@view.registerRoot @model
@lastCoordinate = new @view.draw.Point 0, 0
@invalidate = false
# *Zeroth pass variables*
# computeChildren
@lineLength = 0 # How many lines does this take up?
@children = [] # All children, flat
@oldChildren = [] # Previous children, for removing
@lineChildren = [] # Children who own each line
@multilineChildrenData = [] # Where do indents start/end?
# *First pass variables*
# computeMargins
@margins = {left:0, right:0, top:0, bottom:0}
@topLineSticksToBottom = false
@bottomLineSticksToTop = false
# *Pre-second pass variables*
# computeMinDimensions
# @view.draw.Size type, {width:n, height:m}
@minDimensions = [] # Dimensions on each line
@minDistanceToBase = [] # {above:n, below:n}
# *Second pass variables*
# computeDimensions
# @view.draw.Size type, {width:n, height:m}
@dimensions = [] # Dimensions on each line
@distanceToBase = [] # {above:n, below:n}
@carriageArrow = CARRIAGE_ARROW_NONE
@bevels =
top: false
bottom: false
# *Third/fifth pass variables*
# computeBoundingBoxX, computeBoundingBoxY
# @view.draw.Rectangle type, {x:0, y:0, width:200, height:100}
@bounds = [] # Bounding boxes on each line
@changedBoundingBox = true # Did any bounding boxes change just now?
# *Fourth pass variables*
# computeGlue
# {height:2, draw:true}
@glue = {}
@elements = []
@activeElements = []
# Versions. The corresponding
# Model will keep corresponding version
# numbers, and each of our passes can
# become a no-op when we are up-to-date (so
# that rerendering is fast when there are
# few or no changes to the Model).
@computedVersion = -1
draw: (boundingRect, style = {}, parent = null) ->
@drawSelf style, parent
root: ->
for element in @elements
element.setParent @view.draw.ctx
serialize: (line) ->
result = []
for prop in [
'lineLength'
'margins'
'topLineSticksToBottom'
'bottomLineSticksToTop'
'changedBoundingBox'
'path'
'highlightArea'
'computedVersion'
'carriageArrow'
'bevels']
result.push(prop + ': ' + JSON.stringify(@[prop]))
for child, i in @children
result.push("child #{i}: {startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}")
if line?
for prop in [
'multilineChildrenData'
'minDimensions'
'minDistanceToBase'
'dimensions'
'distanceToBase'
'bounds'
'glue']
result.push("#{prop} #{line}: #{JSON.stringify(@[prop][line])}")
for child, i in @lineChildren[line]
result.push("line #{line} child #{i}: " +
"{startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}}")
else
for line in [0...@lineLength]
for prop in [
'multilineChildrenData'
'minDimensions'
'minDistanceToBase'
'dimensions'
'distanceToBase'
'bounds'
'glue']
result.push("#{prop} #{line}: #{JSON.stringify(@[prop][line])}")
for child, i in @lineChildren[line]
result.push("line #{line} child #{i}: " +
"{startLine: #{child.startLine}, " +
"endLine: #{child.endLine}}}")
return result.join('\n')
# ## computeChildren (GenericViewNode)
# Find out which of our children lie on each line that we
# own, and also how many lines we own.
#
# Return the number of lines we own.
#
# This is basically a void computeChildren that should be
# overridden.
computeChildren: -> @lineLength
focusAll: ->
@group.focus()
computeCarriageArrow: ->
for childObj in @children
@view.getViewNodeFor(childObj.child).computeCarriageArrow()
return @carriageArrow
# ## computeMargins (GenericViewNode)
# Compute the amount of margin required outside the child
# on the top, bottom, left, and right.
#
# This is a void computeMargins that should be overridden.
computeMargins: ->
if @computedVersion is @model.version and
(not @model.parent? or not @view.hasViewNodeFor(@model.parent) or
@model.parent.version is @view.getViewNodeFor(@model.parent).computedVersion)
return @margins
# the margins I need depend on the type of my parent
parenttype = @model.parent?.type
padding = @view.opts.padding
left = if @model.isFirstOnLine() or @lineLength > 1 then padding else 0
right = if @model.isLastOnLine() or @lineLength > 1 then padding else 0
if parenttype is 'block' and @model.type is 'indent'
@margins =
top: 0
bottom: if @lineLength > 1 then @view.opts.indentTongueHeight else padding
firstLeft: padding
midLeft: @view.opts.indentWidth
lastLeft: @view.opts.indentWidth
firstRight: 0
midRight: 0
lastRight: padding
else if @model.type is 'text' and parenttype is 'socket'
@margins =
top: @view.opts.textPadding
bottom: @view.opts.textPadding
firstLeft: @view.opts.textPadding
midLeft: @view.opts.textPadding
lastLeft: @view.opts.textPadding
firstRight: @view.opts.textPadding
midRight: @view.opts.textPadding
lastRight: @view.opts.textPadding
else if @model.type is 'text' and parenttype is 'block'
if @model.prev?.type is 'newline' and @model.next?.type in ['newline', 'indentStart'] or @model.prev?.prev?.type is 'indentEnd'
textPadding = padding / 2
else
textPadding = padding
@margins =
top: textPadding
bottom: textPadding #padding
firstLeft: left
midLeft: left
lastLeft: left
firstRight: right
midRight: right
lastRight: right
else if parenttype is 'block'
@margins =
top: padding
bottom: padding
firstLeft: left
midLeft: padding
lastLeft: padding
firstRight: right
midRight: 0
lastRight: right
else
@margins = {
firstLeft: 0, midLeft:0, lastLeft: 0
firstRight: 0, midRight:0, lastRight: 0
top:0, bottom:0
}
@firstMargins =
left: @margins.firstLeft
right: @margins.firstRight
top: @margins.top
bottom: if @lineLength is 1 then @margins.bottom else 0
@midMargins =
left: @margins.midLeft
right: @margins.midRight
top: 0
bottom: 0
@lastMargins =
left: @margins.lastLeft
right: @margins.lastRight
top: if @lineLength is 1 then @margins.top else 0
bottom: @margins.bottom
for childObj in @children
@view.getViewNodeFor(childObj.child).computeMargins()
return null
getMargins: (line) ->
if line is 0 then @firstMargins
else if line is @lineLength - 1 then @lastMargins
else @midMargins
computeBevels: ->
for childObj in @children
@view.getViewNodeFor(childObj.child).computeBevels()
return @bevels
# ## computeMinDimensions (GenericViewNode)
# Compute the size of our bounding box on each
# line that we contain.
#
# Return child node.
#
# This is a void computeDimensinos that should be overridden.
computeMinDimensions: ->
if @minDimensions.length > @lineLength
@minDimensions.length = @minDistanceToBase.length = @lineLength
else
until @minDimensions.length is @lineLength
@minDimensions.push new @view.draw.Size 0, 0
@minDistanceToBase.push {above: 0, below: 0}
for i in [0...@lineLength]
@minDimensions[i].width = @minDimensions[i].height = 0
@minDistanceToBase[i].above = @minDistanceToBase[i].below = 0
return null
# ## computeDimensions (GenericViewNode)
# Compute the size of our bounding box on each
# line that we contain.
#
# Return child node.
computeDimensions: (force, root = false) ->
if @computedVersion is @model.version and not force and not @invalidate
return
oldDimensions = @dimensions
oldDistanceToBase = @distanceToBase
@dimensions = (new @view.draw.Size 0, 0 for [0...@lineLength])
@distanceToBase = ({above: 0, below: 0} for [0...@lineLength])
for size, i in @minDimensions
@dimensions[i].width = size.width; @dimensions[i].height = size.height
@distanceToBase[i].above = @minDistanceToBase[i].above
@distanceToBase[i].below = @minDistanceToBase[i].below
if @model.parent? and @view.hasViewNodeFor(@model.parent) and not root and
(@topLineSticksToBottom or @bottomLineSticksToTop or
(@lineLength > 1 and not @model.isLastOnLine()))
parentNode = @view.getViewNodeFor @model.parent
startLine = @model.getLinesToParent()
# grow below if "stick to bottom" is set.
if @topLineSticksToBottom
distance = @distanceToBase[0]
distance.below = Math.max(distance.below,
parentNode.distanceToBase[startLine].below)
@dimensions[0] = new @view.draw.Size(
@dimensions[0].width,
distance.below + distance.above)
# grow above if "stick to top" is set.
if @bottomLineSticksToTop
lineCount = @distanceToBase.length
distance = @distanceToBase[lineCount - 1]
distance.above = Math.max(distance.above,
parentNode.distanceToBase[startLine + lineCount - 1].above)
@dimensions[lineCount - 1] = new @view.draw.Size(
@dimensions[lineCount - 1].width,
distance.below + distance.above)
if @lineLength > 1 and not @model.isLastOnLine() and @model.type is 'block'
distance = @distanceToBase[@lineLength - 1]
distance.below = parentNode.distanceToBase[startLine + @lineLength - 1].below
@dimensions[lineCount - 1] = new @view.draw.Size(
@dimensions[lineCount - 1].width,
distance.below + distance.above)
changed = (oldDimensions.length != @lineLength)
if not changed then for line in [0...@lineLength]
if !oldDimensions[line].equals(@dimensions[line]) or
oldDistanceToBase[line].above != @distanceToBase[line].above or
oldDistanceToBase[line].below != @distanceToBase[line].below
changed = true
break
@changedBoundingBox or= changed
for childObj in @children
if childObj in @lineChildren[0] or childObj in @lineChildren[@lineLength - 1]
@view.getViewNodeFor(childObj.child).computeDimensions(changed, not (@model instanceof model.Container)) #(hack)
else
@view.getViewNodeFor(childObj.child).computeDimensions(false, not (@model instanceof model.Container)) #(hack)
return null
# ## computeBoundingBoxX (GenericViewNode)
# Given the left edge coordinate for our bounding box on
# this line, recursively layout the x-coordinates of us
# and all our children on this line.
computeBoundingBoxX: (left, line) ->
# Attempt to use our cache. Because modifications in the parent
# can affect the shape of child blocks, we can't only rely
# on versioning. For instance, changing `fd 10` to `forward 10`
# does not update the version on `10`, but the bounding box for
# `10` still needs to change. So we must also check
# that the coordinate we are given to begin the bounding box on matches.
if @computedVersion is @model.version and
left is @bounds[line]?.x and not @changedBoundingBox or
@bounds[line]?.x is left and
@bounds[line]?.width is @dimensions[line].width
return @bounds[line]
@changedBoundingBox = true
# Avoid re-instantiating a Rectangle object,
# if possible.
if @bounds[line]?
@bounds[line].x = left
@bounds[line].width = @dimensions[line].width
# If not, create one.
else
@bounds[line] = new @view.draw.Rectangle(
left, 0
@dimensions[line].width, 0
)
return @bounds[line]
# ## computeAllBoundingBoxX (GenericViewNode)
# Call `@computeBoundingBoxX` on all lines,
# thus laying out the entire document horizontally.
computeAllBoundingBoxX: (left = 0) ->
for size, line in @dimensions
@computeBoundingBoxX left, line
return @bounds
# ## computeGlue (GenericViewNode)
# If there are disconnected bounding boxes
# that belong to the same block,
# insert "glue" spacers between lines
# to connect them. For instance:
#
# ```
# someLongFunctionName ''' hello
# world '''
# ```
#
# would require glue between 'hello' and 'world'.
#
# This is a void function that should be overridden.
computeGlue: ->
@glue = {}
# ## computeBoundingBoxY (GenericViewNode)
# Like computeBoundingBoxX. We must separate
# these passes because glue spacers from `computeGlue`
# affect computeBoundingBoxY.
computeBoundingBoxY: (top, line) ->
# Again, we need to check to make sure that the coordinate
# we are given matches, since we cannot only rely on
# versioning (see computeBoundingBoxX).
if @computedVersion is @model.version and
top is @bounds[line]?.y and not @changedBoundingBox or
@bounds[line].y is top and
@bounds[line].height is @dimensions[line].height
return @bounds[line]
@changedBoundingBox = true
# Accept the bounding box edge we were given.
# We assume here that computeBoundingBoxX was
# already run for this version, so we
# should be guaranteed that `@bounds[line]` exists.
@bounds[line].y = top
@bounds[line].height = @dimensions[line].height
return @bounds[line]
# ## computeAllBoundingBoxY (GenericViewNode)
# Call `@computeBoundingBoxY` on all lines,
# thus laying out the entire document vertically.
#
# Account for glue spacing between lines.
computeAllBoundingBoxY: (top = 0) ->
for size, line in @dimensions
@computeBoundingBoxY top, line
top += size.height
if line of @glue then top += @glue[line].height
return @bounds
# ## getBounds (GenericViewNode)
# Deprecated. Access `@totalBounds` directly instead.
getBounds: -> @totalBounds
# ## computeOwnPath
# Using bounding box data, compute the vertices
# of the polygon that will wrap them. This function
# will be called from `computePath`, which does this
# recursively so as to draw the entire tree.
#
# Many nodes do not have paths at all,
# and so need not override this function.
computeOwnPath: ->
# ## computePath (GenericViewNode)
# Call `@computeOwnPath` and recurse. This function
# should never need to be overridden; override `@computeOwnPath`
# instead.
computePath: ->
# Here, we cannot just rely on versioning either.
# We need to know if any bounding box data changed. So,
# look at `@changedBoundingBox`, which should be set
# to `true` whenever a bounding box changed on the bounding box
# passes.
if @computedVersion is @model.version and
(@model.isLastOnLine() is @lastComputedLinePredicate) and
not @changedBoundingBox
return null
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computePath()
# It is possible that we have a version increment
# without changing bounding boxes. If this is the case,
# we don't need to recompute our own path.
if @changedBoundingBox or (@model.isLastOnLine() isnt @lastComputedLinePredicate)
@computeOwnPath()
# Recompute `totalBounds`, which is used
# to avoid re*drawing* polygons that
# are not on-screen. `totalBounds` is the AABB
# of the everything that has to do with the element,
# and we redraw iff it overlaps the AABB of the viewport.
@totalBounds = new @view.draw.NoRectangle()
if @bounds.length > 0
@totalBounds.unite @bounds[0]
@totalBounds.unite @bounds[@bounds.length - 1]
# Figure out our total bounding box however is faster.
if @bounds.length > @children.length
for child in @children
@totalBounds.unite @view.getViewNodeFor(child.child).totalBounds
else
maxRight = @totalBounds.right()
for bound in @bounds
@totalBounds.x = Math.min @totalBounds.x, bound.x
maxRight = Math.max maxRight, bound.right()
@totalBounds.width = maxRight - @totalBounds.x
if @path?
@totalBounds.unite @path.bounds()
@lastComputedLinePredicate = @model.isLastOnLine()
return null
# ## computeOwnDropArea (GenericViewNode)
# Using bounding box data, compute the drop area
# for drag-and-drop blocks, if it exists.
#
# If we cannot drop something on this node
# (e.g. a socket that already contains a block),
# set `@dropArea` to null.
#
# Simultaneously, compute `@highlightArea`, which
# is the white polygon that lights up
# when we hover over a drop area.
computeOwnDropArea: ->
# ## computeDropAreas (GenericViewNode)
# Call `@computeOwnDropArea`, and recurse.
#
# This should never have to be overridden;
# override `@computeOwnDropArea` instead.
computeDropAreas: ->
# Like with `@computePath`, we cannot rely solely on versioning,
# so we check the bounding box flag.
if @computedVersion is @model.version and
not @changedBoundingBox
return null
# Compute drop and highlight areas for ourself
@computeOwnDropArea()
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computeDropAreas()
return null
computeNewVersionNumber: ->
if @computedVersion is @model.version and
not @changedBoundingBox
return null
@changedBoundingBox = false
@invalidate = false
@computedVersion = @model.version
# Recurse.
for childObj in @children
@view.getViewNodeFor(childObj.child).computeNewVersionNumber()
return null
# ## drawSelf (GenericViewNode)
# Draw our own polygon on a canvas context.
# May require special effects, like graying-out
# or blueing for lasso select.
drawSelf: (style = {}) ->
hide: ->
for element in @elements
element?.deactivate?()
@activeElements = []
destroy: (root = true) ->
if root
for element in @elements
element?.destroy?()
else if @highlightArea?
@highlightArea.destroy()
@activeElements = []
for child in @children
@view.getViewNodeFor(child.child).destroy(false)
class ListViewNode extends GenericViewNode
constructor: (@model, @view) ->
super
draw: (boundingRect, style = {}, parent = null) ->
super
for childObj in @children
@view.getViewNodeFor(childObj.child).draw boundingRect, style, @group
root: ->
for child in @children
@view.getViewNodeFor(child.child).root()
destroy: (root = true) ->
for child in @children
@view.getViewNodeFor(child.child).destroy()
# ## computeChildren (ListViewNode)
# Figure out which children lie on each line,
# and compute `@multilineChildrenData` simultaneously.
#
# We will do this by going to all of our immediate children,
# recursing, then calculating their starting and ending lines
# based on their computing line lengths.
computeChildren: ->
# If we can, use our cached information.
if @computedVersion is @model.version
return @lineLength
# Otherwise, recompute.
@lineLength = 0
@lineChildren = [[]]
@children = []
@multilineChildrenData = []
@topLineSticksToBottom = false
@bottomLineSticksToTop = false
line = 0
# Go to all our immediate children.
@model.traverseOneLevel (head) =>
# If the child is a newline, simply advance the
# line counter.
if head.type is 'newline'
line += 1
@lineChildren[line] ?= []
# Otherwise, get the view object associated
# with this model, and ask it to
# compute children.
else
view = @view.getViewNodeFor(head)
childLength = view.computeChildren()
# Construct a childObject,
# which will remember starting and endling lines.
childObject =
child: head
startLine: line
endLine: line + childLength - 1
# Put it into `@children`.
@children.push childObject
# Put it into `@lineChildren`.
for i in [line...line + childLength]
@lineChildren[i] ?= []
# We don't want to store cursor tokens
# in `@lineChildren`, as they are inconvenient
# to deal with in layout, which is the only
# thing `@lineChildren` is used for.
unless head.type is 'cursor'
@lineChildren[i].push childObject
# If this object is a multiline child,
# update our multiline child data to reflect
# where it started and ended.
if view.lineLength > 1
if @multilineChildrenData[line] is MULTILINE_END
@multilineChildrenData[line] = MULTILINE_END_START
else
@multilineChildrenData[line] = MULTILINE_START
@multilineChildrenData[i] = MULTILINE_MIDDLE for i in [line + 1...line + childLength - 1]
@multilineChildrenData[line + childLength - 1] = MULTILINE_END
# Advance our line counter
# by however long the child was
# (i.e. however many newlines
# we skipped).
line += childLength - 1
# Set @lineLength to reflect
# what we just found out.
@lineLength = line + 1
# If we have changed in line length,
# there has obviously been a bounding box change.
# The bounding box pass as it stands only deals
# with lines it knows exists, so we need to chop off
# the end of the array.
if @bounds.length isnt @lineLength
@changedBoundingBox = true
@bounds = @bounds[...@lineLength]
# Fill in gaps in @multilineChildrenData with NO_MULTILINE
@multilineChildrenData[i] ?= NO_MULTILINE for i in [0...@lineLength]
if @lineLength > 1
@topLineSticksToBottom = true
@bottomLineSticksToTop = true
return @lineLength
# ## computeDimensions (ListViewNode)
# Compute the size of our bounding box on each line.
computeMinDimensions: ->
# If we can, use cached data.
if @computedVersion is @model.version
return null
# start at zero min dimensions
super
# Lines immediately after the end of Indents
# have to be extended to a minimum width.
# Record the lines that need to be extended here.
linesToExtend = []
preIndentLines = []
# Recurse on our children, updating
# our dimensions as we go to contain them.
for childObject in @children
# Ask the child to compute dimensions
childNode = @view.getViewNodeFor(childObject.child)
childNode.computeMinDimensions()
minDimensions = childNode.minDimensions
minDistanceToBase = childNode.minDistanceToBase
# Horizontal margins get added to every line.
for size, line in minDimensions
desiredLine = line + childObject.startLine
margins = childNode.getMargins line
# Unless we are in the middle of an indent,
# add padding on the right of the child.
#
# Exception: Children with invisible bounding boxes
# should remain invisible. This matters
# mainly for indents starting at the end of a line.
@minDimensions[desiredLine].width += size.width +
margins.left +
margins.right
# Compute max distance above and below text
#
# Exception: do not add the bottom padding on an
# Indent if we own the next line as well.
if childObject.child.type is 'indent' and
line is minDimensions.length - 1 and
desiredLine < @lineLength - 1
bottomMargin = 0
linesToExtend.push desiredLine + 1
else if childObject.child.type is 'indent' and
line is 0
preIndentLines.push desiredLine
bottomMargin = margins.bottom
else
bottomMargin = margins.bottom
@minDistanceToBase[desiredLine].above = Math.max(
@minDistanceToBase[desiredLine].above,
minDistanceToBase[line].above + margins.top)
@minDistanceToBase[desiredLine].below = Math.max(
@minDistanceToBase[desiredLine].below,
minDistanceToBase[line].below + Math.max(bottomMargin, (
if @model.buttons? and @model.buttons.length > 0 and
desiredLine is @lineLength - 1 and
@multilineChildrenData[line] is MULTILINE_END and
@lineChildren[line].length is 1
@view.opts.buttonVertPadding + @view.opts.buttonHeight
else
0
)))
# Height is just the sum of the above-base and below-base counts.
# Empty lines should have some height.
for minDimension, line in @minDimensions
if @lineChildren[line].length is 0
# Socket should be shorter than other blocks
if @model.type is 'socket'
@minDistanceToBase[line].above = @view.opts.textHeight + @view.opts.textPadding
@minDistanceToBase[line].below = @view.opts.textPadding
# Text should not claim any padding
else if @model.type is 'text'
@minDistanceToBase[line].above = @view.opts.textHeight
@minDistanceToBase[line].below = 0
# The first line of an indent is often empty; this is the desired behavior
else if @model.type is 'indent' and line is 0
@minDistanceToBase[line].above = 0
@minDistanceToBase[line].below = 0
# Empty blocks should be the height of lines with text
else
@minDistanceToBase[line].above = @view.opts.textHeight + @view.opts.padding
@minDistanceToBase[line].below = @view.opts.padding
minDimension.height =
@minDistanceToBase[line].above +
@minDistanceToBase[line].below
# Make space for mutation buttons. In lockedSocket,
# these will go on the left; otherwise they will go on the right.
@extraLeft = 0
@extraWidth = 0
if @model.type in ['block', 'buttonContainer']
if @model.buttons? then for {key} in @model.buttons
@extraWidth += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
@minDimensions[@minDimensions.length - 1].width += @extraWidth
if @model.type is 'lockedSocket'
if @model.buttons? then for {key} in @model.buttons
@extraLeft += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
@minDimensions[@minDimensions.length - 1].width += @extraLeft
# Go through and adjust the width of rectangles
# immediately after the end of an indent to
# be as long as necessary
for line in linesToExtend
@minDimensions[line].width = Math.max(
@minDimensions[line].width, Math.max(
@view.opts.minIndentTongueWidth,
@view.opts.indentWidth + @view.opts.tabWidth + @view.opts.tabOffset + @view.opts.bevelClip
))
for line in preIndentLines
@minDimensions[line].width = Math.max(
@minDimensions[line].width, Math.max(
@view.opts.minIndentTongueWidth,
@view.opts.indentWidth + @view.opts.tabWidth + @view.opts.tabOffset + @view.opts.bevelClip
))
# Add space for carriage arrow
for lineChild in @lineChildren[@lineLength - 1]
lineChildView = @view.getViewNodeFor lineChild.child
if lineChildView.carriageArrow isnt CARRIAGE_ARROW_NONE
@minDistanceToBase[@lineLength - 1].below += @view.opts.padding
@minDimensions[@lineLength - 1].height =
@minDistanceToBase[@lineLength - 1].above +
@minDistanceToBase[@lineLength - 1].below
break
return null
# ## computeBoundingBoxX (ListViewNode)
# Layout bounding box positions horizontally.
# This needs to be separate from y-coordinate computation
# because of glue spacing (the space between lines
# that keeps weird-shaped blocks continuous), which
# can shift y-coordinates around.
computeBoundingBoxX: (left, line, offset = 0) ->
# Use cached data if possible
if @computedVersion is @model.version and
left is @bounds[line]?.x and not @changedBoundingBox
return @bounds[line]
offset += @extraLeft
# If the bounding box we're being asked
# to layout is exactly the same,
# avoid setting `@changedBoundingBox`
# for performance reasons (also, trivially,
# avoid changing bounding box coords).
unless @bounds[line]?.x is left and
@bounds[line]?.width is @dimensions[line].width
# Assign our own bounding box given
# this center-left coordinate
if @bounds[line]?
@bounds[line].x = left
@bounds[line].width = @dimensions[line].width
else
@bounds[line] = new @view.draw.Rectangle(
left, 0
@dimensions[line].width, 0
)
@changedBoundingBox = true
# Now recurse. We will keep track
# of a "cursor" as we go along,
# placing children down and
# adding padding and sizes
# to make them not overlap.
childLeft = left + offset
# Get rendering info on each of these children
for lineChild, i in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
childMargins = childView.getMargins childLine
childLeft += childMargins.left
childView.computeBoundingBoxX childLeft, childLine
childLeft +=
childView.dimensions[childLine].width + childMargins.right
# Return the bounds we just
# computed.
return @bounds[line]
# ## computeBoundingBoxY
# Layout a line vertically.
computeBoundingBoxY: (top, line) ->
# Use our cache if possible.
if @computedVersion is @model.version and
top is @bounds[line]?.y and not @changedBoundingBox
return @bounds[line]
# Avoid setting `@changedBoundingBox` if our
# bounding box has not actually changed,
# for performance reasons. (Still need to
# recurse, in case children have changed
# but not us)
unless @bounds[line]?.y is top and
@bounds[line]?.height is @dimensions[line].height
# Assign our own bounding box given
# this center-left coordinate
@bounds[line].y = top
@bounds[line].height = @dimensions[line].height
@changedBoundingBox = true
# Go to each child and lay them out so that their distanceToBase
# lines up.
above = @distanceToBase[line].above
for lineChild, i in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
childAbove = childView.distanceToBase[childLine].above
childView.computeBoundingBoxY top + above - childAbove, childLine
# Return the bounds we just computed.
return @bounds[line]
# ## layout
# Run all of these layout steps in order.
#
# Takes two arguments, which can be changed
# to translate the entire document from the upper-left corner.
layout: (left = @lastCoordinate.x, top = @lastCoordinate.y) ->
@view.registerRoot @model
@lastCoordinate = new @view.draw.Point left, top
@computeChildren()
@computeCarriageArrow true
@computeMargins()
@computeBevels()
@computeMinDimensions()
@computeDimensions 0, true
@computeAllBoundingBoxX left
@computeGlue()
@computeAllBoundingBoxY top
@computePath()
@computeDropAreas()
changedBoundingBox = @changedBoundingBox
@computeNewVersionNumber()
return changedBoundingBox
# ## absorbCache
# A hacky thing to get a view node of a new List
# to acquire all the properties of its children
# TODO re-examine
absorbCache: ->
@view.registerRoot @model
@computeChildren()
@computeCarriageArrow true
@computeMargins()
@computeBevels()
@computeMinDimensions()
# Replacement for computeDimensions
for size, line in @minDimensions
@distanceToBase[line] = {
above: @lineChildren[line].map((child) => @view.getViewNodeFor(child.child).distanceToBase[line - child.startLine].above).reduce((a, b) -> Math.max(a, b))
below: @lineChildren[line].map((child) => @view.getViewNodeFor(child.child).distanceToBase[line - child.startLine].below).reduce((a, b) -> Math.max(a, b))
}
@dimensions[line] = new draw.Size @minDimensions[line].width, @minDimensions[line].height
#@computeDimensions false, true
# Replacement for computeAllBoundingBoxX
for size, line in @dimensions
child = @lineChildren[line][0]
childView = @view.getViewNodeFor child.child
left = childView.bounds[line - child.startLine].x
@computeBoundingBoxX left, line
@computeGlue()
# Replacement for computeAllBoundingBoxY
for size, line in @dimensions
child = @lineChildren[line][0]
childView = @view.getViewNodeFor child.child
oldY = childView.bounds[line - child.startLine].y
top = childView.bounds[line - child.startLine].y +
childView.distanceToBase[line - child.startLine].above -
@distanceToBase[line].above
@computeBoundingBoxY top, line
@computePath()
@computeDropAreas()
return true
# ## computeGlue
# Compute the necessary glue spacing between lines.
#
# If a block has disconnected blocks, e.g.
# ```
# someLongFunctionName '''hello
# world'''
# ```
#
# it requires glue spacing. Then, any surrounding blocks
# must add their padding to that glue spacing, until we
# reach an Indent, at which point we can stop.
#
# Parents outside the indent must stil know that there is
# a space between these line, but they wil not have
# to colour in that space. This will be flaged
# by the `draw` flag on the glue objects.
computeGlue: ->
# Use our cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
# Immediately recurse, as we will
# need to know child glue info in order
# to compute our own (adding padding, etc.).
for childObj in @children
@view.getViewNodeFor(childObj.child).computeGlue()
@glue = {}
# Go through every pair of adjacent bounding boxes
# to see if they overlap or not
for box, line in @bounds when line < @bounds.length - 1
@glue[line] = {
type: 'normal'
height: 0
draw: false
}
# We will always have glue spacing at least as big
# as the biggest child's glue spacing.
for lineChild in @lineChildren[line]
childView = @view.getViewNodeFor lineChild.child
childLine = line - lineChild.startLine
if childLine of childView.glue
# Either add padding or not, depending
# on whether there is an indent between us.
@glue[line].height = Math.max @glue[line].height, childView.glue[childLine].height
if childView.carriageArrow isnt CARRIAGE_ARROW_NONE
@glue[line].height = Math.max @glue[line].height, @view.opts.padding
# Return the glue we just computed.
return @glue
# # ContainerViewNode
# Class from which `socketView`, `indentView`, `blockView`, and `documentView` extend.
# Contains function for dealing with multiple children, making polygons to wrap
# multiple lines, etc.
class ContainerViewNode extends ListViewNode
constructor: (@model, @view) ->
super
# *Sixth pass variables*
# computePath
@group = @view.draw.group('droplet-container-group')
if @model.type is 'block'
@path = @view.draw.path([], true, {
cssClass: 'droplet-block-path'
})
else
@path = @view.draw.path([], false, {
cssClass: "droplet-#{@model.type}-path"
})
@totalBounds = new @view.draw.NoRectangle()
@path.setParent @group
# *Seventh pass variables*
# computeDropAreas
# each one is a @view.draw.Path (or null)
@dropPoint = null
@highlightArea = @view.draw.path([], false, {
fillColor: '#FF0'
strokeColor: '#FF0'
lineWidth: 1
})
@highlightArea.deactivate()
@buttonGroups = {}
@buttonTexts = {}
@buttonPaths = {}
@buttonRects = {}
if @model.buttons? then for {key, glyph} in @model.buttons
@buttonGroups[key] = @view.draw.group()
@buttonPaths[key] = @view.draw.path([
new @view.draw.Point 0, 0
new @view.draw.Point @view.opts.buttonWidth, 0
new @view.draw.Point @view.opts.buttonWidth, @view.opts.buttonHeight
new @view.draw.Point 0, @view.opts.buttonHeight
], false, {
fillColor: 'none'
cssClass: 'droplet-button-path'
})
###
new @view.draw.Point 0, @view.opts.bevelClip
new @view.draw.Point @view.opts.bevelClip, 0
new @view.draw.Point @view.opts.buttonWidth - @view.opts.bevelClip, 0
new @view.draw.Point @view.opts.buttonWidth, @view.opts.bevelClip
new @view.draw.Point @view.opts.buttonWidth, @view.opts.buttonHeight - @view.opts.bevelClip
new @view.draw.Point @view.opts.buttonWidth - @view.opts.bevelClip, @view.opts.buttonHeight
new @view.draw.Point @view.opts.bevelClip, @view.opts.buttonHeight
new @view.draw.Point 0, @view.opts.buttonHeight - @view.opts.bevelClip
###
@buttonGroups[key].style = {}
@buttonTexts[key] = @view.draw.text(new @view.draw.Point(
(@view.opts.buttonWidth - @view.draw.measureCtx.measureText(glyph).width)/ 2,
(@view.opts.buttonHeight - @view.opts.textHeight) / 2
), glyph, if @view.opts.invert then BUTTON_GLYPH_INVERT_COLOR else BUTTON_GLYPH_COLOR)
@buttonPaths[key].setParent @buttonGroups[key]
@buttonTexts[key].setParent @buttonGroups[key]
@buttonGroups[key].setParent @group
@elements.push @buttonGroups[key]
@activeElements.push @buttonPaths[key]
@activeElements.push @buttonTexts[key]
@activeElements.push @buttonGroups[key]
@elements.push @group
@elements.push @path
@elements.push @highlightArea
destroy: (root = true) ->
if root
for element in @elements
element?.destroy?()
else if @highlightArea?
@highlightArea.destroy()
for child in @children
@view.getViewNodeFor(child.child).destroy(false)
root: ->
@group.setParent @view.draw.ctx
# ## draw (GenericViewNode)
# Call `drawSelf` and recurse, if we are in the viewport.
draw: (boundingRect, style = {}, parent = null) ->
if not boundingRect? or @totalBounds.overlap boundingRect
@drawSelf style, parent
@group.activate(); @path.activate()
for element in @activeElements
element.activate()
if @highlightArea?
@highlightArea.setParent @view.draw.ctx
if parent?
@group.setParent parent
for childObj in @children
@view.getViewNodeFor(childObj.child).draw boundingRect, style, @group
else
@group.destroy()
if @highlightArea?
@highlightArea.destroy()
computeCarriageArrow: (root = false) ->
oldCarriageArrow = @carriageArrow
@carriageArrow = CARRIAGE_ARROW_NONE
parent = @model.parent
if (not root) and parent?.type is 'indent' and @view.hasViewNodeFor(parent) and
@view.getViewNodeFor(parent).lineLength > 1 and
@lineLength is 1
head = @model.start
until head is parent.start or head.type is 'newline'
head = head.prev
if head is parent.start
if @model.isLastOnLine()
@carriageArrow = CARRIAGE_ARROW_INDENT
else
@carriageArrow = CARRIAGE_GROW_DOWN
else unless @model.isFirstOnLine()
@carriageArrow = CARRIAGE_ARROW_SIDEALONG
if @carriageArrow isnt oldCarriageArrow
@changedBoundingBox = true
if @computedVersion is @model.version and
(not @model.parent? or not @view.hasViewNodeFor(@model.parent) or
@model.parent.version is @view.getViewNodeFor(@model.parent).computedVersion)
return null
super
computeGlue: ->
# Use our cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
super
for box, line in @bounds when line < @bounds.length - 1
# Additionally, we add glue spacing padding if we are disconnected
# from the bounding box on the next line.
unless @multilineChildrenData[line] is MULTILINE_MIDDLE
# Find the horizontal overlap between these two bounding rectangles,
# which is our right edge minus their left, or vice versa.
overlap = Math.min @bounds[line].right() - @bounds[line + 1].x, @bounds[line + 1].right() - @bounds[line].x
# If we are starting an indent, then our "bounding box"
# on the next line is not actually how we will be visualized;
# instead, we must connect to the small rectangle
# on the left of a C-shaped indent thing. So,
# compute overlap with that as well.
if @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
overlap = Math.min overlap, @bounds[line + 1].x + @view.opts.indentWidth - @bounds[line].x
# If the overlap is too small, demand glue.
if overlap < @view.opts.padding and @model.type isnt 'indent'
@glue[line].height += @view.opts.padding
@glue[line].draw = true
return @glue
computeBevels: ->
oldBevels = @bevels
@bevels =
top: true
bottom: true
if (@model.parent?.type in ['indent', 'document']) and
@model.start.prev?.type is 'newline' and
@model.start.prev?.prev isnt @model.parent.start
@bevels.top = false
if (@model.parent?.type in ['indent', 'document']) and
@model.end.next?.type is 'newline'
@bevels.bottom = false
unless oldBevels.top is @bevels.top and
oldBevels.bottom is @bevels.bottom
@changedBoundingBox = true
if @computedVersion is @model.version
return null
super
# ## computeOwnPath
# Using bounding box data, compute the polygon
# that represents us. This contains a lot of special cases
# for glue and multiline starts and ends.
computeOwnPath: ->
# There are four kinds of line,
# for the purposes of computing the path.
#
# 1. Normal block line; we surround the bounding rectangle.
# 2. Beginning of a multiline block. Avoid that block on the right and bottom.
# 3. Middle of a multiline block. We avoid to the left side
# 4. End of a multiline block. We make a G-shape if necessary. If it is an Indent,
# this will leave a thick tongue due to things done in dimension
# computation.
# We will keep track of two sets of coordinates,
# the left side of the polygon and the right side.
#
# At the end, we will reverse `left` and concatenate these
# so as to create a counterclockwise path.
left = []
right = []
# If necessary, add tab
# at the top.
if @shouldAddTab() and @model.isFirstOnLine() and
@carriageArrow isnt CARRIAGE_ARROW_SIDEALONG
@addTabReverse right, new @view.draw.Point @bounds[0].x + @view.opts.tabOffset, @bounds[0].y
for bounds, line in @bounds
# Case 1. Normal rendering.
if @multilineChildrenData[line] is NO_MULTILINE
# Draw the left edge of the bounding box.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Draw the right edge of the bounding box.
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# Case 2. Start of a multiline block.
if @multilineChildrenData[line] is MULTILINE_START
# Draw the left edge of the bounding box.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Find the multiline child that's starting on this line,
# so that we can know its bounds
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineView = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineView.bounds[line - multilineChild.startLine]
# If the multiline child here is invisible,
# draw the line just normally.
if multilineBounds.width is 0
right.push new @view.draw.Point bounds.right(), bounds.y
# Otherwise, avoid the block by tracing out its
# top and left edges, then going to our bound's bottom.
else
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), multilineBounds.y
if multilineChild.child.type is 'indent'
@addTab right, new @view.draw.Point multilineBounds.x + @view.opts.tabOffset, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
# Case 3. Middle of an indent.
if @multilineChildrenData[line] is MULTILINE_MIDDLE
multilineChild = @lineChildren[line][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[line - multilineChild.startLine]
# Draw the left edge normally.
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Draw the right edge straight down,
# exactly to the left of the multiline child.
unless @multilineChildrenData[line - 1] in [MULTILINE_START, MULTILINE_END_START] and
multilineChild.child.type is 'indent'
right.push new @view.draw.Point multilineBounds.x, bounds.y
right.push new @view.draw.Point multilineBounds.x, bounds.bottom()
# Case 4. End of an indent.
if @multilineChildrenData[line] in [MULTILINE_END, MULTILINE_END_START]
left.push new @view.draw.Point bounds.x, bounds.y
left.push new @view.draw.Point bounds.x, bounds.bottom()
# Find the child that is the indent
multilineChild = @lineChildren[line][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[line - multilineChild.startLine]
# Avoid the indented area
unless @multilineChildrenData[line - 1] in [MULTILINE_START, MULTILINE_END_START] and
multilineChild.child.type is 'indent'
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
if multilineChild.child.type is 'indent'
@addTabReverse right, new @view.draw.Point multilineBounds.x + @view.opts.tabOffset, multilineBounds.bottom()
right.push new @view.draw.Point multilineBounds.right(), multilineBounds.bottom()
# If we must, make the "G"-shape
if @lineChildren[line].length > 1
right.push new @view.draw.Point multilineBounds.right(), multilineBounds.y
if @multilineChildrenData[line] is MULTILINE_END
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
else
# Find the multiline child that's starting on this line,
# so that we can know its bounds
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineView = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineView.bounds[line - multilineChild.startLine]
# Draw the upper-right corner
right.push new @view.draw.Point bounds.right(), bounds.y
# If the multiline child here is invisible,
# draw the line just normally.
if multilineBounds.width is 0
right.push new @view.draw.Point bounds.right(), bounds.y
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# Otherwise, avoid the block by tracing out its
# top and left edges, then going to our bound's bottom.
else
right.push new @view.draw.Point bounds.right(), multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.y
right.push new @view.draw.Point multilineBounds.x, multilineBounds.bottom()
# Otherwise, don't.
else
right.push new @view.draw.Point bounds.right(), multilineBounds.bottom()
right.push new @view.draw.Point bounds.right(), bounds.bottom()
# "Glue" phase
# Here we use our glue spacing data
# to draw glue, if necessary.
#
# If we are being told to draw some glue here,
# do so.
if line < @lineLength - 1 and line of @glue and @glue[line].draw
# Extract information from the glue spacing
# and bounding box data combined.
#
# `glueTop` will be the top of the "glue" box.
# `leftmost` and `rightmost` are the leftmost
# and rightmost extremes of this and the next line's
# bounding boxes.
glueTop = @bounds[line + 1].y - @glue[line].height
leftmost = Math.min @bounds[line + 1].x, @bounds[line].x
rightmost = Math.max @bounds[line + 1].right(), @bounds[line].right()
# Bring the left down to the glue top line, then down to the
# level of the next line's bounding box. This prepares
# it to go straight horizontally over
# to the top of the next bounding box,
# once the loop reaches that point.
left.push new @view.draw.Point @bounds[line].x, glueTop
left.push new @view.draw.Point leftmost, glueTop
left.push new @view.draw.Point leftmost, glueTop + @view.opts.padding
# Do the same for the right side, unless we can't
# because we're avoiding intersections with a multiline child that's
# in the way.
unless @multilineChildrenData[line] is MULTILINE_START
right.push new @view.draw.Point @bounds[line].right(), glueTop
right.push new @view.draw.Point rightmost, glueTop
right.push new @view.draw.Point rightmost, glueTop + @view.opts.padding
# Otherwise, bring us gracefully to the next line
# without lots of glue (minimize the extra colour).
else if @bounds[line + 1]? and @multilineChildrenData[line] isnt MULTILINE_MIDDLE
# Instead of outward extremes, we take inner extremes this time,
# to minimize extra colour between lines.
innerLeft = Math.max @bounds[line + 1].x, @bounds[line].x
innerRight = Math.min @bounds[line + 1].right(), @bounds[line].right()
# Drop down to the next line on the left, minimizing extra colour
left.push new @view.draw.Point innerLeft, @bounds[line].bottom()
left.push new @view.draw.Point innerLeft, @bounds[line + 1].y
# Do the same on the right, unless we need to avoid
# a multiline block that's starting here.
unless @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
right.push new @view.draw.Point innerRight, @bounds[line].bottom()
right.push new @view.draw.Point innerRight, @bounds[line + 1].y
else if @carriageArrow is CARRIAGE_GROW_DOWN
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point @bounds[line].x, destinationBounds.y - @view.opts.padding
else if @carriageArrow is CARRIAGE_ARROW_INDENT
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.y
right.push new @view.draw.Point destinationBounds.x + @view.opts.tabOffset + @view.opts.tabWidth, destinationBounds.y
left.push new @view.draw.Point @bounds[line].x, destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point destinationBounds.x, destinationBounds.y - @view.opts.padding
left.push new @view.draw.Point destinationBounds.x, destinationBounds.y
@addTab right, new @view.draw.Point destinationBounds.x + @view.opts.tabOffset, destinationBounds.y
else if @carriageArrow is CARRIAGE_ARROW_SIDEALONG and @model.isLastOnLine()
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[@model.getLinesToParent()]
right.push new @view.draw.Point @bounds[line].right(), destinationBounds.bottom() + @view.opts.padding
right.push new @view.draw.Point destinationBounds.x + @view.opts.tabOffset + @view.opts.tabWidth,
destinationBounds.bottom() + @view.opts.padding
left.push new @view.draw.Point @bounds[line].x, destinationBounds.bottom()
left.push new @view.draw.Point destinationBounds.x, destinationBounds.bottom()
left.push new @view.draw.Point destinationBounds.x, destinationBounds.bottom() + @view.opts.padding
@addTab right, new @view.draw.Point destinationBounds.x + @view.opts.tabOffset,
destinationBounds.bottom() + @view.opts.padding
# If we're avoiding intersections with a multiline child in the way,
# bring us gracefully to the next line's top. We had to keep avoiding
# using bounding box right-edge data earlier, because it would have overlapped;
# instead, we want to use the left edge of the multiline block that's
# starting here.
if @multilineChildrenData[line] in [MULTILINE_START, MULTILINE_END_START]
multilineChild = @lineChildren[line][@lineChildren[line].length - 1]
multilineNode = @view.getViewNodeFor multilineChild.child
multilineBounds = multilineNode.bounds[line - multilineChild.startLine]
if @glue[line]?.draw
glueTop = @bounds[line + 1].y - @glue[line].height + @view.opts.padding
else
glueTop = @bounds[line].bottom()
# Special case for indents that start with newlines;
# don't do any of the same-line-start multiline stuff.
if multilineChild.child.type is 'indent' and multilineChild.child.start.next.type is 'newline'
right.push new @view.draw.Point @bounds[line].right(), glueTop
@addTab right, new @view.draw.Point(@bounds[line + 1].x +
@view.opts.indentWidth +
@extraLeft +
@view.opts.tabOffset, glueTop), true
else
right.push new @view.draw.Point multilineBounds.x, glueTop
unless glueTop is @bounds[line + 1].y
right.push new @view.draw.Point multilineNode.bounds[line - multilineChild.startLine + 1].x, glueTop
right.push new @view.draw.Point multilineNode.bounds[line - multilineChild.startLine + 1].x, @bounds[line + 1].y
# If necessary, add tab
# at the bottom.
if @shouldAddTab() and @model.isLastOnLine() and
@carriageArrow is CARRIAGE_ARROW_NONE
@addTab right, new @view.draw.Point @bounds[@lineLength - 1].x + @view.opts.tabOffset,
@bounds[@lineLength - 1].bottom()
topLeftPoint = left[0]
# Reverse the left and concatenate it with the right
# to make a counterclockwise path
path = dedupe left.reverse().concat right
newPath = []
for point, i in path
if i is 0 and not @bevels.bottom
newPath.push point
continue
if (not @bevels.top) and point.almostEquals(topLeftPoint)
newPath.push point
continue
next = path[(i + 1) %% path.length]
prev = path[(i - 1) %% path.length]
if (point.x is next.x) isnt (point.y is next.y) and
(point.x is prev.x) isnt (point.y is prev.y) and
point.from(prev).magnitude() >= @view.opts.bevelClip * 2 and
point.from(next).magnitude() >= @view.opts.bevelClip * 2
newPath.push point.plus(point.from(prev).toMagnitude(-@view.opts.bevelClip))
newPath.push point.plus(point.from(next).toMagnitude(-@view.opts.bevelClip))
else
newPath.push point
# Make a Path object out of these points
@path.setPoints newPath
if @model.type is 'block'
@path.style.fillColor = @view.getColor @model
if @model.buttons? and @model.type is 'lockedSocket'
# Add the add button if necessary
firstRect = @bounds[0]
start = firstRect.x
top = firstRect.y + firstRect.height / 2 - @view.opts.buttonHeight / 2
for {key} in @model.buttons
@buttonGroups[key].style.transform = "translate(#{start}, #{top})"
@buttonGroups[key].update()
@buttonPaths[key].update()
@buttonRects[key] = new @view.draw.Rectangle start, top, @view.opts.buttonWidth, @view.opts.buttonHeight
@elements.push @buttonPaths[key]
start += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
else if @model.buttons?
# Add the add button if necessary
lastLine = @bounds.length - 1
lastRect = @bounds[lastLine]
if @model.type is 'block'
start = lastRect.x + lastRect.width - @extraWidth - @view.opts.buttonHorizPadding
else
start = lastRect.x + lastRect.width - @extraWidth + @view.opts.buttonHorizPadding
top = lastRect.y + lastRect.height / 2 - @view.opts.buttonHeight / 2
for {key} in @model.buttons
# Cases when last line is MULTILINE
if @multilineChildrenData[lastLine] is MULTILINE_END
multilineChild = @lineChildren[lastLine][0]
multilineBounds = @view.getViewNodeFor(multilineChild.child).bounds[lastLine - multilineChild.startLine]
# If it is a G-Shape
if @lineChildren[lastLine].length > 1
height = multilineBounds.bottom() - lastRect.y
top = lastRect.y + height / 2 - @view.opts.buttonHeight/2
else
height = lastRect.bottom() - multilineBounds.bottom()
top = multilineBounds.bottom() + height/2 - @view.opts.buttonHeight/2
@buttonGroups[key].style.transform = "translate(#{start}, #{top})"
@buttonGroups[key].update()
@buttonPaths[key].update()
@buttonRects[key] = new @view.draw.Rectangle start, top, @view.opts.buttonWidth, @view.opts.buttonHeight
@elements.push @buttonPaths[key]
start += @view.opts.buttonWidth + @view.opts.buttonHorizPadding
# Return it.
return @path
# ## addTab
# Add the tab graphic to a path in a given location.
addTab: (array, point) ->
# Rightmost point of the tab, where it begins to dip down.
array.push new @view.draw.Point(point.x + @view.opts.tabWidth,
point.y)
# Dip down.
array.push new @view.draw.Point point.x + @view.opts.tabWidth * (1 - @view.opts.tabSideWidth),
point.y + @view.opts.tabHeight
# Bottom plateau.
array.push new @view.draw.Point point.x + @view.opts.tabWidth * @view.opts.tabSideWidth,
point.y + @view.opts.tabHeight
# Rise back up.
array.push new @view.draw.Point point.x, point.y
# Move over to the given corner itself.
array.push point
# ## addTabReverse
# Add the tab in reverse order
addTabReverse: (array, point) ->
array.push point
array.push new @view.draw.Point point.x, point.y
array.push new @view.draw.Point point.x + @view.opts.tabWidth * @view.opts.tabSideWidth,
point.y + @view.opts.tabHeight
array.push new @view.draw.Point point.x + @view.opts.tabWidth * (1 - @view.opts.tabSideWidth),
point.y + @view.opts.tabHeight
array.push new @view.draw.Point(point.x + @view.opts.tabWidth,
point.y)
mark: (style) ->
@view.registerMark @model.id
@markStyle = style
@focusAll()
unmark: -> @markStyle = null
# ## drawSelf
# Draw our path, with applied
# styles if necessary.
drawSelf: (style = {}) ->
# We might want to apply some
# temporary color changes,
# so store the old colors
oldFill = @path.style.fillColor
oldStroke = @path.style.strokeColor
if style.grayscale
# Change path color
if @path.style.fillColor isnt 'none'
@path.style.fillColor = avgColor @path.style.fillColor, 0.5, '#888'
if @path.style.strokeColor isnt 'none'
@path.style.strokeColor = avgColor @path.style.strokeColor, 0.5, '#888'
if style.selected
# Change path color
if @path.style.fillColor isnt 'none'
@path.style.fillColor = avgColor @path.style.fillColor, 0.7, '#00F'
if @path.style.strokeColor isnt 'none'
@path.style.strokeColor = avgColor @path.style.strokeColor, 0.7, '#00F'
@path.setMarkStyle @markStyle
@path.update()
if @model.buttons? then for {key} in @model.buttons
@buttonPaths[key].update()
@buttonGroups[key].update()
for element in [@buttonPaths[key], @buttonGroups[key], @buttonTexts[key]]
unless element in @activeElements # TODO unlikely but might be performance chokehold?
@activeElements.push element # Possibly replace activeElements with a more set-like structure.
# Unset all the things we changed
@path.style.fillColor = oldFill
@path.style.strokeColor = oldStroke
if @model.buttons? then for {key} in @model.buttons
if @buttonPaths[key].active
@buttonPaths[key].style.fillColor = oldFill
@buttonPaths[key].style.strokeColor = oldStroke
return null
# ## computeOwnDropArea
# By default, we will not have a
# drop area (not be droppable).
computeOwnDropArea: ->
@dropPoint = null
if @highlightArea?
@elements = @elements.filter (x) -> x isnt @highlightArea
@highlightArea.destroy()
@highlightArea = null
# ## shouldAddTab
# By default, we will ask
# not to have a tab.
shouldAddTab: NO
# # BlockViewNode
class BlockViewNode extends ContainerViewNode
constructor: ->
super
computeMinDimensions: ->
if @computedVersion is @model.version
return null
super
# Blocks have a shape including a lego nubby "tab", and so
# they need to be at least wide enough for tabWidth+tabOffset.
for size, i in @minDimensions
size.width = Math.max size.width,
@view.opts.tabWidth + @view.opts.tabOffset
size.width += @extraLeft
return null
shouldAddTab: ->
if @model.parent? and @view.hasViewNodeFor(@model.parent) and not
(@model.parent.type is 'document' and @model.parent.opts.roundedSingletons and
@model.start.prev is @model.parent.start and @model.end.next is @model.parent.end)
return @model.parent?.type isnt 'socket'
else
return not (@model.shape in [helper.MOSTLY_VALUE, helper.VALUE_ONLY])
computeOwnDropArea: ->
unless @model.parent?.type in ['indent', 'document']
@dropPoint = null
return
# Our drop area is a puzzle-piece shaped path
# of height opts.highlightAreaHeight and width
# equal to our last line width,
# positioned at the bottom of our last line.
if @carriageArrow is CARRIAGE_ARROW_INDENT
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
@dropPoint = new @view.draw.Point destinationBounds.x, destinationBounds.y
lastBoundsLeft = destinationBounds.x
lastBoundsRight = destinationBounds.right()
else if @carriageArrow is CARRIAGE_ARROW_SIDEALONG
parentViewNode = @view.getViewNodeFor @model.parent
destinationBounds = parentViewNode.bounds[1]
@dropPoint = new @view.draw.Point destinationBounds.x,
@bounds[@lineLength - 1].bottom() + @view.opts.padding
lastBoundsLeft = destinationBounds.x
lastBoundsRight = @bounds[@lineLength - 1].right()
else
@dropPoint = new @view.draw.Point @bounds[@lineLength - 1].x, @bounds[@lineLength - 1].bottom()
lastBoundsLeft = @bounds[@lineLength - 1].x
lastBoundsRight = @bounds[@lineLength - 1].right()
# Our highlight area is the a rectangle in the same place,
# with a height that can be given by a different option.
highlightAreaPoints = []
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft, @dropPoint.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft + @view.opts.bevelClip, @dropPoint.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBoundsLeft + @view.opts.tabOffset, @dropPoint.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsRight - @view.opts.bevelClip, @dropPoint.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsRight, @dropPoint.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsRight, @dropPoint.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBoundsRight - @view.opts.bevelClip, @dropPoint.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBoundsLeft + @view.opts.tabOffset, @dropPoint.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft + @view.opts.bevelClip, @dropPoint.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBoundsLeft, @dropPoint.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
# # SocketViewNode
class SocketViewNode extends ContainerViewNode
constructor: ->
super
if @view.opts.showDropdowns and @model.dropdown?
@dropdownElement ?= @view.draw.path([], false, {
fillColor: (if @view.opts.invert then DROP_TRIANGLE_INVERT_COLOR else DROP_TRIANGLE_COLOR),
cssClass: 'droplet-dropdown-arrow'
})
@dropdownElement.deactivate()
@dropdownElement.setParent @group
@elements.push @dropdownElement
@activeElements.push @dropdownElement
shouldAddTab: NO
isInvisibleSocket: ->
'' is @model.emptyString and @model.start?.next is @model.end
# ## computeDimensions (SocketViewNode)
# Sockets have a couple exceptions to normal dimension computation.
#
# 1. Sockets have minimum dimensions even if empty.
# 2. Sockets containing blocks mimic the block exactly.
computeMinDimensions: ->
# Use cache if possible.
if @computedVersion is @model.version
return null
super
@minDistanceToBase[0].above = Math.max(@minDistanceToBase[0].above,
@view.opts.textHeight + @view.opts.textPadding)
@minDistanceToBase[0].below = Math.max(@minDistanceToBase[0].below,
@view.opts.textPadding)
@minDimensions[0].height =
@minDistanceToBase[0].above + @minDistanceToBase[0].below
for dimension in @minDimensions
dimension.width = Math.max(dimension.width,
if @isInvisibleSocket()
@view.opts.invisibleSocketWidth
else
@view.opts.minSocketWidth)
if @model.hasDropdown() and @view.opts.showDropdowns
dimension.width += helper.DROPDOWN_ARROW_WIDTH
return null
# ## computeBoundingBoxX (SocketViewNode)
computeBoundingBoxX: (left, line) ->
super left, line, (
if @model.hasDropdown() and @view.opts.showDropdowns
helper.DROPDOWN_ARROW_WIDTH
else 0
)
# ## computeGlue
# Sockets have one exception to normal glue spacing computation:
# sockets containing a block should **not** add padding to
# the glue.
computeGlue: ->
# Use cache if possible
if @computedVersion is @model.version and
not @changedBoundingBox
return @glue
# Do not add padding to the glue
# if our child is a block.
if @model.start.next.type is 'blockStart'
view = @view.getViewNodeFor @model.start.next.container
@glue = view.computeGlue()
# Otherwise, decrement the glue version
# to force super to recompute,
# and call super.
else
super
# ## computeOwnPath (SocketViewNode)
# Again, exception: sockets containing block
# should mimic blocks exactly.
#
# Under normal circumstances this shouldn't
# actually be an issue, but if we decide
# to change the Block's path,
# the socket should not have stuff sticking out,
# and should hit-test properly.
computeOwnPath: ->
# Use cache if possible.
if @computedVersion is @model.version and
not @changedBoundingBox
return @path
@path.style.fillColor = if @view.opts.invert then '#333' else '#FFF'
if @model.start.next.type is 'blockStart'
@path.style.fillColor = 'none'
# Otherwise, call super.
else
super
# If the socket is empty, make it invisible except
# for mouseover
if '' is @model.emptyString and @model.start?.next is @model.end
@path.style.cssClass = 'droplet-socket-path droplet-empty-socket-path'
@path.style.fillColor = 'none'
else
@path.style.cssClass = 'droplet-socket-path'
return @path
# ## drawSelf (SocketViewNode)
drawSelf: (style = {}) ->
super
if @model.hasDropdown() and @view.opts.showDropdowns
@dropdownElement.setPoints([new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_PADDING,
@bounds[0].y + (@bounds[0].height - DROPDOWN_ARROW_HEIGHT) / 2),
new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_WIDTH - helper.DROPDOWN_ARROW_PADDING,
@bounds[0].y + (@bounds[0].height - DROPDOWN_ARROW_HEIGHT) / 2),
new @view.draw.Point(@bounds[0].x + helper.DROPDOWN_ARROW_WIDTH / 2,
@bounds[0].y + (@bounds[0].height + DROPDOWN_ARROW_HEIGHT) / 2)
])
@dropdownElement.update()
unless @dropdownElement in @activeElements
@activeElements.push @dropdownElement
else if @dropdownElement?
@activeElements = @activeElements.filter (x) -> x isnt @dropdownElement
@dropdownElement.deactivate()
# ## computeOwnDropArea (SocketViewNode)
# Socket drop areas are actually the same
# shape as the sockets themselves, which
# is different from most other
# things.
computeOwnDropArea: ->
if @model.start.next.type is 'blockStart'
@dropPoint = null
@highlightArea.deactivate()
else
@dropPoint = @bounds[0].upperLeftCorner()
@highlightArea.setPoints @path._points
@highlightArea.style.strokeColor = '#FF0'
@highlightArea.style.fillColor = 'none'
@highlightArea.style.lineWidth = @view.opts.highlightAreaHeight / 2
@highlightArea.update()
@highlightArea.deactivate()
# # IndentViewNode
class IndentViewNode extends ContainerViewNode
constructor: ->
super
@lastFirstChildren = []
@lastLastChildren = []
# ## computeOwnPath
# An Indent should also have no drawn
# or hit-tested path.
computeOwnPath: ->
# ## computeChildren
computeChildren: ->
super
unless arrayEq(@lineChildren[0], @lastFirstChildren) and
arrayEq(@lineChildren[@lineLength - 1], @lastLastChildren)
for childObj in @children
childView = @view.getViewNodeFor childObj.child
if childView.topLineSticksToBottom or childView.bottomLineSticksToTop
childView.invalidate = true
if childView.lineLength is 1
childView.topLineSticksToBottom =
childView.bottomLineSticksToTop = false
for childRef in @lineChildren[0]
childView = @view.getViewNodeFor(childRef.child)
unless childView.topLineSticksToBottom
childView.invalidate = true
childView.topLineSticksToBottom = true
for childRef in @lineChildren[@lineChildren.length - 1]
childView = @view.getViewNodeFor(childRef.child)
unless childView.bottomLineSticksToTop
childView.invalidate = true
childView.bottomLineSticksToTop = true
return @lineLength
# ## computeDimensions (IndentViewNode)
#
# Give width to any empty lines
# in the Indent.
computeMinDimensions: ->
super
for size, line in @minDimensions[1..] when size.width is 0
size.width = @view.opts.emptyLineWidth
# ## drawSelf
#
# Again, an Indent should draw nothing.
drawSelf: ->
# ## computeOwnDropArea
#
# Our drop area is a rectangle of
# height dropAreaHeight and a width
# equal to our first line width,
# positioned at the top of our firs tline
computeOwnDropArea: ->
lastBounds = new @view.draw.NoRectangle()
if @model.start.next.type is 'newline'
@dropPoint = @bounds[1].upperLeftCorner()
lastBounds.copy @bounds[1]
else
@dropPoint = @bounds[0].upperLeftCorner()
lastBounds.copy @bounds[0]
lastBounds.width = Math.max lastBounds.width, @view.opts.indentDropAreaMinWidth
# Our highlight area is the a rectangle in the same place,
# with a height that can be given by a different option.
highlightAreaPoints = []
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
# # DocumentViewNode
# Represents a Document. Draws little, but
# recurses.
class DocumentViewNode extends ContainerViewNode
constructor: -> super
# ## computeOwnPath
#
computeOwnPath: ->
# ## computeOwnDropArea
#
# Root documents
# can be dropped at their beginning.
computeOwnDropArea: ->
@dropPoint = @bounds[0].upperLeftCorner()
highlightAreaPoints = []
lastBounds = new @view.draw.NoRectangle()
lastBounds.copy @bounds[0]
lastBounds.width = Math.max lastBounds.width, @view.opts.indentDropAreaMinWidth
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
@addTabReverse highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y - @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y - @view.opts.highlightAreaHeight / 2 + @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right(), lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
highlightAreaPoints.push new @view.draw.Point lastBounds.right() - @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
@addTab highlightAreaPoints, new @view.draw.Point lastBounds.x + @view.opts.tabOffset, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x + @view.opts.bevelClip, lastBounds.y + @view.opts.highlightAreaHeight / 2
highlightAreaPoints.push new @view.draw.Point lastBounds.x, lastBounds.y + @view.opts.highlightAreaHeight / 2 - @view.opts.bevelClip
@highlightArea.setPoints highlightAreaPoints
@highlightArea.deactivate()
return null
# # TextViewNode
#
# TextViewNode does not extend ContainerViewNode.
# We contain a @view.draw.TextElement to measure
# bounding boxes and draw text.
class TextViewNode extends GenericViewNode
constructor: (@model, @view) ->
super
@textElement = @view.draw.text(
new @view.draw.Point(0, 0),
@model.value,
if @view.opts.invert then '#FFF' else '#000'
)
@textElement.destroy()
@elements.push @textElement
# ## computeChildren
#
# Text elements are one line
# and contain no children (and thus
# no multiline children, either)
computeChildren: ->
@multilineChildrenData = [NO_MULTILINE]
return @lineLength = 1
# ## computeMinDimensions (TextViewNode)
#
# Set our dimensions to the measured dimensinos
# of our text value.
computeMinDimensions: ->
if @computedVersion is @model.version
return null
@textElement.point = new @view.draw.Point 0, 0
@textElement.value = @model.value
height = @view.opts.textHeight
@minDimensions[0] = new @view.draw.Size(@textElement.bounds().width, height)
@minDistanceToBase[0] = {above: height, below: 0}
return null
# ## computeBoundingBox (x and y)
#
# Assign the position of our textElement
# to match our laid out bounding box position.
computeBoundingBoxX: (left, line) ->
@textElement.point.x = left; super
computeBoundingBoxY: (top, line) ->
@textElement.point.y = top; super
# ## drawSelf
#
# Draw the text element itself.
drawSelf: (style = {}, parent = null) ->
@textElement.update()
if style.noText
@textElement.deactivate()
else
@textElement.activate()
if parent?
@textElement.setParent parent
toRGB = (hex) ->
# Convert to 6-char hex if not already there
if hex.length is 4
hex = (c + c for c in hex).join('')[1..]
# Extract integers from hex
r = parseInt hex[1..2], 16
g = parseInt hex[3..4], 16
b = parseInt hex[5..6], 16
return [r, g, b]
zeroPad = (str, len) ->
if str.length < len
('0' for [str.length...len]).join('') + str
else
str
twoDigitHex = (n) -> zeroPad Math.round(n).toString(16), 2
toHex = (rgb) ->
return '#' + (twoDigitHex(k) for k in rgb).join ''
avgColor = (a, factor, b) ->
a = toRGB a
b = toRGB b
newRGB = (a[i] * factor + b[i] * (1 - factor) for k, i in a)
return toHex newRGB
dedupe = (path) ->
path = path.filter((x, i) ->
not x.equals(path[(i - 1) %% path.length])
)
path = path.filter((x, i) ->
not draw._collinear(path[(i - 1) %% path.length], x, path[(i + 1) %% path.length])
)
return path
|
[
{
"context": "ins[1].urn, peerId:config.logins[0].urn, peerIP: \"127.0.0.1\", peerPID: 1212, peerStatus:\"ready\", peerInbox:[{",
"end": 4015,
"score": 0.9996331334114075,
"start": 4006,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "ins[3].urn, peerId:config.logins[0].ur... | test/hTracker.coffee | fredpottier/hubiquitus | 2 | #
# * Copyright (c) Novedia Group 2012.
# *
# * This file is part of Hubiquitus
# *
# * 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.
# *
# * You should have received a copy of the MIT License along with Hubiquitus.
# * If not, see <http://opensource.org/licenses/mit-license.php>.
#
should = require("should")
config = require("./_config")
_ = require "underscore"
describe "hTracker", ->
hActor = undefined
hResultStatus = require("../lib/codes").hResultStatus
Tracker = require "../lib/actors/htracker"
describe "topology without channel", ->
before () ->
topology =
actor: config.logins[0].urn,
type: "hTracker"
children: []
properties:{}
hActor = new Tracker topology
after () ->
#hActor.h_tearDown()
hActor = null
it "should automatically add the trackchannel if not set", (done) ->
if hActor.topology.children[0].type == "hchannel"
done()
describe "other", ->
before () ->
topology =
actor: config.logins[0].urn,
type: "hTracker"
children: []
properties:
channel:
actor: "urn:localhost:trackChannel",
type: "hchannel",
method: "inproc",
properties:{}
hActor = new Tracker topology
hActor.send = (hMessage) ->
after () ->
hActor.h_tearDown()
hActor = null
describe "Peer-info", ->
it "should add peer when receive peer-info", (done) ->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"started", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(1)
done()
it "should remove peer when receive peer-info stopping", (done) ->
hActor.stopAlert = (actor)->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"stopped", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(0)
done()
it "should remove peer after 3 unreceived peer-info", (done) ->
hActor.touchDelay = 100
hActor.timeoutDelay = 300
hActor.stopAlert = (actor)->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"started", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(1)
setTimeout(=>
hActor.peers.length.should.be.equal(0)
done()
, 500)
describe "Peer-search", ->
before () ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"started", peerInbox:[]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"stopped", peerInbox:[{type:"socket_in", url:"url"}]}
]
it "should send outboundAdapter when the acteur is started and have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.should.be.an.instanceof(Object, null)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[1].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send NOT_AVAILABLE when the acteur is not started but not have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.INVALID_ATTR
hMessage.payload.result.should.be.equal("Actor not found")
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[3].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send NOT_AVAILABLE when the acteur is not starting and have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.INVALID_ATTR
hMessage.payload.result.should.be.equal("Actor not found")
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[5].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[1].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN with load balancing", (done) ->
@timeout(4000)
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
goodResult = [config.logins[1].urn, config.logins[3].urn, config.logins[5].urn]
result1 = 0
result2 = 0
result3 = 0
index = 0
index2 = 0
hActor.send = (hMessage) ->
index2++
hMessage.payload.should.have.property "status", hResultStatus.OK
goodResult.should.include(hMessage.payload.result.targetActorAid)
if hMessage.payload.result.targetActorAid is config.logins[1].urn
result1++
else if hMessage.payload.result.targetActorAid is config.logins[3].urn
result2++
else
result3++
if index2 is 20
result1.should.be.above(0)
result2.should.be.above(0)
result3.should.be.above(0)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
while index < 20
hActor.h_onMessageInternal search
index++
it "should send outboundAdapter when search actor with bareURN and same PID", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "192.12.12.12", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[1].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN and same host", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "192.12.12.12", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[5].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 4242, ip: "192.12.12.12"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN and other host", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "192.12.12.12", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
answer = [config.logins[1].urn, config.logins[3].urn, config.logins[5].urn]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
answer.should.include(hMessage.payload.result.targetActorAid)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 4242, ip: "127.12.12.12"}})
search.timeout = 1000
hActor.h_onMessageInternal search | 69455 | #
# * Copyright (c) Novedia Group 2012.
# *
# * This file is part of Hubiquitus
# *
# * 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.
# *
# * You should have received a copy of the MIT License along with Hubiquitus.
# * If not, see <http://opensource.org/licenses/mit-license.php>.
#
should = require("should")
config = require("./_config")
_ = require "underscore"
describe "hTracker", ->
hActor = undefined
hResultStatus = require("../lib/codes").hResultStatus
Tracker = require "../lib/actors/htracker"
describe "topology without channel", ->
before () ->
topology =
actor: config.logins[0].urn,
type: "hTracker"
children: []
properties:{}
hActor = new Tracker topology
after () ->
#hActor.h_tearDown()
hActor = null
it "should automatically add the trackchannel if not set", (done) ->
if hActor.topology.children[0].type == "hchannel"
done()
describe "other", ->
before () ->
topology =
actor: config.logins[0].urn,
type: "hTracker"
children: []
properties:
channel:
actor: "urn:localhost:trackChannel",
type: "hchannel",
method: "inproc",
properties:{}
hActor = new Tracker topology
hActor.send = (hMessage) ->
after () ->
hActor.h_tearDown()
hActor = null
describe "Peer-info", ->
it "should add peer when receive peer-info", (done) ->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"started", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(1)
done()
it "should remove peer when receive peer-info stopping", (done) ->
hActor.stopAlert = (actor)->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"stopped", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(0)
done()
it "should remove peer after 3 unreceived peer-info", (done) ->
hActor.touchDelay = 100
hActor.timeoutDelay = 300
hActor.stopAlert = (actor)->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"started", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(1)
setTimeout(=>
hActor.peers.length.should.be.equal(0)
done()
, 500)
describe "Peer-search", ->
before () ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"started", peerInbox:[]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"stopped", peerInbox:[{type:"socket_in", url:"url"}]}
]
it "should send outboundAdapter when the acteur is started and have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.should.be.an.instanceof(Object, null)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[1].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send NOT_AVAILABLE when the acteur is not started but not have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.INVALID_ATTR
hMessage.payload.result.should.be.equal("Actor not found")
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[3].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send NOT_AVAILABLE when the acteur is not starting and have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.INVALID_ATTR
hMessage.payload.result.should.be.equal("Actor not found")
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[5].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[1].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN with load balancing", (done) ->
@timeout(4000)
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
goodResult = [config.logins[1].urn, config.logins[3].urn, config.logins[5].urn]
result1 = 0
result2 = 0
result3 = 0
index = 0
index2 = 0
hActor.send = (hMessage) ->
index2++
hMessage.payload.should.have.property "status", hResultStatus.OK
goodResult.should.include(hMessage.payload.result.targetActorAid)
if hMessage.payload.result.targetActorAid is config.logins[1].urn
result1++
else if hMessage.payload.result.targetActorAid is config.logins[3].urn
result2++
else
result3++
if index2 is 20
result1.should.be.above(0)
result2.should.be.above(0)
result3.should.be.above(0)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
while index < 20
hActor.h_onMessageInternal search
index++
it "should send outboundAdapter when search actor with bareURN and same PID", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "172.16.17.32", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[1].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN and same host", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "172.16.17.32", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[5].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 4242, ip: "172.16.17.32"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN and other host", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "172.16.17.32", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
answer = [config.logins[1].urn, config.logins[3].urn, config.logins[5].urn]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
answer.should.include(hMessage.payload.result.targetActorAid)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 4242, ip: "127.12.12.12"}})
search.timeout = 1000
hActor.h_onMessageInternal search | true | #
# * Copyright (c) Novedia Group 2012.
# *
# * This file is part of Hubiquitus
# *
# * 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.
# *
# * You should have received a copy of the MIT License along with Hubiquitus.
# * If not, see <http://opensource.org/licenses/mit-license.php>.
#
should = require("should")
config = require("./_config")
_ = require "underscore"
describe "hTracker", ->
hActor = undefined
hResultStatus = require("../lib/codes").hResultStatus
Tracker = require "../lib/actors/htracker"
describe "topology without channel", ->
before () ->
topology =
actor: config.logins[0].urn,
type: "hTracker"
children: []
properties:{}
hActor = new Tracker topology
after () ->
#hActor.h_tearDown()
hActor = null
it "should automatically add the trackchannel if not set", (done) ->
if hActor.topology.children[0].type == "hchannel"
done()
describe "other", ->
before () ->
topology =
actor: config.logins[0].urn,
type: "hTracker"
children: []
properties:
channel:
actor: "urn:localhost:trackChannel",
type: "hchannel",
method: "inproc",
properties:{}
hActor = new Tracker topology
hActor.send = (hMessage) ->
after () ->
hActor.h_tearDown()
hActor = null
describe "Peer-info", ->
it "should add peer when receive peer-info", (done) ->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"started", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(1)
done()
it "should remove peer when receive peer-info stopping", (done) ->
hActor.stopAlert = (actor)->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"stopped", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(0)
done()
it "should remove peer after 3 unreceived peer-info", (done) ->
hActor.touchDelay = 100
hActor.timeoutDelay = 300
hActor.stopAlert = (actor)->
info = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-info", params:{peerType:"hactor", peerId:config.logins[2].urn, peerStatus:"started", peerInbox:[]}})
hActor.h_onMessageInternal info
hActor.peers.length.should.be.equal(1)
setTimeout(=>
hActor.peers.length.should.be.equal(0)
done()
, 500)
describe "Peer-search", ->
before () ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"started", peerInbox:[]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"stopped", peerInbox:[{type:"socket_in", url:"url"}]}
]
it "should send outboundAdapter when the acteur is started and have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.should.be.an.instanceof(Object, null)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[1].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send NOT_AVAILABLE when the acteur is not started but not have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.INVALID_ATTR
hMessage.payload.result.should.be.equal("Actor not found")
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[3].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send NOT_AVAILABLE when the acteur is not starting and have socket_in adapter", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.INVALID_ATTR
hMessage.payload.result.should.be.equal("Actor not found")
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[5].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN", (done) ->
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[1].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN with load balancing", (done) ->
@timeout(4000)
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
goodResult = [config.logins[1].urn, config.logins[3].urn, config.logins[5].urn]
result1 = 0
result2 = 0
result3 = 0
index = 0
index2 = 0
hActor.send = (hMessage) ->
index2++
hMessage.payload.should.have.property "status", hResultStatus.OK
goodResult.should.include(hMessage.payload.result.targetActorAid)
if hMessage.payload.result.targetActorAid is config.logins[1].urn
result1++
else if hMessage.payload.result.targetActorAid is config.logins[3].urn
result2++
else
result3++
if index2 is 20
result1.should.be.above(0)
result2.should.be.above(0)
result3.should.be.above(0)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
while index < 20
hActor.h_onMessageInternal search
index++
it "should send outboundAdapter when search actor with bareURN and same PID", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "PI:IP_ADDRESS:172.16.17.32END_PI", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[1].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 1212, ip: "127.0.0.1"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN and same host", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "PI:IP_ADDRESS:172.16.17.32END_PI", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
hMessage.payload.result.targetActorAid.should.be.equal(config.logins[5].urn)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 4242, ip: "PI:IP_ADDRESS:172.16.17.32END_PI"}})
search.timeout = 1000
hActor.h_onMessageInternal search
it "should send outboundAdapter when search actor with bareURN and other host", (done) ->
hActor.peers = [
{peerType:"hactor", peerFullId:config.logins[1].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[3].urn, peerId:config.logins[0].urn, peerIP: "127.0.0.1", peerPID: 2121, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]},
{peerType:"hactor", peerFullId:config.logins[5].urn, peerId:config.logins[0].urn, peerIP: "PI:IP_ADDRESS:172.16.17.32END_PI", peerPID: 1212, peerStatus:"ready", peerInbox:[{type:"socket_in", url:"url"}]}
]
answer = [config.logins[1].urn, config.logins[3].urn, config.logins[5].urn]
hActor.send = (hMessage) ->
hMessage.payload.should.have.property "status", hResultStatus.OK
answer.should.include(hMessage.payload.result.targetActorAid)
done()
search = config.makeHMessage(hActor.actor, config.logins[3].urn, "hSignal", {name: "peer-search", params:{actor:config.logins[0].urn, pid: 4242, ip: "127.12.12.12"}})
search.timeout = 1000
hActor.h_onMessageInternal search |
[
{
"context": "jector](http://neocotic.com/injector)\n#\n# (c) 2014 Alasdair Mercer\n#\n# Freely distributable under the MIT license\n\n#",
"end": 71,
"score": 0.9998677372932434,
"start": 56,
"tag": "NAME",
"value": "Alasdair Mercer"
}
] | src/coffee/injector.coffee | SlinkySalmon633/injector-chrome | 33 | # [Injector](http://neocotic.com/injector)
#
# (c) 2014 Alasdair Mercer
#
# Freely distributable under the MIT license
# Injector
# --------
# Primary global namespace.
Injector = window.Injector = {}
# Retrieve the value of the given `property` from the "parent" of the context class.
#
# If that value is a function, then invoke it with the additional `args` and retrieve the return
# value of that call instead.
getSuper = (property, args...) ->
result = @constructor.__super__[property]
if _.isFunction(result) then result.apply(@, args) else result
# Setup the Chrome storage for the specified `model` (may also be a collection) based on the
# `storage` property, if it exists.
setupStorage = (model) ->
{name, type} = model.storage ? {}
if name and type
model.chromeStorage = new Backbone.ChromeStorage(name, type)
# Model
# -----
# Base model to be used within our application.
Model = Injector.Model = Backbone.Model.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom model initialization.
initialize: ->
setupStorage(@)
@init(arguments...)
# Restore the default attribute values, where possible.
restoreDefaults: (options) ->
attrs = _.extend({}, _.result(@, 'defaults'))
@set(attrs, options)
# Allow models to access "parent" properties easily.
super: getSuper
}
# The identifier used by single models.
singletonId = 'singleton'
# A singleton model where implementations should only have one persisted instance.
SingletonModel = Injector.SingletonModel = Injector.Model.extend {
# Override `initialize` to set the singleton identifier.
initialize: (attributes, options) ->
@set(@idAttribute, singletonId, options)
Injector.Model::initialize.apply(@, arguments)
}, {
# Retrieve a singleton instance of the model.
fetch: (callback) ->
model = new @()
model.fetch().then ->
callback(model)
}
# Collection
# ----------
# Base collection to be used within our application.
Collection = Injector.Collection = Backbone.Collection.extend {
# The default model for a collection. This should be overridden in most cases.
model: Model
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom collection initialization.
initialize: ->
setupStorage(@)
@init(arguments...)
# Allow collections to access "parent" properties easily.
super: getSuper
}
# View
# ----
# Base view to be used within our application.
View = Injector.View = Backbone.View.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom view initialization.
initialize: (@options) ->
@init(arguments...)
# Indicate whether or not this view has an underlying collection associated with it.
hasCollection: ->
@collection?
# Indicate whether or not this view has an underlying model associated with it.
hasModel: ->
@model?
# Allow views to access "parent" properties easily.
super: getSuper
}
# Router
# ------
# Base router to be used within our application.
Router = Injector.Router = Backbone.Router.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom model initialization.
initialize: ->
@init(arguments...)
# Allow routers to access "parent" properties easily.
super: getSuper
}
# History
# -------
# Base history implementation to be used within our application.
History = Injector.History = Backbone.History.extend
# Allow history implementations to access "parent" properties easily.
super: getSuper
| 154782 | # [Injector](http://neocotic.com/injector)
#
# (c) 2014 <NAME>
#
# Freely distributable under the MIT license
# Injector
# --------
# Primary global namespace.
Injector = window.Injector = {}
# Retrieve the value of the given `property` from the "parent" of the context class.
#
# If that value is a function, then invoke it with the additional `args` and retrieve the return
# value of that call instead.
getSuper = (property, args...) ->
result = @constructor.__super__[property]
if _.isFunction(result) then result.apply(@, args) else result
# Setup the Chrome storage for the specified `model` (may also be a collection) based on the
# `storage` property, if it exists.
setupStorage = (model) ->
{name, type} = model.storage ? {}
if name and type
model.chromeStorage = new Backbone.ChromeStorage(name, type)
# Model
# -----
# Base model to be used within our application.
Model = Injector.Model = Backbone.Model.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom model initialization.
initialize: ->
setupStorage(@)
@init(arguments...)
# Restore the default attribute values, where possible.
restoreDefaults: (options) ->
attrs = _.extend({}, _.result(@, 'defaults'))
@set(attrs, options)
# Allow models to access "parent" properties easily.
super: getSuper
}
# The identifier used by single models.
singletonId = 'singleton'
# A singleton model where implementations should only have one persisted instance.
SingletonModel = Injector.SingletonModel = Injector.Model.extend {
# Override `initialize` to set the singleton identifier.
initialize: (attributes, options) ->
@set(@idAttribute, singletonId, options)
Injector.Model::initialize.apply(@, arguments)
}, {
# Retrieve a singleton instance of the model.
fetch: (callback) ->
model = new @()
model.fetch().then ->
callback(model)
}
# Collection
# ----------
# Base collection to be used within our application.
Collection = Injector.Collection = Backbone.Collection.extend {
# The default model for a collection. This should be overridden in most cases.
model: Model
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom collection initialization.
initialize: ->
setupStorage(@)
@init(arguments...)
# Allow collections to access "parent" properties easily.
super: getSuper
}
# View
# ----
# Base view to be used within our application.
View = Injector.View = Backbone.View.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom view initialization.
initialize: (@options) ->
@init(arguments...)
# Indicate whether or not this view has an underlying collection associated with it.
hasCollection: ->
@collection?
# Indicate whether or not this view has an underlying model associated with it.
hasModel: ->
@model?
# Allow views to access "parent" properties easily.
super: getSuper
}
# Router
# ------
# Base router to be used within our application.
Router = Injector.Router = Backbone.Router.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom model initialization.
initialize: ->
@init(arguments...)
# Allow routers to access "parent" properties easily.
super: getSuper
}
# History
# -------
# Base history implementation to be used within our application.
History = Injector.History = Backbone.History.extend
# Allow history implementations to access "parent" properties easily.
super: getSuper
| true | # [Injector](http://neocotic.com/injector)
#
# (c) 2014 PI:NAME:<NAME>END_PI
#
# Freely distributable under the MIT license
# Injector
# --------
# Primary global namespace.
Injector = window.Injector = {}
# Retrieve the value of the given `property` from the "parent" of the context class.
#
# If that value is a function, then invoke it with the additional `args` and retrieve the return
# value of that call instead.
getSuper = (property, args...) ->
result = @constructor.__super__[property]
if _.isFunction(result) then result.apply(@, args) else result
# Setup the Chrome storage for the specified `model` (may also be a collection) based on the
# `storage` property, if it exists.
setupStorage = (model) ->
{name, type} = model.storage ? {}
if name and type
model.chromeStorage = new Backbone.ChromeStorage(name, type)
# Model
# -----
# Base model to be used within our application.
Model = Injector.Model = Backbone.Model.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom model initialization.
initialize: ->
setupStorage(@)
@init(arguments...)
# Restore the default attribute values, where possible.
restoreDefaults: (options) ->
attrs = _.extend({}, _.result(@, 'defaults'))
@set(attrs, options)
# Allow models to access "parent" properties easily.
super: getSuper
}
# The identifier used by single models.
singletonId = 'singleton'
# A singleton model where implementations should only have one persisted instance.
SingletonModel = Injector.SingletonModel = Injector.Model.extend {
# Override `initialize` to set the singleton identifier.
initialize: (attributes, options) ->
@set(@idAttribute, singletonId, options)
Injector.Model::initialize.apply(@, arguments)
}, {
# Retrieve a singleton instance of the model.
fetch: (callback) ->
model = new @()
model.fetch().then ->
callback(model)
}
# Collection
# ----------
# Base collection to be used within our application.
Collection = Injector.Collection = Backbone.Collection.extend {
# The default model for a collection. This should be overridden in most cases.
model: Model
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom collection initialization.
initialize: ->
setupStorage(@)
@init(arguments...)
# Allow collections to access "parent" properties easily.
super: getSuper
}
# View
# ----
# Base view to be used within our application.
View = Injector.View = Backbone.View.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom view initialization.
initialize: (@options) ->
@init(arguments...)
# Indicate whether or not this view has an underlying collection associated with it.
hasCollection: ->
@collection?
# Indicate whether or not this view has an underlying model associated with it.
hasModel: ->
@model?
# Allow views to access "parent" properties easily.
super: getSuper
}
# Router
# ------
# Base router to be used within our application.
Router = Injector.Router = Backbone.Router.extend {
# Called internally by `initialize`. This should be overridden for custom initialization logic.
init: ->
# Override `initialize` to hook in our own custom model initialization.
initialize: ->
@init(arguments...)
# Allow routers to access "parent" properties easily.
super: getSuper
}
# History
# -------
# Base history implementation to be used within our application.
History = Injector.History = Backbone.History.extend
# Allow history implementations to access "parent" properties easily.
super: getSuper
|
[
{
"context": " doc = new CRDT.Document\n doc.at('key').set \"kitty\"\n deepEqual doc.at('key').get(), \"kitty\"\n doc.a",
"end": 806,
"score": 0.6162673830986023,
"start": 804,
"tag": "KEY",
"value": "ty"
}
] | test/crdt/document.js.coffee | collin/crdt | 1 | module "CRDT.Document"
test "opens a subdoc", ->
doc = new CRDT.Document
sub = doc.at "path"
deepEqual sub.path, ["path"]
test "set text value", ->
doc = new CRDT.Document
doc.at('key').set "KEY"
deepEqual doc.at('key').get(), "KEY"
test "set numeric value", ->
doc = new CRDT.Document
doc.at('key').set 44
deepEqual doc.at('key').get(), 44
test "set bolean value", ->
doc = new CRDT.Document
doc.at('key').set true
deepEqual doc.at('key').get(), true
test "set null value", ->
doc = new CRDT.Document
doc.at('key').set null
deepEqual doc.at('key').get(), null
test "set undefined value", ->
doc = new CRDT.Document
doc.at('key').set undefined
deepEqual doc.at('key').get(), undefined
test "overwrite value", ->
doc = new CRDT.Document
doc.at('key').set "kitty"
deepEqual doc.at('key').get(), "kitty"
doc.at('key').set "doggy"
deepEqual doc.at('key').get(), "doggy"
test "set an array value", ->
doc = new CRDT.Document
doc.at('list').set []
deepEqual doc.at('list').get(), []
test "set an array value with data inside", ->
doc = new CRDT.Document
doc.at('list').set ["item"]
deepEqual doc.at('list').get(), ["item"]
test "set an array with an array inside", ->
doc = new CRDT.Document
doc.at('list').set ["item", ["inception?"]]
deepEqual doc.at('list').get(), ["item", ["inception?"]]
test "get at an array index", ->
doc = new CRDT.Document
doc.at('list').set [0, 1, 2, 3, 4]
deepEqual doc.at('list', 3).get(), 3
test "push onto an array", ->
doc = new CRDT.Document
doc.at('list').set []
doc.at('list').push 33
deepEqual doc.at('list').get(), [33]
test "remove from array", ->
doc = new CRDT.Document
doc.at('list').set [0, 1, 2, 3, 4]
doc.at('list', 3).remove()
deepEqual doc.at('list').get(), [0, 1, 2, 4]
test "set a Hash value", ->
doc = new CRDT.Document
doc.at('o').set {}
deepEqual doc.at('o').get(), {}
complex =
key: "value"
list: ["some", ["lists"]]
crazy: [
"a crazy set of"
["values", {with: ["so much", [{going:"on"}]]}]
]
test "set a complex hash value", ->
doc = new CRDT.Document
doc.at('o').set complex
deepEqual doc.at('o').get(), complex
test "read a complex hash value", ->
doc = new CRDT.Document
doc.at('o').set complex
subdoc = doc.at('o', 'crazy', 1, 1, 'with', 1, 0)
deepEqual subdoc.get(), {going:"on"}
deepEqual doc.at('o', 'crazy', 1, 1).get(), {with: ["so much", [{going:"on"}]]}
# test "at", ->
# doc = new CRDT.Document
module "CRDT.SubDoc", ->
test "opens a subdoc", ->
doc = new CRDT.Document
sub = doc.at("path").at(22)
deepEqual sub.path, ["path", 22]
| 183972 | module "CRDT.Document"
test "opens a subdoc", ->
doc = new CRDT.Document
sub = doc.at "path"
deepEqual sub.path, ["path"]
test "set text value", ->
doc = new CRDT.Document
doc.at('key').set "KEY"
deepEqual doc.at('key').get(), "KEY"
test "set numeric value", ->
doc = new CRDT.Document
doc.at('key').set 44
deepEqual doc.at('key').get(), 44
test "set bolean value", ->
doc = new CRDT.Document
doc.at('key').set true
deepEqual doc.at('key').get(), true
test "set null value", ->
doc = new CRDT.Document
doc.at('key').set null
deepEqual doc.at('key').get(), null
test "set undefined value", ->
doc = new CRDT.Document
doc.at('key').set undefined
deepEqual doc.at('key').get(), undefined
test "overwrite value", ->
doc = new CRDT.Document
doc.at('key').set "kit<KEY>"
deepEqual doc.at('key').get(), "kitty"
doc.at('key').set "doggy"
deepEqual doc.at('key').get(), "doggy"
test "set an array value", ->
doc = new CRDT.Document
doc.at('list').set []
deepEqual doc.at('list').get(), []
test "set an array value with data inside", ->
doc = new CRDT.Document
doc.at('list').set ["item"]
deepEqual doc.at('list').get(), ["item"]
test "set an array with an array inside", ->
doc = new CRDT.Document
doc.at('list').set ["item", ["inception?"]]
deepEqual doc.at('list').get(), ["item", ["inception?"]]
test "get at an array index", ->
doc = new CRDT.Document
doc.at('list').set [0, 1, 2, 3, 4]
deepEqual doc.at('list', 3).get(), 3
test "push onto an array", ->
doc = new CRDT.Document
doc.at('list').set []
doc.at('list').push 33
deepEqual doc.at('list').get(), [33]
test "remove from array", ->
doc = new CRDT.Document
doc.at('list').set [0, 1, 2, 3, 4]
doc.at('list', 3).remove()
deepEqual doc.at('list').get(), [0, 1, 2, 4]
test "set a Hash value", ->
doc = new CRDT.Document
doc.at('o').set {}
deepEqual doc.at('o').get(), {}
complex =
key: "value"
list: ["some", ["lists"]]
crazy: [
"a crazy set of"
["values", {with: ["so much", [{going:"on"}]]}]
]
test "set a complex hash value", ->
doc = new CRDT.Document
doc.at('o').set complex
deepEqual doc.at('o').get(), complex
test "read a complex hash value", ->
doc = new CRDT.Document
doc.at('o').set complex
subdoc = doc.at('o', 'crazy', 1, 1, 'with', 1, 0)
deepEqual subdoc.get(), {going:"on"}
deepEqual doc.at('o', 'crazy', 1, 1).get(), {with: ["so much", [{going:"on"}]]}
# test "at", ->
# doc = new CRDT.Document
module "CRDT.SubDoc", ->
test "opens a subdoc", ->
doc = new CRDT.Document
sub = doc.at("path").at(22)
deepEqual sub.path, ["path", 22]
| true | module "CRDT.Document"
test "opens a subdoc", ->
doc = new CRDT.Document
sub = doc.at "path"
deepEqual sub.path, ["path"]
test "set text value", ->
doc = new CRDT.Document
doc.at('key').set "KEY"
deepEqual doc.at('key').get(), "KEY"
test "set numeric value", ->
doc = new CRDT.Document
doc.at('key').set 44
deepEqual doc.at('key').get(), 44
test "set bolean value", ->
doc = new CRDT.Document
doc.at('key').set true
deepEqual doc.at('key').get(), true
test "set null value", ->
doc = new CRDT.Document
doc.at('key').set null
deepEqual doc.at('key').get(), null
test "set undefined value", ->
doc = new CRDT.Document
doc.at('key').set undefined
deepEqual doc.at('key').get(), undefined
test "overwrite value", ->
doc = new CRDT.Document
doc.at('key').set "kitPI:KEY:<KEY>END_PI"
deepEqual doc.at('key').get(), "kitty"
doc.at('key').set "doggy"
deepEqual doc.at('key').get(), "doggy"
test "set an array value", ->
doc = new CRDT.Document
doc.at('list').set []
deepEqual doc.at('list').get(), []
test "set an array value with data inside", ->
doc = new CRDT.Document
doc.at('list').set ["item"]
deepEqual doc.at('list').get(), ["item"]
test "set an array with an array inside", ->
doc = new CRDT.Document
doc.at('list').set ["item", ["inception?"]]
deepEqual doc.at('list').get(), ["item", ["inception?"]]
test "get at an array index", ->
doc = new CRDT.Document
doc.at('list').set [0, 1, 2, 3, 4]
deepEqual doc.at('list', 3).get(), 3
test "push onto an array", ->
doc = new CRDT.Document
doc.at('list').set []
doc.at('list').push 33
deepEqual doc.at('list').get(), [33]
test "remove from array", ->
doc = new CRDT.Document
doc.at('list').set [0, 1, 2, 3, 4]
doc.at('list', 3).remove()
deepEqual doc.at('list').get(), [0, 1, 2, 4]
test "set a Hash value", ->
doc = new CRDT.Document
doc.at('o').set {}
deepEqual doc.at('o').get(), {}
complex =
key: "value"
list: ["some", ["lists"]]
crazy: [
"a crazy set of"
["values", {with: ["so much", [{going:"on"}]]}]
]
test "set a complex hash value", ->
doc = new CRDT.Document
doc.at('o').set complex
deepEqual doc.at('o').get(), complex
test "read a complex hash value", ->
doc = new CRDT.Document
doc.at('o').set complex
subdoc = doc.at('o', 'crazy', 1, 1, 'with', 1, 0)
deepEqual subdoc.get(), {going:"on"}
deepEqual doc.at('o', 'crazy', 1, 1).get(), {with: ["so much", [{going:"on"}]]}
# test "at", ->
# doc = new CRDT.Document
module "CRDT.SubDoc", ->
test "opens a subdoc", ->
doc = new CRDT.Document
sub = doc.at("path").at(22)
deepEqual sub.path, ["path", 22]
|
[
{
"context": "n if ignoreRouterSettingChange\r\n\r\n\tif arg.key is \"routerContextPath\" or arg.key is \"defaultRouterPath\"\r\n\t\tpath = cola",
"end": 431,
"score": 0.7664515972137451,
"start": 414,
"tag": "KEY",
"value": "routerContextPath"
},
{
"context": "\tif arg.key is \"rout... | src/core/router.coffee | homeant/cola-ui | 90 | routerRegistry = null
currentRoutePath = null
currentRouter = null
trimPath = (path)->
if path
if path.charCodeAt(0) isnt 47 # `/`
path = "/" + path
if path.charCodeAt(path.length - 1) == 47 # `/`
path = path.substring(0, path.length - 1)
return path || ""
ignoreRouterSettingChange = false
cola.on("settingChange", (self, arg)->
return if ignoreRouterSettingChange
if arg.key is "routerContextPath" or arg.key is "defaultRouterPath"
path = cola.setting(arg.key)
tPath = trimPath(path)
if tPath isnt path
ignoreRouterSettingChange = true
cola.setting(arg.key, tPath)
ignoreRouterSettingChange = false
return
)
# router.path
# router.name
# router.redirectTo
# router.enter
# router.leave
# router.title
# router.jsUrl
# router.templateUrl
# router.target
# router.parentModel
cola.route = (path, router)->
routerRegistry ?= new cola.util.KeyedArray()
if typeof router == "function"
router =
enter: router
router.path = path = trimPath(path)
path = path.slice(1)
if not router.name
name = path or cola.constants.DEFAULT_PATH
parts = name.split(/[\/\-]/)
nameParts = []
for part, i in parts
if not part or part.charCodeAt(0) == 58 # `:`
continue
nameParts.push(if nameParts.length > 0 then cola.util.capitalize(part) else part)
router.name = nameParts.join("");
router.pathParts = pathParts = []
if path
hasVariable = false
for part in path.split("/")
if part.charCodeAt(0) == 58 # `:`
optional = part.charCodeAt(part.length - 1) == 63 # `?`
if optional
variable = part.substring(1, part.length - 1)
else
variable = part.substring(1)
hasVariable = true
pathParts.push({
variable: variable
optional: optional
})
else
pathParts.push(part)
router.hasVariable = hasVariable
routerRegistry.add(router.path, router)
return router
cola.getCurrentRoutePath = ()->
return currentRoutePath
cola.getCurrentRouter = ()->
return currentRouter
cola.setRoutePath = (path, replace, alwaysNotify)->
if path and path.charCodeAt(0) == 35 # `#`
routerMode = "hash"
path = path.substring(1)
else
routerMode = cola.setting("routerMode") or "hash"
if routerMode is "hash"
if path.charCodeAt(0) != 47 # `/`
path = "/" + path
window.location.hash = path if window.location.hash != path
if alwaysNotify
_onHashChange()
else
pathRoot = cola.setting("routerContextPath")
if pathRoot and path.charCodeAt(0) is 47 # `/`
realPath = cola.util.path(pathRoot, path)
else
realPath = path
pathname = realPath
i = pathname.indexOf("?")
if i >= 0
pathname = pathname.substring(0, i)
i = pathname.indexOf("#")
if i >= 0
pathname = pathname.substring(0, i)
if location.pathname isnt pathname
if replace
window.history.replaceState({
path: realPath
}, null, realPath)
else
window.history.pushState({
path: realPath
}, null, realPath)
if location.pathname isnt pathname # 处理 ../ ./ 及 path前缀 等情况
realPath = location.pathname + location.search + location.hash
if pathRoot and realPath.indexOf(pathRoot) is 0
path = realPath.substring(pathRoot.length)
window.history.replaceState({
path: realPath
originPath: path
}, null, realPath)
_onStateChange(path)
else if alwaysNotify
_onStateChange(pathname)
return
_findRouter = (path)->
return null unless routerRegistry
path ?= cola.setting("defaultRouterPath")
path = trimPath(path).slice(1)
pathParts = if path then path.split(/[\/\?\#]/) else []
for router in routerRegistry.elements
defPathParts = router.pathParts
gap = defPathParts.length - pathParts.length
unless gap == 0 or gap == 1 and defPathParts.length > 0 and defPathParts[defPathParts.length - 1].optional then continue
matching = true
param = {}
for defPart, i in defPathParts
if typeof defPart == "string"
if defPart != pathParts[i]
matching = false
break
else
if i >= pathParts.length and not defPart.optional
matching = false
break
param[defPart.variable] = pathParts[i]
if matching then break
if matching
router.param = param
return router
else
return null
cola.createRouterModel = (router)->
if router.parentModel instanceof cola.Scope
parentModel = router.parentModel
else
parentModelName = router.parentModel or cola.constants.DEFAULT_PATH
parentModel = cola.model(parentModelName)
if !parentModel then throw new cola.Exception("Parent Model \"#{parentModelName}\" is undefined.")
return new cola.Model(router.name, parentModel)
_switchRouter = (router, path)->
if router.redirectTo
cola.setRoutePath(router.redirectTo)
return
eventArg = {
path: path
prev: currentRouter
next: router
}
if cola.fire("beforeRouterSwitch", cola, eventArg) is false then return
if currentRouter
currentRouter.leave?(currentRouter)
if currentRouter.targetDom
cola.unloadSubView(currentRouter.targetDom, {
cssUrl: currentRouter.cssUrl
})
oldModel = cola.util.removeUserData(currentRouter.targetDom, "_model")
oldModel?.destroy()
if router.templateUrl
if router.target
if router.target.nodeType
target = router.target
else
target = $(router.target)[0]
if !target
target = document.getElementsByClassName(cola.constants.VIEW_PORT_CLASS)[0]
if !target
target = document.getElementsByClassName(cola.constants.VIEW_CLASS)[0]
if !target
target = document.body
router.targetDom = target
$fly(target).empty()
currentRouter = router
if router.templateUrl
model = cola.createRouterModel(router)
eventArg.nextModel = model
cola.util.userData(router.targetDom, "_model", model)
cola.loadSubView(router.targetDom, {
model: model
htmlUrl: router.templateUrl
jsUrl: router.jsUrl
cssUrl: router.cssUrl
data: router.data
param: router.param
callback: ()->
router.enter?(router, model)
document.title = router.title if router.title
return
})
else
router.enter?(router, null)
document.title = router.title if router.title
cola.fire("routerSwitch", cola, eventArg)
return
_getHashPath = ()->
path = location.hash
path = path.substring(1) if path
if path?.charCodeAt(0) == 33 # `!`
path = path.substring(1)
if path.indexOf("?") >= 0
path = path.substring(0, path.indexOf("?"))
return trimPath(path)
_onHashChange = ()->
return if (cola.setting("routerMode") or "hash") isnt "hash"
path = _getHashPath()
return if path is currentRoutePath
currentRoutePath = path
router = _findRouter(path)
_switchRouter(router, path) if router
return
_onStateChange = (path)->
return if cola.setting("routerMode") isnt "state"
path = trimPath(path)
i = path.indexOf("#")
if i > -1
path = path.substring(i + 1)
if path.charCodeAt(0) is 47 # `/`
routerContextPath = cola.setting("routerContextPath")
if routerContextPath and path.indexOf(routerContextPath) is 0
path = path.slice(routerContextPath.length)
return if path is currentRoutePath
currentRoutePath = path
i = path.indexOf("?")
if i > -1
path = path.substring(0, i)
router = _findRouter(path)
_switchRouter(router, path) if router
return
$ ()->
setTimeout(()->
$fly(window).on("hashchange", _onHashChange).on("popstate", ()->
if not location.hash
state = window.history.state
_onStateChange(state?.path or (location.pathname + location.search + location.hash))
return
)
$(document.body).delegate("a.state", "click", ()->
href = @getAttribute("href")
if href
target = @getAttribute("target")
if not target or target is "_self"
cola.setRoutePath(href)
return false
)
path = _getHashPath()
if path
router = _findRouter(path)
if router then _switchRouter(router, path)
else
router = _findRouter(null)
if router
cola.setRoutePath((router.redirectTo or cola.setting("defaultRouterPath") or "") + location.search, true, true)
return
, 0)
return | 163857 | routerRegistry = null
currentRoutePath = null
currentRouter = null
trimPath = (path)->
if path
if path.charCodeAt(0) isnt 47 # `/`
path = "/" + path
if path.charCodeAt(path.length - 1) == 47 # `/`
path = path.substring(0, path.length - 1)
return path || ""
ignoreRouterSettingChange = false
cola.on("settingChange", (self, arg)->
return if ignoreRouterSettingChange
if arg.key is "<KEY>" or arg.key is "<KEY>"
path = cola.setting(arg.key)
tPath = trimPath(path)
if tPath isnt path
ignoreRouterSettingChange = true
cola.setting(arg.key, tPath)
ignoreRouterSettingChange = false
return
)
# router.path
# router.name
# router.redirectTo
# router.enter
# router.leave
# router.title
# router.jsUrl
# router.templateUrl
# router.target
# router.parentModel
cola.route = (path, router)->
routerRegistry ?= new cola.util.KeyedArray()
if typeof router == "function"
router =
enter: router
router.path = path = trimPath(path)
path = path.slice(1)
if not router.name
name = path or cola.constants.DEFAULT_PATH
parts = name.split(/[\/\-]/)
nameParts = []
for part, i in parts
if not part or part.charCodeAt(0) == 58 # `:`
continue
nameParts.push(if nameParts.length > 0 then cola.util.capitalize(part) else part)
router.name = nameParts.join("");
router.pathParts = pathParts = []
if path
hasVariable = false
for part in path.split("/")
if part.charCodeAt(0) == 58 # `:`
optional = part.charCodeAt(part.length - 1) == 63 # `?`
if optional
variable = part.substring(1, part.length - 1)
else
variable = part.substring(1)
hasVariable = true
pathParts.push({
variable: variable
optional: optional
})
else
pathParts.push(part)
router.hasVariable = hasVariable
routerRegistry.add(router.path, router)
return router
cola.getCurrentRoutePath = ()->
return currentRoutePath
cola.getCurrentRouter = ()->
return currentRouter
cola.setRoutePath = (path, replace, alwaysNotify)->
if path and path.charCodeAt(0) == 35 # `#`
routerMode = "hash"
path = path.substring(1)
else
routerMode = cola.setting("routerMode") or "hash"
if routerMode is "hash"
if path.charCodeAt(0) != 47 # `/`
path = "/" + path
window.location.hash = path if window.location.hash != path
if alwaysNotify
_onHashChange()
else
pathRoot = cola.setting("routerContextPath")
if pathRoot and path.charCodeAt(0) is 47 # `/`
realPath = cola.util.path(pathRoot, path)
else
realPath = path
pathname = realPath
i = pathname.indexOf("?")
if i >= 0
pathname = pathname.substring(0, i)
i = pathname.indexOf("#")
if i >= 0
pathname = pathname.substring(0, i)
if location.pathname isnt pathname
if replace
window.history.replaceState({
path: realPath
}, null, realPath)
else
window.history.pushState({
path: realPath
}, null, realPath)
if location.pathname isnt pathname # 处理 ../ ./ 及 path前缀 等情况
realPath = location.pathname + location.search + location.hash
if pathRoot and realPath.indexOf(pathRoot) is 0
path = realPath.substring(pathRoot.length)
window.history.replaceState({
path: realPath
originPath: path
}, null, realPath)
_onStateChange(path)
else if alwaysNotify
_onStateChange(pathname)
return
_findRouter = (path)->
return null unless routerRegistry
path ?= cola.setting("defaultRouterPath")
path = trimPath(path).slice(1)
pathParts = if path then path.split(/[\/\?\#]/) else []
for router in routerRegistry.elements
defPathParts = router.pathParts
gap = defPathParts.length - pathParts.length
unless gap == 0 or gap == 1 and defPathParts.length > 0 and defPathParts[defPathParts.length - 1].optional then continue
matching = true
param = {}
for defPart, i in defPathParts
if typeof defPart == "string"
if defPart != pathParts[i]
matching = false
break
else
if i >= pathParts.length and not defPart.optional
matching = false
break
param[defPart.variable] = pathParts[i]
if matching then break
if matching
router.param = param
return router
else
return null
cola.createRouterModel = (router)->
if router.parentModel instanceof cola.Scope
parentModel = router.parentModel
else
parentModelName = router.parentModel or cola.constants.DEFAULT_PATH
parentModel = cola.model(parentModelName)
if !parentModel then throw new cola.Exception("Parent Model \"#{parentModelName}\" is undefined.")
return new cola.Model(router.name, parentModel)
_switchRouter = (router, path)->
if router.redirectTo
cola.setRoutePath(router.redirectTo)
return
eventArg = {
path: path
prev: currentRouter
next: router
}
if cola.fire("beforeRouterSwitch", cola, eventArg) is false then return
if currentRouter
currentRouter.leave?(currentRouter)
if currentRouter.targetDom
cola.unloadSubView(currentRouter.targetDom, {
cssUrl: currentRouter.cssUrl
})
oldModel = cola.util.removeUserData(currentRouter.targetDom, "_model")
oldModel?.destroy()
if router.templateUrl
if router.target
if router.target.nodeType
target = router.target
else
target = $(router.target)[0]
if !target
target = document.getElementsByClassName(cola.constants.VIEW_PORT_CLASS)[0]
if !target
target = document.getElementsByClassName(cola.constants.VIEW_CLASS)[0]
if !target
target = document.body
router.targetDom = target
$fly(target).empty()
currentRouter = router
if router.templateUrl
model = cola.createRouterModel(router)
eventArg.nextModel = model
cola.util.userData(router.targetDom, "_model", model)
cola.loadSubView(router.targetDom, {
model: model
htmlUrl: router.templateUrl
jsUrl: router.jsUrl
cssUrl: router.cssUrl
data: router.data
param: router.param
callback: ()->
router.enter?(router, model)
document.title = router.title if router.title
return
})
else
router.enter?(router, null)
document.title = router.title if router.title
cola.fire("routerSwitch", cola, eventArg)
return
_getHashPath = ()->
path = location.hash
path = path.substring(1) if path
if path?.charCodeAt(0) == 33 # `!`
path = path.substring(1)
if path.indexOf("?") >= 0
path = path.substring(0, path.indexOf("?"))
return trimPath(path)
_onHashChange = ()->
return if (cola.setting("routerMode") or "hash") isnt "hash"
path = _getHashPath()
return if path is currentRoutePath
currentRoutePath = path
router = _findRouter(path)
_switchRouter(router, path) if router
return
_onStateChange = (path)->
return if cola.setting("routerMode") isnt "state"
path = trimPath(path)
i = path.indexOf("#")
if i > -1
path = path.substring(i + 1)
if path.charCodeAt(0) is 47 # `/`
routerContextPath = cola.setting("routerContextPath")
if routerContextPath and path.indexOf(routerContextPath) is 0
path = path.slice(routerContextPath.length)
return if path is currentRoutePath
currentRoutePath = path
i = path.indexOf("?")
if i > -1
path = path.substring(0, i)
router = _findRouter(path)
_switchRouter(router, path) if router
return
$ ()->
setTimeout(()->
$fly(window).on("hashchange", _onHashChange).on("popstate", ()->
if not location.hash
state = window.history.state
_onStateChange(state?.path or (location.pathname + location.search + location.hash))
return
)
$(document.body).delegate("a.state", "click", ()->
href = @getAttribute("href")
if href
target = @getAttribute("target")
if not target or target is "_self"
cola.setRoutePath(href)
return false
)
path = _getHashPath()
if path
router = _findRouter(path)
if router then _switchRouter(router, path)
else
router = _findRouter(null)
if router
cola.setRoutePath((router.redirectTo or cola.setting("defaultRouterPath") or "") + location.search, true, true)
return
, 0)
return | true | routerRegistry = null
currentRoutePath = null
currentRouter = null
trimPath = (path)->
if path
if path.charCodeAt(0) isnt 47 # `/`
path = "/" + path
if path.charCodeAt(path.length - 1) == 47 # `/`
path = path.substring(0, path.length - 1)
return path || ""
ignoreRouterSettingChange = false
cola.on("settingChange", (self, arg)->
return if ignoreRouterSettingChange
if arg.key is "PI:KEY:<KEY>END_PI" or arg.key is "PI:KEY:<KEY>END_PI"
path = cola.setting(arg.key)
tPath = trimPath(path)
if tPath isnt path
ignoreRouterSettingChange = true
cola.setting(arg.key, tPath)
ignoreRouterSettingChange = false
return
)
# router.path
# router.name
# router.redirectTo
# router.enter
# router.leave
# router.title
# router.jsUrl
# router.templateUrl
# router.target
# router.parentModel
cola.route = (path, router)->
routerRegistry ?= new cola.util.KeyedArray()
if typeof router == "function"
router =
enter: router
router.path = path = trimPath(path)
path = path.slice(1)
if not router.name
name = path or cola.constants.DEFAULT_PATH
parts = name.split(/[\/\-]/)
nameParts = []
for part, i in parts
if not part or part.charCodeAt(0) == 58 # `:`
continue
nameParts.push(if nameParts.length > 0 then cola.util.capitalize(part) else part)
router.name = nameParts.join("");
router.pathParts = pathParts = []
if path
hasVariable = false
for part in path.split("/")
if part.charCodeAt(0) == 58 # `:`
optional = part.charCodeAt(part.length - 1) == 63 # `?`
if optional
variable = part.substring(1, part.length - 1)
else
variable = part.substring(1)
hasVariable = true
pathParts.push({
variable: variable
optional: optional
})
else
pathParts.push(part)
router.hasVariable = hasVariable
routerRegistry.add(router.path, router)
return router
cola.getCurrentRoutePath = ()->
return currentRoutePath
cola.getCurrentRouter = ()->
return currentRouter
cola.setRoutePath = (path, replace, alwaysNotify)->
if path and path.charCodeAt(0) == 35 # `#`
routerMode = "hash"
path = path.substring(1)
else
routerMode = cola.setting("routerMode") or "hash"
if routerMode is "hash"
if path.charCodeAt(0) != 47 # `/`
path = "/" + path
window.location.hash = path if window.location.hash != path
if alwaysNotify
_onHashChange()
else
pathRoot = cola.setting("routerContextPath")
if pathRoot and path.charCodeAt(0) is 47 # `/`
realPath = cola.util.path(pathRoot, path)
else
realPath = path
pathname = realPath
i = pathname.indexOf("?")
if i >= 0
pathname = pathname.substring(0, i)
i = pathname.indexOf("#")
if i >= 0
pathname = pathname.substring(0, i)
if location.pathname isnt pathname
if replace
window.history.replaceState({
path: realPath
}, null, realPath)
else
window.history.pushState({
path: realPath
}, null, realPath)
if location.pathname isnt pathname # 处理 ../ ./ 及 path前缀 等情况
realPath = location.pathname + location.search + location.hash
if pathRoot and realPath.indexOf(pathRoot) is 0
path = realPath.substring(pathRoot.length)
window.history.replaceState({
path: realPath
originPath: path
}, null, realPath)
_onStateChange(path)
else if alwaysNotify
_onStateChange(pathname)
return
_findRouter = (path)->
return null unless routerRegistry
path ?= cola.setting("defaultRouterPath")
path = trimPath(path).slice(1)
pathParts = if path then path.split(/[\/\?\#]/) else []
for router in routerRegistry.elements
defPathParts = router.pathParts
gap = defPathParts.length - pathParts.length
unless gap == 0 or gap == 1 and defPathParts.length > 0 and defPathParts[defPathParts.length - 1].optional then continue
matching = true
param = {}
for defPart, i in defPathParts
if typeof defPart == "string"
if defPart != pathParts[i]
matching = false
break
else
if i >= pathParts.length and not defPart.optional
matching = false
break
param[defPart.variable] = pathParts[i]
if matching then break
if matching
router.param = param
return router
else
return null
cola.createRouterModel = (router)->
if router.parentModel instanceof cola.Scope
parentModel = router.parentModel
else
parentModelName = router.parentModel or cola.constants.DEFAULT_PATH
parentModel = cola.model(parentModelName)
if !parentModel then throw new cola.Exception("Parent Model \"#{parentModelName}\" is undefined.")
return new cola.Model(router.name, parentModel)
_switchRouter = (router, path)->
if router.redirectTo
cola.setRoutePath(router.redirectTo)
return
eventArg = {
path: path
prev: currentRouter
next: router
}
if cola.fire("beforeRouterSwitch", cola, eventArg) is false then return
if currentRouter
currentRouter.leave?(currentRouter)
if currentRouter.targetDom
cola.unloadSubView(currentRouter.targetDom, {
cssUrl: currentRouter.cssUrl
})
oldModel = cola.util.removeUserData(currentRouter.targetDom, "_model")
oldModel?.destroy()
if router.templateUrl
if router.target
if router.target.nodeType
target = router.target
else
target = $(router.target)[0]
if !target
target = document.getElementsByClassName(cola.constants.VIEW_PORT_CLASS)[0]
if !target
target = document.getElementsByClassName(cola.constants.VIEW_CLASS)[0]
if !target
target = document.body
router.targetDom = target
$fly(target).empty()
currentRouter = router
if router.templateUrl
model = cola.createRouterModel(router)
eventArg.nextModel = model
cola.util.userData(router.targetDom, "_model", model)
cola.loadSubView(router.targetDom, {
model: model
htmlUrl: router.templateUrl
jsUrl: router.jsUrl
cssUrl: router.cssUrl
data: router.data
param: router.param
callback: ()->
router.enter?(router, model)
document.title = router.title if router.title
return
})
else
router.enter?(router, null)
document.title = router.title if router.title
cola.fire("routerSwitch", cola, eventArg)
return
_getHashPath = ()->
path = location.hash
path = path.substring(1) if path
if path?.charCodeAt(0) == 33 # `!`
path = path.substring(1)
if path.indexOf("?") >= 0
path = path.substring(0, path.indexOf("?"))
return trimPath(path)
_onHashChange = ()->
return if (cola.setting("routerMode") or "hash") isnt "hash"
path = _getHashPath()
return if path is currentRoutePath
currentRoutePath = path
router = _findRouter(path)
_switchRouter(router, path) if router
return
_onStateChange = (path)->
return if cola.setting("routerMode") isnt "state"
path = trimPath(path)
i = path.indexOf("#")
if i > -1
path = path.substring(i + 1)
if path.charCodeAt(0) is 47 # `/`
routerContextPath = cola.setting("routerContextPath")
if routerContextPath and path.indexOf(routerContextPath) is 0
path = path.slice(routerContextPath.length)
return if path is currentRoutePath
currentRoutePath = path
i = path.indexOf("?")
if i > -1
path = path.substring(0, i)
router = _findRouter(path)
_switchRouter(router, path) if router
return
$ ()->
setTimeout(()->
$fly(window).on("hashchange", _onHashChange).on("popstate", ()->
if not location.hash
state = window.history.state
_onStateChange(state?.path or (location.pathname + location.search + location.hash))
return
)
$(document.body).delegate("a.state", "click", ()->
href = @getAttribute("href")
if href
target = @getAttribute("target")
if not target or target is "_self"
cola.setRoutePath(href)
return false
)
path = _getHashPath()
if path
router = _findRouter(path)
if router then _switchRouter(router, path)
else
router = _findRouter(null)
if router
cola.setRoutePath((router.redirectTo or cola.setting("defaultRouterPath") or "") + location.search, true, true)
return
, 0)
return |
[
{
"context": "fore (done) ->\n auth.login(server, {username: \"admin@test.com\", password:\"password\"}, 200, \n (res)->\n ",
"end": 491,
"score": 0.9999154806137085,
"start": 477,
"tag": "EMAIL",
"value": "admin@test.com"
},
{
"context": "in(server, {username: \"admin@te... | test/services_tests/test_build_services.coffee | J-JRC/ureport-standalone | 0 | #load application models
server = require('../../app')
_ = require('underscore');
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User can perform action on builds collection ', ->
cookies = undefined;
before (done) ->
auth.login(server, {username: "admin@test.com", password:"password"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
describe 'filter builds', ->
it 'should return all builds with filter', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "Team1" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 8
done()
)
return
it 'should return all builds with given range', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "Team1" }
],
"range" : 3
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 3
done()
)
return
it 'should return all archvied builds', (done) ->
payload = {
"is_archive" : true,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"range" : 3
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should not assign any default browser when it is not given.', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 7
done()
)
return
it 'should return provided version', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"version" : [
{ "version" : "2.1" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should return provided device', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"device" : [
{ "device" : "iPhoneX" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should return provided browser type', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : {$regex: "ie", $options:"i"}}
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 3
done()
)
return
it 'should return error when product is not given', (done) ->
payload = {
"is_archive" : false,
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : "ie"}
],
"range" : 20
}
build.filter(server,cookies, payload, 400,
(res) ->
res.body.should.be.an 'Object'
res.body.error.should.include "mandatory"
done()
)
return
it 'should return error when type is not given', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : "ie"}
],
"range" : 20
}
build.filter(server,cookies, payload, 400,
(res) ->
res.body.should.be.an 'Object'
res.body.error.should.include "mandatory"
done()
)
return
describe 'find build by ID', ->
existbuild = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
existbuild = res.body[0]
done()
)
return
it 'should find a build', (done) ->
build.findById(server, cookies, existbuild._id, 200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
done()
)
return
it 'should not find a build when ID is not valid', (done) ->
build.findById(server, cookies, "598f5d31fa965603f86b2d35", 404,
(res) ->
res.error.should.exist
res.error.text.should.contains "598f5d31fa965603f86b2d35"
done()
)
return
describe 'update build info', ->
existbuild = undefined;
existbuildWithCommentAndOutage = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateCommentAndOutage" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithCommentAndOutage = res.body[1]
else
existbuild = res.body[1]
existbuildWithCommentAndOutage = res.body[0]
done()
)
return
it 'should update a build parameter', (done) ->
date = new Date("2015-03-25T12:00:00.000Z")
build.update(server,cookies,
existbuild._id,
{
start_time: date,
end_time: date
owner: 'Tester'
is_archive: false
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.owner.should.be.equal 'Tester'
res.body.start_time.should.be.equal "2015-03-25T12:00:00.000Z"
res.body.end_time.should.be.equal "2015-03-25T12:00:00.000Z"
done()
)
return
it 'should update a build pass status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 18,
fail: undefined,
skip: "4",
warning: null
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.status.pass.should.be.equal 28
res.body.status.fail.should.be.equal 9
res.body.status.skip.should.be.equal 11
res.body.status.warning.should.be.equal 12
res.body.status.total.should.be.equal 60
done()
)
return
it 'should update a build status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 0,
fail: 2,
skip: 4,
warning: 0
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.status.pass.should.be.equal 28
res.body.status.fail.should.be.equal 11
res.body.status.skip.should.be.equal 15
res.body.status.warning.should.be.equal 12
done()
)
return
it 'should update a build comments', (done) ->
build.update(server,cookies,
existbuildWithCommentAndOutage._id,
{
comments: [{
user: 'Update user',
message: 'this is just a updated message.',
time: moment().add(4, 'hour').format()
},{
user: 'Update user',
message: 'this is just another updated message.',
time: moment().add(4, 'hour').format()
}]
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateCommentAndOutage'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 2
res.body.comments[0].user.should.be.equal "Update user"
res.body.comments[0].message.should.be.equal "this is just a updated message."
res.body.comments[0].time.should.exists
res.body.comments[1].user.should.be.equal "Update user"
res.body.comments[1].message.should.be.equal 'this is just another updated message.'
res.body.comments[1].time.should.exists
done()
)
return
it 'should not update a build product, type and team', (done) ->
build.update(server,cookies,
existbuild._id,
{
product: "some product"
type: "some type"
team: "some team"
},
200,
(res) ->
res.error.should.exist
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.team.should.be.equal 'UpdateTeam'
done()
)
return
it 'should not update a build when ID is not valid', (done) ->
build.update(server, cookies, "598f5d31fa965603f86b2d35", {}, 404,
(res) ->
res.error.should.exist
res.error.text.should.contains "598f5d31fa965603f86b2d35"
done()
)
return
describe 'add Comments and Outages', ->
existbuild = undefined;
existbuildWithoutComment = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateComment" }
],
"type" : [
{ "type" : "API" }
],
"browser" : [
{ "browser" : null }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithoutComment = res.body[1]
else
existbuild = res.body[1]
existbuildWithoutComment = res.body[0]
done()
)
return
it 'should add comment to a build does not have comment', (done) ->
# date = new Date("2015-03-25T12:00:00.000Z")
build.addComment(server,cookies,
existbuildWithoutComment._id,
{
comment:{
user: "Mike"
message: "This build is very bad, everything is broken."
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateComment'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 1
res.body.comments[0].user.should.be.equal "Mike"
res.body.comments[0].message.should.be.equal "This build is very bad, everything is broken."
res.body.comments[0].time.should.exists
done()
)
return
it 'should add comment to a build has comment', (done) ->
# date = new Date("2015-03-25T12:00:00.000Z")
build.addComment(server,cookies,
existbuild._id,
{
comment:{
user: "Jason"
message: "Come on, everything is broken."
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 2
res.body.comments[0].user.should.be.equal "Super user"
res.body.comments[0].message.should.be.equal "this is just a message."
res.body.comments[0].time.should.exists
res.body.comments[1].user.should.be.equal "Jason"
res.body.comments[1].message.should.be.equal "Come on, everything is broken."
res.body.comments[1].time.should.exists
done()
)
return
it 'should add outage to a build does not have outage', (done) ->
build.addOutage(server,cookies,
existbuildWithoutComment._id,
{
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
number : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateComment'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].pattern.should.be.equal "^\s*Nullpointer exception\s*$"
res.body.outages[0].search_type.should.be.equal "regex"
res.body.outages[0].caused_by.should.be.equal "System Error"
res.body.outages[0].tracking.number.should.be.equal 'JIRA-2234'
res.body.outages[0].impact_test.should.be.an 'Object'
res.body.outages[0].impact_test.warning.should.be.equal 0
res.body.outages[0].exceptions.length.should.be.equal 2
done()
)
return
it 'should update outage to a build has outage', (done) ->
build.addOutage(server,cookies,
existbuild._id,
{
pattern: 'Nullpointer exception',
search_type: 'STRING',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-8888'
},
exceptions: [
'TEST2234', 'TEST2235','TEST2236', 'TEST2237'
],
impact_test:{
fail: 16,
skip: 14,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.device.should.be.equal 'Windows 7'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].pattern.should.be.equal "Nullpointer exception"
res.body.outages[0].search_type.should.be.equal "STRING"
res.body.outages[0].caused_by.should.be.equal "System Error"
res.body.outages[0].impact_test.should.be.an 'Object'
res.body.outages[0].impact_test.fail.should.be.equal 16
res.body.outages[0].impact_test.skip.should.be.equal 14
res.body.outages[0].exceptions.length.should.be.equal 4
done()
)
return
it 'should update comment to exist outage', (done) ->
build.addOutageComment(server,cookies,
existbuild._id,
{
pattern: 'Nullpointer exception',
search_type: 'STRING',
comment: {
'user': 'Super user',
'message': 'this is just a message.',
'time': moment().add(4, 'hour').format()
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.device.should.be.equal 'Windows 7'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].comments.should.be.an 'Array'
res.body.outages[0].comments.length.should.equal 1
done()
)
return
it 'should add outage to a build has outage', (done) ->
build.addOutage(server,cookies,
existbuild._id,
{
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 2
res.body.outages[1].pattern.should.be.equal "^\s*Nullpointer exception\s*$"
res.body.outages[1].search_type.should.be.equal "regex"
res.body.outages[1].caused_by.should.be.equal "System Error"
res.body.outages[1].impact_test.should.be.an 'Object'
res.body.outages[1].impact_test.warning.should.be.equal 0
res.body.outages[1].exceptions.length.should.be.equal 2
done()
)
return
describe 'create build', ->
create_build_id = undefined
it 'should create a new build with min params', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'team' : 'TeamX',
'build' : 1
}
build.create(server,cookies,
payload,
200,
(res) ->
create_build_id = res.body._id
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'TestProductData'
res.body.type.should.be.equal 'API'
res.body.team.should.be.equal 'TeamX'
res.body.build.should.be.equal 1
res.body.is_archive.should.be.equal false
res.body.status.should.be.an 'Object'
res.body.status.total.should.be.equal 0
res.body.status.pass.should.be.equal 0
res.body.status.fail.should.be.equal 0
res.body.status.skip.should.be.equal 0
res.body.status.warning.should.be.equal 0
res.body.outages.length.should.equal 0
res.body.comments.length.should.equal 0
done()
)
return
after (done) ->
build.delete(server,cookies, create_build_id, 200,
(res) ->
done()
)
return
describe 'create build with missing params', ->
it 'should not create a new build', (done) ->
payload = {
'product' : 'TestProductData'
}
build.create(server,cookies,
payload,
400,
(res) ->
res.body.error.should.equal 'Type is mandatory'
done()
)
return
it 'should not create a new build when miss build', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'team' : 'TEAMTest'
}
build.create(server,cookies,
payload,
400,
(res) ->
res.body.error.should.equal 'Build is mandatory'
done()
)
return
| 74994 | #load application models
server = require('../../app')
_ = require('underscore');
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User can perform action on builds collection ', ->
cookies = undefined;
before (done) ->
auth.login(server, {username: "<EMAIL>", password:"<PASSWORD>"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
describe 'filter builds', ->
it 'should return all builds with filter', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "Team1" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 8
done()
)
return
it 'should return all builds with given range', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "Team1" }
],
"range" : 3
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 3
done()
)
return
it 'should return all archvied builds', (done) ->
payload = {
"is_archive" : true,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"range" : 3
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should not assign any default browser when it is not given.', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 7
done()
)
return
it 'should return provided version', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"version" : [
{ "version" : "2.1" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should return provided device', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"device" : [
{ "device" : "iPhoneX" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should return provided browser type', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : {$regex: "ie", $options:"i"}}
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 3
done()
)
return
it 'should return error when product is not given', (done) ->
payload = {
"is_archive" : false,
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : "ie"}
],
"range" : 20
}
build.filter(server,cookies, payload, 400,
(res) ->
res.body.should.be.an 'Object'
res.body.error.should.include "mandatory"
done()
)
return
it 'should return error when type is not given', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : "ie"}
],
"range" : 20
}
build.filter(server,cookies, payload, 400,
(res) ->
res.body.should.be.an 'Object'
res.body.error.should.include "mandatory"
done()
)
return
describe 'find build by ID', ->
existbuild = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
existbuild = res.body[0]
done()
)
return
it 'should find a build', (done) ->
build.findById(server, cookies, existbuild._id, 200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
done()
)
return
it 'should not find a build when ID is not valid', (done) ->
build.findById(server, cookies, "598f5d31fa965603f86b2d35", 404,
(res) ->
res.error.should.exist
res.error.text.should.contains "598f5d31fa965603f86b2d35"
done()
)
return
describe 'update build info', ->
existbuild = undefined;
existbuildWithCommentAndOutage = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateCommentAndOutage" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithCommentAndOutage = res.body[1]
else
existbuild = res.body[1]
existbuildWithCommentAndOutage = res.body[0]
done()
)
return
it 'should update a build parameter', (done) ->
date = new Date("2015-03-25T12:00:00.000Z")
build.update(server,cookies,
existbuild._id,
{
start_time: date,
end_time: date
owner: 'Tester'
is_archive: false
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.owner.should.be.equal 'Tester'
res.body.start_time.should.be.equal "2015-03-25T12:00:00.000Z"
res.body.end_time.should.be.equal "2015-03-25T12:00:00.000Z"
done()
)
return
it 'should update a build pass status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 18,
fail: undefined,
skip: "4",
warning: null
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.status.pass.should.be.equal 28
res.body.status.fail.should.be.equal 9
res.body.status.skip.should.be.equal 11
res.body.status.warning.should.be.equal 12
res.body.status.total.should.be.equal 60
done()
)
return
it 'should update a build status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 0,
fail: 2,
skip: 4,
warning: 0
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.status.pass.should.be.equal 28
res.body.status.fail.should.be.equal 11
res.body.status.skip.should.be.equal 15
res.body.status.warning.should.be.equal 12
done()
)
return
it 'should update a build comments', (done) ->
build.update(server,cookies,
existbuildWithCommentAndOutage._id,
{
comments: [{
user: 'Update user',
message: 'this is just a updated message.',
time: moment().add(4, 'hour').format()
},{
user: 'Update user',
message: 'this is just another updated message.',
time: moment().add(4, 'hour').format()
}]
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateCommentAndOutage'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 2
res.body.comments[0].user.should.be.equal "Update user"
res.body.comments[0].message.should.be.equal "this is just a updated message."
res.body.comments[0].time.should.exists
res.body.comments[1].user.should.be.equal "Update user"
res.body.comments[1].message.should.be.equal 'this is just another updated message.'
res.body.comments[1].time.should.exists
done()
)
return
it 'should not update a build product, type and team', (done) ->
build.update(server,cookies,
existbuild._id,
{
product: "some product"
type: "some type"
team: "some team"
},
200,
(res) ->
res.error.should.exist
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.team.should.be.equal 'UpdateTeam'
done()
)
return
it 'should not update a build when ID is not valid', (done) ->
build.update(server, cookies, "598f5d31fa965603f86b2d35", {}, 404,
(res) ->
res.error.should.exist
res.error.text.should.contains "598f5d31fa965603f86b2d35"
done()
)
return
describe 'add Comments and Outages', ->
existbuild = undefined;
existbuildWithoutComment = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateComment" }
],
"type" : [
{ "type" : "API" }
],
"browser" : [
{ "browser" : null }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithoutComment = res.body[1]
else
existbuild = res.body[1]
existbuildWithoutComment = res.body[0]
done()
)
return
it 'should add comment to a build does not have comment', (done) ->
# date = new Date("2015-03-25T12:00:00.000Z")
build.addComment(server,cookies,
existbuildWithoutComment._id,
{
comment:{
user: "Mike"
message: "This build is very bad, everything is broken."
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateComment'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 1
res.body.comments[0].user.should.be.equal "<NAME>"
res.body.comments[0].message.should.be.equal "This build is very bad, everything is broken."
res.body.comments[0].time.should.exists
done()
)
return
it 'should add comment to a build has comment', (done) ->
# date = new Date("2015-03-25T12:00:00.000Z")
build.addComment(server,cookies,
existbuild._id,
{
comment:{
user: "<NAME>"
message: "Come on, everything is broken."
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 2
res.body.comments[0].user.should.be.equal "Super user"
res.body.comments[0].message.should.be.equal "this is just a message."
res.body.comments[0].time.should.exists
res.body.comments[1].user.should.be.equal "<NAME>"
res.body.comments[1].message.should.be.equal "Come on, everything is broken."
res.body.comments[1].time.should.exists
done()
)
return
it 'should add outage to a build does not have outage', (done) ->
build.addOutage(server,cookies,
existbuildWithoutComment._id,
{
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
number : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateComment'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].pattern.should.be.equal "^\s*Nullpointer exception\s*$"
res.body.outages[0].search_type.should.be.equal "regex"
res.body.outages[0].caused_by.should.be.equal "System Error"
res.body.outages[0].tracking.number.should.be.equal 'JIRA-2234'
res.body.outages[0].impact_test.should.be.an 'Object'
res.body.outages[0].impact_test.warning.should.be.equal 0
res.body.outages[0].exceptions.length.should.be.equal 2
done()
)
return
it 'should update outage to a build has outage', (done) ->
build.addOutage(server,cookies,
existbuild._id,
{
pattern: 'Nullpointer exception',
search_type: 'STRING',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-8888'
},
exceptions: [
'TEST2234', 'TEST2235','TEST2236', 'TEST2237'
],
impact_test:{
fail: 16,
skip: 14,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.device.should.be.equal 'Windows 7'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].pattern.should.be.equal "Nullpointer exception"
res.body.outages[0].search_type.should.be.equal "STRING"
res.body.outages[0].caused_by.should.be.equal "System Error"
res.body.outages[0].impact_test.should.be.an 'Object'
res.body.outages[0].impact_test.fail.should.be.equal 16
res.body.outages[0].impact_test.skip.should.be.equal 14
res.body.outages[0].exceptions.length.should.be.equal 4
done()
)
return
it 'should update comment to exist outage', (done) ->
build.addOutageComment(server,cookies,
existbuild._id,
{
pattern: 'Nullpointer exception',
search_type: 'STRING',
comment: {
'user': 'Super user',
'message': 'this is just a message.',
'time': moment().add(4, 'hour').format()
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.device.should.be.equal 'Windows 7'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].comments.should.be.an 'Array'
res.body.outages[0].comments.length.should.equal 1
done()
)
return
it 'should add outage to a build has outage', (done) ->
build.addOutage(server,cookies,
existbuild._id,
{
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 2
res.body.outages[1].pattern.should.be.equal "^\s*Nullpointer exception\s*$"
res.body.outages[1].search_type.should.be.equal "regex"
res.body.outages[1].caused_by.should.be.equal "System Error"
res.body.outages[1].impact_test.should.be.an 'Object'
res.body.outages[1].impact_test.warning.should.be.equal 0
res.body.outages[1].exceptions.length.should.be.equal 2
done()
)
return
describe 'create build', ->
create_build_id = undefined
it 'should create a new build with min params', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'team' : 'TeamX',
'build' : 1
}
build.create(server,cookies,
payload,
200,
(res) ->
create_build_id = res.body._id
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'TestProductData'
res.body.type.should.be.equal 'API'
res.body.team.should.be.equal 'TeamX'
res.body.build.should.be.equal 1
res.body.is_archive.should.be.equal false
res.body.status.should.be.an 'Object'
res.body.status.total.should.be.equal 0
res.body.status.pass.should.be.equal 0
res.body.status.fail.should.be.equal 0
res.body.status.skip.should.be.equal 0
res.body.status.warning.should.be.equal 0
res.body.outages.length.should.equal 0
res.body.comments.length.should.equal 0
done()
)
return
after (done) ->
build.delete(server,cookies, create_build_id, 200,
(res) ->
done()
)
return
describe 'create build with missing params', ->
it 'should not create a new build', (done) ->
payload = {
'product' : 'TestProductData'
}
build.create(server,cookies,
payload,
400,
(res) ->
res.body.error.should.equal 'Type is mandatory'
done()
)
return
it 'should not create a new build when miss build', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'team' : 'TEAMTest'
}
build.create(server,cookies,
payload,
400,
(res) ->
res.body.error.should.equal 'Build is mandatory'
done()
)
return
| true | #load application models
server = require('../../app')
_ = require('underscore');
build = require('../api_objects/build_api_object')
auth = require('../api_objects/auth_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User can perform action on builds collection ', ->
cookies = undefined;
before (done) ->
auth.login(server, {username: "PI:EMAIL:<EMAIL>END_PI", password:"PI:PASSWORD:<PASSWORD>END_PI"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
done()
)
return
describe 'filter builds', ->
it 'should return all builds with filter', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "Team1" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 8
done()
)
return
it 'should return all builds with given range', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "Team1" }
],
"range" : 3
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 3
done()
)
return
it 'should return all archvied builds', (done) ->
payload = {
"is_archive" : true,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"range" : 3
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should not assign any default browser when it is not given.', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 7
done()
)
return
it 'should return provided version', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"version" : [
{ "version" : "2.1" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should return provided device', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"device" : [
{ "device" : "iPhoneX" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 1
done()
)
return
it 'should return provided browser type', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : {$regex: "ie", $options:"i"}}
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
res.body.should.be.an 'Array'
res.body.length.should.equal 3
done()
)
return
it 'should return error when product is not given', (done) ->
payload = {
"is_archive" : false,
"type" : [
{ "type" : "UI" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : "ie"}
],
"range" : 20
}
build.filter(server,cookies, payload, 400,
(res) ->
res.body.should.be.an 'Object'
res.body.error.should.include "mandatory"
done()
)
return
it 'should return error when type is not given', (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "uReport" }
],
"team" : [
{ "team" : "Team2" }
],
"browser" : [
{ "browser" : "ie"}
],
"range" : 20
}
build.filter(server,cookies, payload, 400,
(res) ->
res.body.should.be.an 'Object'
res.body.error.should.include "mandatory"
done()
)
return
describe 'find build by ID', ->
existbuild = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
existbuild = res.body[0]
done()
)
return
it 'should find a build', (done) ->
build.findById(server, cookies, existbuild._id, 200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
done()
)
return
it 'should not find a build when ID is not valid', (done) ->
build.findById(server, cookies, "598f5d31fa965603f86b2d35", 404,
(res) ->
res.error.should.exist
res.error.text.should.contains "598f5d31fa965603f86b2d35"
done()
)
return
describe 'update build info', ->
existbuild = undefined;
existbuildWithCommentAndOutage = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateCommentAndOutage" }
],
"type" : [
{ "type" : "API" }
],
"team" : [
{ "team" : "UpdateTeam" }
]
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithCommentAndOutage = res.body[1]
else
existbuild = res.body[1]
existbuildWithCommentAndOutage = res.body[0]
done()
)
return
it 'should update a build parameter', (done) ->
date = new Date("2015-03-25T12:00:00.000Z")
build.update(server,cookies,
existbuild._id,
{
start_time: date,
end_time: date
owner: 'Tester'
is_archive: false
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.owner.should.be.equal 'Tester'
res.body.start_time.should.be.equal "2015-03-25T12:00:00.000Z"
res.body.end_time.should.be.equal "2015-03-25T12:00:00.000Z"
done()
)
return
it 'should update a build pass status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 18,
fail: undefined,
skip: "4",
warning: null
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.status.pass.should.be.equal 28
res.body.status.fail.should.be.equal 9
res.body.status.skip.should.be.equal 11
res.body.status.warning.should.be.equal 12
res.body.status.total.should.be.equal 60
done()
)
return
it 'should update a build status', (done) ->
build.updateStatus(server,cookies,
existbuild._id,
{
pass: 0,
fail: 2,
skip: 4,
warning: 0
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.status.pass.should.be.equal 28
res.body.status.fail.should.be.equal 11
res.body.status.skip.should.be.equal 15
res.body.status.warning.should.be.equal 12
done()
)
return
it 'should update a build comments', (done) ->
build.update(server,cookies,
existbuildWithCommentAndOutage._id,
{
comments: [{
user: 'Update user',
message: 'this is just a updated message.',
time: moment().add(4, 'hour').format()
},{
user: 'Update user',
message: 'this is just another updated message.',
time: moment().add(4, 'hour').format()
}]
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateCommentAndOutage'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 2
res.body.comments[0].user.should.be.equal "Update user"
res.body.comments[0].message.should.be.equal "this is just a updated message."
res.body.comments[0].time.should.exists
res.body.comments[1].user.should.be.equal "Update user"
res.body.comments[1].message.should.be.equal 'this is just another updated message.'
res.body.comments[1].time.should.exists
done()
)
return
it 'should not update a build product, type and team', (done) ->
build.update(server,cookies,
existbuild._id,
{
product: "some product"
type: "some type"
team: "some team"
},
200,
(res) ->
res.error.should.exist
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.team.should.be.equal 'UpdateTeam'
done()
)
return
it 'should not update a build when ID is not valid', (done) ->
build.update(server, cookies, "598f5d31fa965603f86b2d35", {}, 404,
(res) ->
res.error.should.exist
res.error.text.should.contains "598f5d31fa965603f86b2d35"
done()
)
return
describe 'add Comments and Outages', ->
existbuild = undefined;
existbuildWithoutComment = undefined;
before (done) ->
payload = {
"is_archive" : false,
"product" : [
{ "product" : "UpdateProduct" },
{ "product" : "UpdateComment" }
],
"type" : [
{ "type" : "API" }
],
"browser" : [
{ "browser" : null }
],
"team" : [
{ "team" : "UpdateTeam" }
],
"range" : 20
}
build.filter(server,cookies, payload, 200,
(res) ->
#only two builds should be returned
if(res.body[0].product == 'UpdateProduct')
existbuild = res.body[0]
existbuildWithoutComment = res.body[1]
else
existbuild = res.body[1]
existbuildWithoutComment = res.body[0]
done()
)
return
it 'should add comment to a build does not have comment', (done) ->
# date = new Date("2015-03-25T12:00:00.000Z")
build.addComment(server,cookies,
existbuildWithoutComment._id,
{
comment:{
user: "Mike"
message: "This build is very bad, everything is broken."
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateComment'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 1
res.body.comments[0].user.should.be.equal "PI:NAME:<NAME>END_PI"
res.body.comments[0].message.should.be.equal "This build is very bad, everything is broken."
res.body.comments[0].time.should.exists
done()
)
return
it 'should add comment to a build has comment', (done) ->
# date = new Date("2015-03-25T12:00:00.000Z")
build.addComment(server,cookies,
existbuild._id,
{
comment:{
user: "PI:NAME:<NAME>END_PI"
message: "Come on, everything is broken."
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.comments.should.be.an 'Array'
res.body.comments.length.should.equal 2
res.body.comments[0].user.should.be.equal "Super user"
res.body.comments[0].message.should.be.equal "this is just a message."
res.body.comments[0].time.should.exists
res.body.comments[1].user.should.be.equal "PI:NAME:<NAME>END_PI"
res.body.comments[1].message.should.be.equal "Come on, everything is broken."
res.body.comments[1].time.should.exists
done()
)
return
it 'should add outage to a build does not have outage', (done) ->
build.addOutage(server,cookies,
existbuildWithoutComment._id,
{
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
number : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateComment'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].pattern.should.be.equal "^\s*Nullpointer exception\s*$"
res.body.outages[0].search_type.should.be.equal "regex"
res.body.outages[0].caused_by.should.be.equal "System Error"
res.body.outages[0].tracking.number.should.be.equal 'JIRA-2234'
res.body.outages[0].impact_test.should.be.an 'Object'
res.body.outages[0].impact_test.warning.should.be.equal 0
res.body.outages[0].exceptions.length.should.be.equal 2
done()
)
return
it 'should update outage to a build has outage', (done) ->
build.addOutage(server,cookies,
existbuild._id,
{
pattern: 'Nullpointer exception',
search_type: 'STRING',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-8888'
},
exceptions: [
'TEST2234', 'TEST2235','TEST2236', 'TEST2237'
],
impact_test:{
fail: 16,
skip: 14,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.device.should.be.equal 'Windows 7'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].pattern.should.be.equal "Nullpointer exception"
res.body.outages[0].search_type.should.be.equal "STRING"
res.body.outages[0].caused_by.should.be.equal "System Error"
res.body.outages[0].impact_test.should.be.an 'Object'
res.body.outages[0].impact_test.fail.should.be.equal 16
res.body.outages[0].impact_test.skip.should.be.equal 14
res.body.outages[0].exceptions.length.should.be.equal 4
done()
)
return
it 'should update comment to exist outage', (done) ->
build.addOutageComment(server,cookies,
existbuild._id,
{
pattern: 'Nullpointer exception',
search_type: 'STRING',
comment: {
'user': 'Super user',
'message': 'this is just a message.',
'time': moment().add(4, 'hour').format()
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.type.should.be.equal 'API'
res.body.device.should.be.equal 'Windows 7'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 1
res.body.outages[0].comments.should.be.an 'Array'
res.body.outages[0].comments.length.should.equal 1
done()
)
return
it 'should add outage to a build has outage', (done) ->
build.addOutage(server,cookies,
existbuild._id,
{
pattern: '^\s*Nullpointer exception\s*$',
search_type: 'regex',
caused_by: 'System Error',
tracking: {
'number' : 'JIRA-2234'
},
exceptions: [
'TEST2234', 'TEST2235'
],
impact_test:{
fail: 6,
skip: 4,
warning: 0
}
},
200,
(res) ->
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'UpdateProduct'
res.body.outages.should.be.an 'Array'
res.body.outages.length.should.equal 2
res.body.outages[1].pattern.should.be.equal "^\s*Nullpointer exception\s*$"
res.body.outages[1].search_type.should.be.equal "regex"
res.body.outages[1].caused_by.should.be.equal "System Error"
res.body.outages[1].impact_test.should.be.an 'Object'
res.body.outages[1].impact_test.warning.should.be.equal 0
res.body.outages[1].exceptions.length.should.be.equal 2
done()
)
return
describe 'create build', ->
create_build_id = undefined
it 'should create a new build with min params', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'team' : 'TeamX',
'build' : 1
}
build.create(server,cookies,
payload,
200,
(res) ->
create_build_id = res.body._id
res.body.should.be.an 'Object'
res.body.product.should.be.equal 'TestProductData'
res.body.type.should.be.equal 'API'
res.body.team.should.be.equal 'TeamX'
res.body.build.should.be.equal 1
res.body.is_archive.should.be.equal false
res.body.status.should.be.an 'Object'
res.body.status.total.should.be.equal 0
res.body.status.pass.should.be.equal 0
res.body.status.fail.should.be.equal 0
res.body.status.skip.should.be.equal 0
res.body.status.warning.should.be.equal 0
res.body.outages.length.should.equal 0
res.body.comments.length.should.equal 0
done()
)
return
after (done) ->
build.delete(server,cookies, create_build_id, 200,
(res) ->
done()
)
return
describe 'create build with missing params', ->
it 'should not create a new build', (done) ->
payload = {
'product' : 'TestProductData'
}
build.create(server,cookies,
payload,
400,
(res) ->
res.body.error.should.equal 'Type is mandatory'
done()
)
return
it 'should not create a new build when miss build', (done) ->
payload = {
'product' : 'TestProductData',
'type' : 'API',
'team' : 'TEAMTest'
}
build.create(server,cookies,
payload,
400,
(res) ->
res.body.error.should.equal 'Build is mandatory'
done()
)
return
|
[
{
"context": " '.auth-email': 'email'\n '.auth-password': 'password'\n '.login': 'loginBtn'\n '.register': 'regis",
"end": 314,
"score": 0.9992194175720215,
"start": 306,
"tag": "PASSWORD",
"value": "password"
}
] | app/controllers/auth.coffee | gzferrar/Nitro | 1 | Spine = require 'spine'
Setting = require '../models/setting.coffee'
Cookies = require '../utils/cookies.js'
CONFIG = require '../utils/conf.coffee'
$ = Spine.$
class Auth extends Spine.Controller
elements:
'.form': 'form'
'.auth-name': 'name'
'.auth-email': 'email'
'.auth-password': 'password'
'.login': 'loginBtn'
'.register': 'registerBtn'
'.note-login': 'loginNote'
'.note-register': 'registerNote'
'.note-success': 'successNote'
'.error': 'errorNote'
events:
'click .login': 'buttonLogin'
'click .register': 'buttonRegister'
'click .switch-mode': 'switchMode'
'click .offline': 'noAccount'
'click .service': 'oauthLogin'
'keydown input': 'enterKey'
constructor: ->
Spine.touchify(@events)
super
# True = login
# False = register
@mode = true
Setting.bind 'offline', =>
@el.hide()
Setting.bind 'login', =>
@el.fadeOut(300)
@form.removeClass('ajax')
@handleOauth()
enterKey: (e) =>
if e.keyCode is 13
if @mode
@buttonLogin()
else
@buttonRegister()
buttonLogin: =>
# Check for empty fields
if @email.val() is '' or @password.val() is ''
@errorNote.addClass('populated').text('Please fill out all fields')
else
@form.addClass('ajax')
@login @getData()
return true
buttonRegister: =>
# Check for empty fields
if @email.val() is '' or @password.val() is '' or @name.val() is ''
@errorNote.addClass('populated').text 'Please fill out all fields'
else
@form.addClass('ajax')
@register @getData()
return true
switchMode: (mode) =>
if typeof(mode) isnt 'boolean' then mode = !@mode
@mode = mode
@form.toggleClass('mode-login', @mode)
@form.toggleClass('mode-register', !@mode)
@errorNote.removeClass('populated').empty()
if @mode then @email.focus() else @name.focus()
noAccount: =>
Setting.set('noAccount', true)
Setting.trigger('offline')
# Make default tasks
# TODO: This should be part of @startApp() right?
Task.default()
return true
# Retrieve login form data
getData: =>
console.log @mode
name: @name.val()
email: @email.val()
password: @password.val()
saveToken: (id, token) ->
Setting.set('uid', id)
Setting.set('token', token)
Setting.trigger 'haveToken', [id, token]
register: (data) ->
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/register"
data: data
success: (data) =>
@form.removeClass('ajax')
# User Message
@switchMode(true)
@successNote.show()
@errorNote.removeClass("populated").empty()
if Setting.get('noAccount') is false
Task.default()
error: (xhr, status, msg) =>
@error 'signup', xhr.responseText
login: (data) ->
@errorNote.empty().removeClass('populated')
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/login"
data: data
dataType: 'json'
success: ([uid, token, email, name, pro]) =>
@saveToken(uid, token)
Setting.set('user_name', name)
Setting.set('user_email', email)
Setting.set('pro', pro)
@errorNote.removeClass('populated').empty()
# In case it's been set
Setting.set 'noAccount', false
error: (xhr, status, msg) =>
console.log 'Could not login'
@error 'login', xhr.responseText
error: (type, err) ->
@form.removeClass('ajax')
console.log "(#{type}): #{err}"
@errorNote.addClass 'populated'
if err is 'err_bad_pass'
@errorNote.html "Incorrect email or password. <a href=\"http://#{CONFIG.server}/forgot\">Forgot?</a>"
else if err is 'err_old_email'
@errorNote.text 'Account already in use'
else
@errorNote.text "#{err}"
oauthLogin: (e) =>
service = e.target.attributes['data-service']?.value
return unless service in ['dropbox', 'ubuntu']
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/request"
data:
service: service
success: (request) =>
Setting.set 'oauth',
service: service
token: request.oauth_token
secret: request.oauth_token_secret
location.href = request.authorize_url
handleOauth: =>
oauth = Setting.get('oauth')
return unless oauth?
token = oauth.token
secret = oauth.secret
service = oauth.service
Setting.delete('oauth')
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/access"
data:
service: service
token: token
secret: secret
success: (access) =>
console.log access
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/login"
data:
service: service
token: access.oauth_token
secret: access.oauth_token_secret
success: ([uid, token, email, name]) =>
@saveToken(uid, token)
Setting.set('user_name', name)
Setting.set('user_email', email)
fail: ->
console.log arguments
module.exports = Auth
| 99439 | Spine = require 'spine'
Setting = require '../models/setting.coffee'
Cookies = require '../utils/cookies.js'
CONFIG = require '../utils/conf.coffee'
$ = Spine.$
class Auth extends Spine.Controller
elements:
'.form': 'form'
'.auth-name': 'name'
'.auth-email': 'email'
'.auth-password': '<PASSWORD>'
'.login': 'loginBtn'
'.register': 'registerBtn'
'.note-login': 'loginNote'
'.note-register': 'registerNote'
'.note-success': 'successNote'
'.error': 'errorNote'
events:
'click .login': 'buttonLogin'
'click .register': 'buttonRegister'
'click .switch-mode': 'switchMode'
'click .offline': 'noAccount'
'click .service': 'oauthLogin'
'keydown input': 'enterKey'
constructor: ->
Spine.touchify(@events)
super
# True = login
# False = register
@mode = true
Setting.bind 'offline', =>
@el.hide()
Setting.bind 'login', =>
@el.fadeOut(300)
@form.removeClass('ajax')
@handleOauth()
enterKey: (e) =>
if e.keyCode is 13
if @mode
@buttonLogin()
else
@buttonRegister()
buttonLogin: =>
# Check for empty fields
if @email.val() is '' or @password.val() is ''
@errorNote.addClass('populated').text('Please fill out all fields')
else
@form.addClass('ajax')
@login @getData()
return true
buttonRegister: =>
# Check for empty fields
if @email.val() is '' or @password.val() is '' or @name.val() is ''
@errorNote.addClass('populated').text 'Please fill out all fields'
else
@form.addClass('ajax')
@register @getData()
return true
switchMode: (mode) =>
if typeof(mode) isnt 'boolean' then mode = !@mode
@mode = mode
@form.toggleClass('mode-login', @mode)
@form.toggleClass('mode-register', !@mode)
@errorNote.removeClass('populated').empty()
if @mode then @email.focus() else @name.focus()
noAccount: =>
Setting.set('noAccount', true)
Setting.trigger('offline')
# Make default tasks
# TODO: This should be part of @startApp() right?
Task.default()
return true
# Retrieve login form data
getData: =>
console.log @mode
name: @name.val()
email: @email.val()
password: @password.val()
saveToken: (id, token) ->
Setting.set('uid', id)
Setting.set('token', token)
Setting.trigger 'haveToken', [id, token]
register: (data) ->
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/register"
data: data
success: (data) =>
@form.removeClass('ajax')
# User Message
@switchMode(true)
@successNote.show()
@errorNote.removeClass("populated").empty()
if Setting.get('noAccount') is false
Task.default()
error: (xhr, status, msg) =>
@error 'signup', xhr.responseText
login: (data) ->
@errorNote.empty().removeClass('populated')
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/login"
data: data
dataType: 'json'
success: ([uid, token, email, name, pro]) =>
@saveToken(uid, token)
Setting.set('user_name', name)
Setting.set('user_email', email)
Setting.set('pro', pro)
@errorNote.removeClass('populated').empty()
# In case it's been set
Setting.set 'noAccount', false
error: (xhr, status, msg) =>
console.log 'Could not login'
@error 'login', xhr.responseText
error: (type, err) ->
@form.removeClass('ajax')
console.log "(#{type}): #{err}"
@errorNote.addClass 'populated'
if err is 'err_bad_pass'
@errorNote.html "Incorrect email or password. <a href=\"http://#{CONFIG.server}/forgot\">Forgot?</a>"
else if err is 'err_old_email'
@errorNote.text 'Account already in use'
else
@errorNote.text "#{err}"
oauthLogin: (e) =>
service = e.target.attributes['data-service']?.value
return unless service in ['dropbox', 'ubuntu']
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/request"
data:
service: service
success: (request) =>
Setting.set 'oauth',
service: service
token: request.oauth_token
secret: request.oauth_token_secret
location.href = request.authorize_url
handleOauth: =>
oauth = Setting.get('oauth')
return unless oauth?
token = oauth.token
secret = oauth.secret
service = oauth.service
Setting.delete('oauth')
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/access"
data:
service: service
token: token
secret: secret
success: (access) =>
console.log access
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/login"
data:
service: service
token: access.oauth_token
secret: access.oauth_token_secret
success: ([uid, token, email, name]) =>
@saveToken(uid, token)
Setting.set('user_name', name)
Setting.set('user_email', email)
fail: ->
console.log arguments
module.exports = Auth
| true | Spine = require 'spine'
Setting = require '../models/setting.coffee'
Cookies = require '../utils/cookies.js'
CONFIG = require '../utils/conf.coffee'
$ = Spine.$
class Auth extends Spine.Controller
elements:
'.form': 'form'
'.auth-name': 'name'
'.auth-email': 'email'
'.auth-password': 'PI:PASSWORD:<PASSWORD>END_PI'
'.login': 'loginBtn'
'.register': 'registerBtn'
'.note-login': 'loginNote'
'.note-register': 'registerNote'
'.note-success': 'successNote'
'.error': 'errorNote'
events:
'click .login': 'buttonLogin'
'click .register': 'buttonRegister'
'click .switch-mode': 'switchMode'
'click .offline': 'noAccount'
'click .service': 'oauthLogin'
'keydown input': 'enterKey'
constructor: ->
Spine.touchify(@events)
super
# True = login
# False = register
@mode = true
Setting.bind 'offline', =>
@el.hide()
Setting.bind 'login', =>
@el.fadeOut(300)
@form.removeClass('ajax')
@handleOauth()
enterKey: (e) =>
if e.keyCode is 13
if @mode
@buttonLogin()
else
@buttonRegister()
buttonLogin: =>
# Check for empty fields
if @email.val() is '' or @password.val() is ''
@errorNote.addClass('populated').text('Please fill out all fields')
else
@form.addClass('ajax')
@login @getData()
return true
buttonRegister: =>
# Check for empty fields
if @email.val() is '' or @password.val() is '' or @name.val() is ''
@errorNote.addClass('populated').text 'Please fill out all fields'
else
@form.addClass('ajax')
@register @getData()
return true
switchMode: (mode) =>
if typeof(mode) isnt 'boolean' then mode = !@mode
@mode = mode
@form.toggleClass('mode-login', @mode)
@form.toggleClass('mode-register', !@mode)
@errorNote.removeClass('populated').empty()
if @mode then @email.focus() else @name.focus()
noAccount: =>
Setting.set('noAccount', true)
Setting.trigger('offline')
# Make default tasks
# TODO: This should be part of @startApp() right?
Task.default()
return true
# Retrieve login form data
getData: =>
console.log @mode
name: @name.val()
email: @email.val()
password: @password.val()
saveToken: (id, token) ->
Setting.set('uid', id)
Setting.set('token', token)
Setting.trigger 'haveToken', [id, token]
register: (data) ->
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/register"
data: data
success: (data) =>
@form.removeClass('ajax')
# User Message
@switchMode(true)
@successNote.show()
@errorNote.removeClass("populated").empty()
if Setting.get('noAccount') is false
Task.default()
error: (xhr, status, msg) =>
@error 'signup', xhr.responseText
login: (data) ->
@errorNote.empty().removeClass('populated')
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/login"
data: data
dataType: 'json'
success: ([uid, token, email, name, pro]) =>
@saveToken(uid, token)
Setting.set('user_name', name)
Setting.set('user_email', email)
Setting.set('pro', pro)
@errorNote.removeClass('populated').empty()
# In case it's been set
Setting.set 'noAccount', false
error: (xhr, status, msg) =>
console.log 'Could not login'
@error 'login', xhr.responseText
error: (type, err) ->
@form.removeClass('ajax')
console.log "(#{type}): #{err}"
@errorNote.addClass 'populated'
if err is 'err_bad_pass'
@errorNote.html "Incorrect email or password. <a href=\"http://#{CONFIG.server}/forgot\">Forgot?</a>"
else if err is 'err_old_email'
@errorNote.text 'Account already in use'
else
@errorNote.text "#{err}"
oauthLogin: (e) =>
service = e.target.attributes['data-service']?.value
return unless service in ['dropbox', 'ubuntu']
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/request"
data:
service: service
success: (request) =>
Setting.set 'oauth',
service: service
token: request.oauth_token
secret: request.oauth_token_secret
location.href = request.authorize_url
handleOauth: =>
oauth = Setting.get('oauth')
return unless oauth?
token = oauth.token
secret = oauth.secret
service = oauth.service
Setting.delete('oauth')
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/access"
data:
service: service
token: token
secret: secret
success: (access) =>
console.log access
$.ajax
type: 'post'
url: "http://#{CONFIG.server}/oauth/login"
data:
service: service
token: access.oauth_token
secret: access.oauth_token_secret
success: ([uid, token, email, name]) =>
@saveToken(uid, token)
Setting.set('user_name', name)
Setting.set('user_email', email)
fail: ->
console.log arguments
module.exports = Auth
|
[
{
"context": "ccessKeyId: 'public'\n awsSecretAccessKey: 'secret'\n\n assert.equal upload.opts.aws.region, 'my-",
"end": 2782,
"score": 0.7077449560165405,
"start": 2776,
"tag": "KEY",
"value": "secret"
}
] | test/suite.coffee | DavidBennettUK/node-s3-uploader | 0 | assert = require 'assert'
Upload = require '../src/index.coffee'
fs = require('fs')
gm = require('gm').subClass imageMagick: true
hash = require('crypto').createHash
rand = require('crypto').pseudoRandomBytes
upload = listObjects = putObject = null
cleanup = []
SIZE = if process.env.DRONE or process.env.CI then 'KBB' else 'KB'
COLOR = if process.env.DRONE or process.env.CI then 'RGB' else 'sRGB'
beforeEach ->
upload = new Upload process.env.AWS_BUCKET_NAME,
aws:
path: process.env.AWS_BUCKET_PATH
region: process.env.AWS_BUCKET_REGION
acl: 'public-read'
versions: [{
original: true
awsImageAcl: 'private'
},{
maxHeight: 1040
maxWidth: 1040
suffix: '-large'
quality: 80
},{
maxHeight: 780
maxWidth: 780
suffix: '-medium'
},{
maxHeight: 320
maxWidth: 320
suffix: '-small'
}]
# Mock S3 API calls
if process.env.INTEGRATION_TEST isnt 'true'
upload.s3.listObjects = (path, cb) ->
process.nextTick -> cb null, Contents: []
upload.s3.putObject = (opts, cb) ->
process.nextTick -> cb null, ETag: '"' + hash('md5').update(rand(32)).digest('hex') + '"'
# Clean up S3 objects
if process.env.INTEGRATION_TEST is 'true'
afterEach (done) ->
@timeout 40000
return process.nextTick done if cleanup.length is 0
upload.s3.deleteObjects Delete: Objects: cleanup, (err) ->
throw err if err
cleanup = []
done()
describe 'Upload', ->
describe 'constructor', ->
it 'should throw error for missing awsBucketName param', ->
assert.throws ->
new Upload()
, /Bucket name can not be undefined/
it 'should set default values if not provided', ->
upload = new Upload 'myBucket'
assert upload.s3 instanceof require('aws-sdk').S3
assert.equal upload.opts.aws.region, 'us-east-1'
assert.equal upload.opts.aws.path, ''
assert.equal upload.opts.aws.acl, 'privat'
assert.equal upload.opts.aws.maxRetries, 3
assert.equal upload.opts.aws.httpOptions.timeout, 10000
assert upload.opts.versions instanceof Array
assert.equal upload.opts.resizeQuality, 70
assert.equal upload.opts.returnExif, false
assert.equal upload.opts.tmpDir, '/tmp/'
assert.equal upload.opts.tmpPrefix, 'gm-'
assert.equal upload.opts.workers, 1
assert.equal upload.opts.url, 'https://s3-us-east-1.amazonaws.com/myBucket/'
it 'should set deprecated options correctly', ->
upload = new Upload 'myBucket',
awsBucketRegion: 'my-region'
awsBucketPath: '/some/path'
awsBucketAcl: 'some-acl'
awsMaxRetries: 24
awsHttpTimeout: 1337
awsAccessKeyId: 'public'
awsSecretAccessKey: 'secret'
assert.equal upload.opts.aws.region, 'my-region'
assert.equal upload.opts.aws.path, '/some/path'
assert.equal upload.opts.aws.acl, 'some-acl'
assert.equal upload.opts.aws.maxRetries, 24
assert.equal upload.opts.aws.httpOptions.timeout, 1337
assert.equal upload.opts.aws.accessKeyId, 'public'
assert.equal upload.opts.aws.secretAccessKey, 'secret'
it 'should set custom url', ->
upload = new Upload 'myBucket', url: 'http://cdn.app.com/'
assert.equal upload.opts.url, 'http://cdn.app.com/'
it 'should override default values'
it 'should connect to AWS S3 using environment variables', (done) ->
@timeout 10000
upload = new Upload process.env.AWS_BUCKET_NAME
upload.s3.headBucket Bucket: process.env.AWS_BUCKET_NAME, (err, data) ->
assert.ifError err
done()
it 'should connect to AWS S3 using constructor options', (done) ->
@timeout 10000
upload = new Upload process.env.AWS_BUCKET_NAME, aws:
accessKeyId: process.env.AWS_ACCESS_KEY_ID
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
upload.s3.headBucket Bucket: process.env.AWS_BUCKET_NAME, (err, data) ->
assert.ifError err
done()
describe '#_getRandomPath()', ->
it 'should return a new random path', ->
path = upload._getRandomPath()
assert(/^[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}$/.test(path))
describe '#_uploadPathIsAvailable()', ->
it 'should return true for avaiable path', (done) ->
upload.s3.listObjects = (opts, cb) -> process.nextTick -> cb null, Contents: []
upload._uploadPathIsAvailable 'some/path/', (err, path, isAvaiable) ->
assert.ifError err
assert.equal isAvaiable, true
done()
it 'should return false for unavaiable path', (done) ->
upload.s3.listObjects = (opts, cb) -> process.nextTick -> cb null, Contents: [opts.Prefix]
upload._uploadPathIsAvailable 'some/path/', (err, path, isAvaiable) ->
assert.ifError err
assert.equal isAvaiable, false
done()
describe '#_uploadGeneratePath()', ->
it 'should return an error if path is taken', (done) ->
upload._uploadPathIsAvailable = (path, cb) -> process.nextTick -> cb null, path, false
upload._uploadGeneratePath 'some/path/', (err, path) ->
assert /Path '[^']+' not avaiable!/.test err
done()
it 'should return an avaiable path', (done) ->
upload._uploadPathIsAvailable = (path, cb) -> process.nextTick -> cb null, path, true
upload._uploadGeneratePath 'some/path/', (err, path) ->
assert.ifError err
assert /^some\/path\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}$/.test(path)
done()
describe '#upload()', ->
it 'should use default aws path', (done) ->
upload._uploadGeneratePath = (prefix, cb) ->
assert.equal prefix, upload.opts.aws.path
done()
upload.upload 'dummy.jpg', {}
it 'should override default aws path', (done) ->
upload._uploadGeneratePath = (prefix, cb) ->
assert.equal prefix, '/my/new/path'
done()
upload.upload 'dummy.jpg', awsPath: '/my/new/path'
describe 'Image', ->
image = null
beforeEach ->
src = __dirname + '/assets/photo.jpg'
dest = 'images_test/Wm/PH/f3/I0'
opts = {}
image = new Upload.Image src, dest, opts, upload
describe 'constructor', ->
it 'should set default values', ->
assert image instanceof Upload.Image
assert image.config instanceof Upload
assert.equal image.src, __dirname + '/assets/photo.jpg'
assert.equal image.dest, 'images_test/Wm/PH/f3/I0'
assert /[a-z0-9]{24}/.test image.tmpName
assert.deepEqual image.meta, {}
assert.equal typeof image.gm, 'object'
describe '#getMeta()', ->
it 'should return image metadata', (done) ->
@timeout 10000
image.getMeta (err, meta) ->
assert.ifError err
assert.equal meta.format, 'jpeg'
assert.equal meta.fileSize, '617' + SIZE
assert.equal meta.imageSize.width, 1536
assert.equal meta.imageSize.height, 2048
assert.equal meta.orientation, 'Undefined'
assert.equal meta.colorSpace, COLOR
assert.equal meta.compression, 'JPEG'
assert.equal meta.quallity, '96'
assert.equal meta.exif, undefined
done()
it 'should store image matadata', (done) ->
@timeout 10000
image.getMeta (err) ->
assert.ifError err
assert.equal image.meta.format, 'jpeg'
assert.equal image.meta.fileSize, '617' + SIZE
assert.equal image.meta.imageSize.width, 1536
assert.equal image.meta.imageSize.height, 2048
assert.equal image.meta.orientation, 'Undefined'
assert.equal image.meta.colorSpace, COLOR
assert.equal image.meta.compression, 'JPEG'
assert.equal image.meta.quallity, '96'
assert.equal image.meta.exif, undefined
done()
it 'should return exif data if returnExif is set to true', (done) ->
@timeout 10000
image.config.opts.returnExif = true
image.getMeta (err) ->
assert.ifError err
assert.equal typeof image.meta.exif, 'object'
done()
it 'should store gm image instance', (done) ->
@timeout 10000
image.getMeta (err) ->
assert.ifError err
assert image.gm instanceof require('gm')
done()
describe '#resize()', ->
versions = null
beforeEach ->
versions = JSON.parse JSON.stringify upload.opts.versions
versions[0].suffix = ''
image.src = __dirname + '/assets/photo.jpg'
image.gm = gm image.src
image.tmpName = 'ed8d8b72071e731dc9065095c92c3e384d7c1e27'
image.meta =
format: 'jpeg'
fileSize: '617' + SIZE
imageSize: width: 1536, height: 2048
orientation: 'Undefined'
colorSpace: 'RGB'
compression: 'JPEG'
quallity: '96'
exif: undefined
it 'should return updated properties for original image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[0])), (err, version) ->
assert.ifError err
assert.deepEqual version,
original: true,
awsImageAcl: 'private'
suffix: ''
src: image.src
format: image.meta.format
size: image.meta.fileSize
width: image.meta.imageSize.width
height: image.meta.imageSize.height
done()
it 'should throw error when version original is false', ->
assert.throws ->
image.resize original: false
, '/version.original can not be false/'
it 'should return updated properties for resized image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
assert.deepEqual version,
suffix: versions[1].suffix
quality: versions[1].quality
format: 'jpeg'
src: '/tmp/gm-ed8d8b72071e731dc9065095c92c3e384d7c1e27-large.jpeg'
width: versions[1].maxWidth
height: versions[1].maxHeight
done()
it 'should write resized image to temp destination', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
fs.stat version.src, (err, stat) ->
assert.ifError err
assert.equal typeof stat, 'object'
done()
it 'should set hegith and width for reszied image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).size (err, value) ->
assert.ifError err
assert.deepEqual value,
width: 780
height: 1040
done()
it 'should set correct orientation for resized image', (done) ->
@timeout 10000
image.src = __dirname + '/assets/rotate.jpg'
image.gm = gm image.src
image.meta.orientation = 'TopLeft'
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Orientation, 'Undefined'
assert.equal value.size.width, 585
assert.equal value.size.height, 1040
done()
it 'should set colorspace to RGB for resized image', (done) ->
@timeout 10000
image.src = __dirname + '/assets/cmyk.jpg'
image.gm = gm image.src
image.meta.colorSpace = 'CMYK'
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Colorspace, COLOR
done()
it 'should set quality for resized image', (done) ->
@timeout 10000
versions[1].quality = 50
image.src = __dirname + '/assets/photo.jpg'
image.gm = gm image.src
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Quality, versions[1].quality
done()
describe '#upload()', ->
it 'should set object Key to correct location on AWS S3'
it 'should set ojbect ACL to specified ACL'
it 'should set object ACL to default if not specified'
it 'should set object Body to version src file'
it 'should set object ContentType according to version type'
it 'should set object Metadata from default metadata'
it 'should set object Metadata from upload metadata'
it 'should return updated version object on successfull upload'
describe '#resizeAndUpload()', ->
it 'should set version suffix if not provided'
it 'should resize and upload according to image version'
describe '#exec()', ->
it 'should get source image metadata'
it 'should make a copy of master version objects array'
it 'should resize and upload original image accroding to versions'
describe 'Integration Tests', ->
it 'should upload image to new random path', (done) ->
@timeout 40000
upload.upload __dirname + '/assets/photo.jpg', {}, (err, images, meta) ->
assert.ifError err
for image in images
cleanup.push Key: image.path if image.path # clean up in AWS
if image.original
assert.equal typeof image.size, 'string'
assert.equal typeof image.src, 'string'
assert.equal typeof image.format, 'string'
assert.equal typeof image.width, 'number'
assert.equal typeof image.height, 'number'
assert /[0-9a-f]{32}/.test image.etag
assert.equal typeof image.path, 'string'
assert.equal typeof image.url, 'string'
done()
it 'should not upload original if not in versions array', (done) ->
@timeout 40000
upload.opts.versions.shift()
upload.upload __dirname + '/assets/photo.jpg', {}, (err, images, meta) ->
assert.ifError err
for image in images
cleanup.push Key: image.path if image.path # clean up in AWS
assert.equal typeof image.original, 'undefined'
assert.equal typeof image.src, 'string'
assert.equal typeof image.format, 'string'
assert.equal typeof image.width, 'number'
assert.equal typeof image.height, 'number'
assert /[0-9a-f]{32}/.test image.etag
assert.equal typeof image.path, 'string'
assert.equal typeof image.url, 'string'
done()
| 13064 | assert = require 'assert'
Upload = require '../src/index.coffee'
fs = require('fs')
gm = require('gm').subClass imageMagick: true
hash = require('crypto').createHash
rand = require('crypto').pseudoRandomBytes
upload = listObjects = putObject = null
cleanup = []
SIZE = if process.env.DRONE or process.env.CI then 'KBB' else 'KB'
COLOR = if process.env.DRONE or process.env.CI then 'RGB' else 'sRGB'
beforeEach ->
upload = new Upload process.env.AWS_BUCKET_NAME,
aws:
path: process.env.AWS_BUCKET_PATH
region: process.env.AWS_BUCKET_REGION
acl: 'public-read'
versions: [{
original: true
awsImageAcl: 'private'
},{
maxHeight: 1040
maxWidth: 1040
suffix: '-large'
quality: 80
},{
maxHeight: 780
maxWidth: 780
suffix: '-medium'
},{
maxHeight: 320
maxWidth: 320
suffix: '-small'
}]
# Mock S3 API calls
if process.env.INTEGRATION_TEST isnt 'true'
upload.s3.listObjects = (path, cb) ->
process.nextTick -> cb null, Contents: []
upload.s3.putObject = (opts, cb) ->
process.nextTick -> cb null, ETag: '"' + hash('md5').update(rand(32)).digest('hex') + '"'
# Clean up S3 objects
if process.env.INTEGRATION_TEST is 'true'
afterEach (done) ->
@timeout 40000
return process.nextTick done if cleanup.length is 0
upload.s3.deleteObjects Delete: Objects: cleanup, (err) ->
throw err if err
cleanup = []
done()
describe 'Upload', ->
describe 'constructor', ->
it 'should throw error for missing awsBucketName param', ->
assert.throws ->
new Upload()
, /Bucket name can not be undefined/
it 'should set default values if not provided', ->
upload = new Upload 'myBucket'
assert upload.s3 instanceof require('aws-sdk').S3
assert.equal upload.opts.aws.region, 'us-east-1'
assert.equal upload.opts.aws.path, ''
assert.equal upload.opts.aws.acl, 'privat'
assert.equal upload.opts.aws.maxRetries, 3
assert.equal upload.opts.aws.httpOptions.timeout, 10000
assert upload.opts.versions instanceof Array
assert.equal upload.opts.resizeQuality, 70
assert.equal upload.opts.returnExif, false
assert.equal upload.opts.tmpDir, '/tmp/'
assert.equal upload.opts.tmpPrefix, 'gm-'
assert.equal upload.opts.workers, 1
assert.equal upload.opts.url, 'https://s3-us-east-1.amazonaws.com/myBucket/'
it 'should set deprecated options correctly', ->
upload = new Upload 'myBucket',
awsBucketRegion: 'my-region'
awsBucketPath: '/some/path'
awsBucketAcl: 'some-acl'
awsMaxRetries: 24
awsHttpTimeout: 1337
awsAccessKeyId: 'public'
awsSecretAccessKey: '<KEY>'
assert.equal upload.opts.aws.region, 'my-region'
assert.equal upload.opts.aws.path, '/some/path'
assert.equal upload.opts.aws.acl, 'some-acl'
assert.equal upload.opts.aws.maxRetries, 24
assert.equal upload.opts.aws.httpOptions.timeout, 1337
assert.equal upload.opts.aws.accessKeyId, 'public'
assert.equal upload.opts.aws.secretAccessKey, 'secret'
it 'should set custom url', ->
upload = new Upload 'myBucket', url: 'http://cdn.app.com/'
assert.equal upload.opts.url, 'http://cdn.app.com/'
it 'should override default values'
it 'should connect to AWS S3 using environment variables', (done) ->
@timeout 10000
upload = new Upload process.env.AWS_BUCKET_NAME
upload.s3.headBucket Bucket: process.env.AWS_BUCKET_NAME, (err, data) ->
assert.ifError err
done()
it 'should connect to AWS S3 using constructor options', (done) ->
@timeout 10000
upload = new Upload process.env.AWS_BUCKET_NAME, aws:
accessKeyId: process.env.AWS_ACCESS_KEY_ID
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
upload.s3.headBucket Bucket: process.env.AWS_BUCKET_NAME, (err, data) ->
assert.ifError err
done()
describe '#_getRandomPath()', ->
it 'should return a new random path', ->
path = upload._getRandomPath()
assert(/^[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}$/.test(path))
describe '#_uploadPathIsAvailable()', ->
it 'should return true for avaiable path', (done) ->
upload.s3.listObjects = (opts, cb) -> process.nextTick -> cb null, Contents: []
upload._uploadPathIsAvailable 'some/path/', (err, path, isAvaiable) ->
assert.ifError err
assert.equal isAvaiable, true
done()
it 'should return false for unavaiable path', (done) ->
upload.s3.listObjects = (opts, cb) -> process.nextTick -> cb null, Contents: [opts.Prefix]
upload._uploadPathIsAvailable 'some/path/', (err, path, isAvaiable) ->
assert.ifError err
assert.equal isAvaiable, false
done()
describe '#_uploadGeneratePath()', ->
it 'should return an error if path is taken', (done) ->
upload._uploadPathIsAvailable = (path, cb) -> process.nextTick -> cb null, path, false
upload._uploadGeneratePath 'some/path/', (err, path) ->
assert /Path '[^']+' not avaiable!/.test err
done()
it 'should return an avaiable path', (done) ->
upload._uploadPathIsAvailable = (path, cb) -> process.nextTick -> cb null, path, true
upload._uploadGeneratePath 'some/path/', (err, path) ->
assert.ifError err
assert /^some\/path\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}$/.test(path)
done()
describe '#upload()', ->
it 'should use default aws path', (done) ->
upload._uploadGeneratePath = (prefix, cb) ->
assert.equal prefix, upload.opts.aws.path
done()
upload.upload 'dummy.jpg', {}
it 'should override default aws path', (done) ->
upload._uploadGeneratePath = (prefix, cb) ->
assert.equal prefix, '/my/new/path'
done()
upload.upload 'dummy.jpg', awsPath: '/my/new/path'
describe 'Image', ->
image = null
beforeEach ->
src = __dirname + '/assets/photo.jpg'
dest = 'images_test/Wm/PH/f3/I0'
opts = {}
image = new Upload.Image src, dest, opts, upload
describe 'constructor', ->
it 'should set default values', ->
assert image instanceof Upload.Image
assert image.config instanceof Upload
assert.equal image.src, __dirname + '/assets/photo.jpg'
assert.equal image.dest, 'images_test/Wm/PH/f3/I0'
assert /[a-z0-9]{24}/.test image.tmpName
assert.deepEqual image.meta, {}
assert.equal typeof image.gm, 'object'
describe '#getMeta()', ->
it 'should return image metadata', (done) ->
@timeout 10000
image.getMeta (err, meta) ->
assert.ifError err
assert.equal meta.format, 'jpeg'
assert.equal meta.fileSize, '617' + SIZE
assert.equal meta.imageSize.width, 1536
assert.equal meta.imageSize.height, 2048
assert.equal meta.orientation, 'Undefined'
assert.equal meta.colorSpace, COLOR
assert.equal meta.compression, 'JPEG'
assert.equal meta.quallity, '96'
assert.equal meta.exif, undefined
done()
it 'should store image matadata', (done) ->
@timeout 10000
image.getMeta (err) ->
assert.ifError err
assert.equal image.meta.format, 'jpeg'
assert.equal image.meta.fileSize, '617' + SIZE
assert.equal image.meta.imageSize.width, 1536
assert.equal image.meta.imageSize.height, 2048
assert.equal image.meta.orientation, 'Undefined'
assert.equal image.meta.colorSpace, COLOR
assert.equal image.meta.compression, 'JPEG'
assert.equal image.meta.quallity, '96'
assert.equal image.meta.exif, undefined
done()
it 'should return exif data if returnExif is set to true', (done) ->
@timeout 10000
image.config.opts.returnExif = true
image.getMeta (err) ->
assert.ifError err
assert.equal typeof image.meta.exif, 'object'
done()
it 'should store gm image instance', (done) ->
@timeout 10000
image.getMeta (err) ->
assert.ifError err
assert image.gm instanceof require('gm')
done()
describe '#resize()', ->
versions = null
beforeEach ->
versions = JSON.parse JSON.stringify upload.opts.versions
versions[0].suffix = ''
image.src = __dirname + '/assets/photo.jpg'
image.gm = gm image.src
image.tmpName = 'ed8d8b72071e731dc9065095c92c3e384d7c1e27'
image.meta =
format: 'jpeg'
fileSize: '617' + SIZE
imageSize: width: 1536, height: 2048
orientation: 'Undefined'
colorSpace: 'RGB'
compression: 'JPEG'
quallity: '96'
exif: undefined
it 'should return updated properties for original image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[0])), (err, version) ->
assert.ifError err
assert.deepEqual version,
original: true,
awsImageAcl: 'private'
suffix: ''
src: image.src
format: image.meta.format
size: image.meta.fileSize
width: image.meta.imageSize.width
height: image.meta.imageSize.height
done()
it 'should throw error when version original is false', ->
assert.throws ->
image.resize original: false
, '/version.original can not be false/'
it 'should return updated properties for resized image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
assert.deepEqual version,
suffix: versions[1].suffix
quality: versions[1].quality
format: 'jpeg'
src: '/tmp/gm-ed8d8b72071e731dc9065095c92c3e384d7c1e27-large.jpeg'
width: versions[1].maxWidth
height: versions[1].maxHeight
done()
it 'should write resized image to temp destination', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
fs.stat version.src, (err, stat) ->
assert.ifError err
assert.equal typeof stat, 'object'
done()
it 'should set hegith and width for reszied image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).size (err, value) ->
assert.ifError err
assert.deepEqual value,
width: 780
height: 1040
done()
it 'should set correct orientation for resized image', (done) ->
@timeout 10000
image.src = __dirname + '/assets/rotate.jpg'
image.gm = gm image.src
image.meta.orientation = 'TopLeft'
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Orientation, 'Undefined'
assert.equal value.size.width, 585
assert.equal value.size.height, 1040
done()
it 'should set colorspace to RGB for resized image', (done) ->
@timeout 10000
image.src = __dirname + '/assets/cmyk.jpg'
image.gm = gm image.src
image.meta.colorSpace = 'CMYK'
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Colorspace, COLOR
done()
it 'should set quality for resized image', (done) ->
@timeout 10000
versions[1].quality = 50
image.src = __dirname + '/assets/photo.jpg'
image.gm = gm image.src
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Quality, versions[1].quality
done()
describe '#upload()', ->
it 'should set object Key to correct location on AWS S3'
it 'should set ojbect ACL to specified ACL'
it 'should set object ACL to default if not specified'
it 'should set object Body to version src file'
it 'should set object ContentType according to version type'
it 'should set object Metadata from default metadata'
it 'should set object Metadata from upload metadata'
it 'should return updated version object on successfull upload'
describe '#resizeAndUpload()', ->
it 'should set version suffix if not provided'
it 'should resize and upload according to image version'
describe '#exec()', ->
it 'should get source image metadata'
it 'should make a copy of master version objects array'
it 'should resize and upload original image accroding to versions'
describe 'Integration Tests', ->
it 'should upload image to new random path', (done) ->
@timeout 40000
upload.upload __dirname + '/assets/photo.jpg', {}, (err, images, meta) ->
assert.ifError err
for image in images
cleanup.push Key: image.path if image.path # clean up in AWS
if image.original
assert.equal typeof image.size, 'string'
assert.equal typeof image.src, 'string'
assert.equal typeof image.format, 'string'
assert.equal typeof image.width, 'number'
assert.equal typeof image.height, 'number'
assert /[0-9a-f]{32}/.test image.etag
assert.equal typeof image.path, 'string'
assert.equal typeof image.url, 'string'
done()
it 'should not upload original if not in versions array', (done) ->
@timeout 40000
upload.opts.versions.shift()
upload.upload __dirname + '/assets/photo.jpg', {}, (err, images, meta) ->
assert.ifError err
for image in images
cleanup.push Key: image.path if image.path # clean up in AWS
assert.equal typeof image.original, 'undefined'
assert.equal typeof image.src, 'string'
assert.equal typeof image.format, 'string'
assert.equal typeof image.width, 'number'
assert.equal typeof image.height, 'number'
assert /[0-9a-f]{32}/.test image.etag
assert.equal typeof image.path, 'string'
assert.equal typeof image.url, 'string'
done()
| true | assert = require 'assert'
Upload = require '../src/index.coffee'
fs = require('fs')
gm = require('gm').subClass imageMagick: true
hash = require('crypto').createHash
rand = require('crypto').pseudoRandomBytes
upload = listObjects = putObject = null
cleanup = []
SIZE = if process.env.DRONE or process.env.CI then 'KBB' else 'KB'
COLOR = if process.env.DRONE or process.env.CI then 'RGB' else 'sRGB'
beforeEach ->
upload = new Upload process.env.AWS_BUCKET_NAME,
aws:
path: process.env.AWS_BUCKET_PATH
region: process.env.AWS_BUCKET_REGION
acl: 'public-read'
versions: [{
original: true
awsImageAcl: 'private'
},{
maxHeight: 1040
maxWidth: 1040
suffix: '-large'
quality: 80
},{
maxHeight: 780
maxWidth: 780
suffix: '-medium'
},{
maxHeight: 320
maxWidth: 320
suffix: '-small'
}]
# Mock S3 API calls
if process.env.INTEGRATION_TEST isnt 'true'
upload.s3.listObjects = (path, cb) ->
process.nextTick -> cb null, Contents: []
upload.s3.putObject = (opts, cb) ->
process.nextTick -> cb null, ETag: '"' + hash('md5').update(rand(32)).digest('hex') + '"'
# Clean up S3 objects
if process.env.INTEGRATION_TEST is 'true'
afterEach (done) ->
@timeout 40000
return process.nextTick done if cleanup.length is 0
upload.s3.deleteObjects Delete: Objects: cleanup, (err) ->
throw err if err
cleanup = []
done()
describe 'Upload', ->
describe 'constructor', ->
it 'should throw error for missing awsBucketName param', ->
assert.throws ->
new Upload()
, /Bucket name can not be undefined/
it 'should set default values if not provided', ->
upload = new Upload 'myBucket'
assert upload.s3 instanceof require('aws-sdk').S3
assert.equal upload.opts.aws.region, 'us-east-1'
assert.equal upload.opts.aws.path, ''
assert.equal upload.opts.aws.acl, 'privat'
assert.equal upload.opts.aws.maxRetries, 3
assert.equal upload.opts.aws.httpOptions.timeout, 10000
assert upload.opts.versions instanceof Array
assert.equal upload.opts.resizeQuality, 70
assert.equal upload.opts.returnExif, false
assert.equal upload.opts.tmpDir, '/tmp/'
assert.equal upload.opts.tmpPrefix, 'gm-'
assert.equal upload.opts.workers, 1
assert.equal upload.opts.url, 'https://s3-us-east-1.amazonaws.com/myBucket/'
it 'should set deprecated options correctly', ->
upload = new Upload 'myBucket',
awsBucketRegion: 'my-region'
awsBucketPath: '/some/path'
awsBucketAcl: 'some-acl'
awsMaxRetries: 24
awsHttpTimeout: 1337
awsAccessKeyId: 'public'
awsSecretAccessKey: 'PI:KEY:<KEY>END_PI'
assert.equal upload.opts.aws.region, 'my-region'
assert.equal upload.opts.aws.path, '/some/path'
assert.equal upload.opts.aws.acl, 'some-acl'
assert.equal upload.opts.aws.maxRetries, 24
assert.equal upload.opts.aws.httpOptions.timeout, 1337
assert.equal upload.opts.aws.accessKeyId, 'public'
assert.equal upload.opts.aws.secretAccessKey, 'secret'
it 'should set custom url', ->
upload = new Upload 'myBucket', url: 'http://cdn.app.com/'
assert.equal upload.opts.url, 'http://cdn.app.com/'
it 'should override default values'
it 'should connect to AWS S3 using environment variables', (done) ->
@timeout 10000
upload = new Upload process.env.AWS_BUCKET_NAME
upload.s3.headBucket Bucket: process.env.AWS_BUCKET_NAME, (err, data) ->
assert.ifError err
done()
it 'should connect to AWS S3 using constructor options', (done) ->
@timeout 10000
upload = new Upload process.env.AWS_BUCKET_NAME, aws:
accessKeyId: process.env.AWS_ACCESS_KEY_ID
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
upload.s3.headBucket Bucket: process.env.AWS_BUCKET_NAME, (err, data) ->
assert.ifError err
done()
describe '#_getRandomPath()', ->
it 'should return a new random path', ->
path = upload._getRandomPath()
assert(/^[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}$/.test(path))
describe '#_uploadPathIsAvailable()', ->
it 'should return true for avaiable path', (done) ->
upload.s3.listObjects = (opts, cb) -> process.nextTick -> cb null, Contents: []
upload._uploadPathIsAvailable 'some/path/', (err, path, isAvaiable) ->
assert.ifError err
assert.equal isAvaiable, true
done()
it 'should return false for unavaiable path', (done) ->
upload.s3.listObjects = (opts, cb) -> process.nextTick -> cb null, Contents: [opts.Prefix]
upload._uploadPathIsAvailable 'some/path/', (err, path, isAvaiable) ->
assert.ifError err
assert.equal isAvaiable, false
done()
describe '#_uploadGeneratePath()', ->
it 'should return an error if path is taken', (done) ->
upload._uploadPathIsAvailable = (path, cb) -> process.nextTick -> cb null, path, false
upload._uploadGeneratePath 'some/path/', (err, path) ->
assert /Path '[^']+' not avaiable!/.test err
done()
it 'should return an avaiable path', (done) ->
upload._uploadPathIsAvailable = (path, cb) -> process.nextTick -> cb null, path, true
upload._uploadGeneratePath 'some/path/', (err, path) ->
assert.ifError err
assert /^some\/path\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}\/[A-Za-z0-9]{2}$/.test(path)
done()
describe '#upload()', ->
it 'should use default aws path', (done) ->
upload._uploadGeneratePath = (prefix, cb) ->
assert.equal prefix, upload.opts.aws.path
done()
upload.upload 'dummy.jpg', {}
it 'should override default aws path', (done) ->
upload._uploadGeneratePath = (prefix, cb) ->
assert.equal prefix, '/my/new/path'
done()
upload.upload 'dummy.jpg', awsPath: '/my/new/path'
describe 'Image', ->
image = null
beforeEach ->
src = __dirname + '/assets/photo.jpg'
dest = 'images_test/Wm/PH/f3/I0'
opts = {}
image = new Upload.Image src, dest, opts, upload
describe 'constructor', ->
it 'should set default values', ->
assert image instanceof Upload.Image
assert image.config instanceof Upload
assert.equal image.src, __dirname + '/assets/photo.jpg'
assert.equal image.dest, 'images_test/Wm/PH/f3/I0'
assert /[a-z0-9]{24}/.test image.tmpName
assert.deepEqual image.meta, {}
assert.equal typeof image.gm, 'object'
describe '#getMeta()', ->
it 'should return image metadata', (done) ->
@timeout 10000
image.getMeta (err, meta) ->
assert.ifError err
assert.equal meta.format, 'jpeg'
assert.equal meta.fileSize, '617' + SIZE
assert.equal meta.imageSize.width, 1536
assert.equal meta.imageSize.height, 2048
assert.equal meta.orientation, 'Undefined'
assert.equal meta.colorSpace, COLOR
assert.equal meta.compression, 'JPEG'
assert.equal meta.quallity, '96'
assert.equal meta.exif, undefined
done()
it 'should store image matadata', (done) ->
@timeout 10000
image.getMeta (err) ->
assert.ifError err
assert.equal image.meta.format, 'jpeg'
assert.equal image.meta.fileSize, '617' + SIZE
assert.equal image.meta.imageSize.width, 1536
assert.equal image.meta.imageSize.height, 2048
assert.equal image.meta.orientation, 'Undefined'
assert.equal image.meta.colorSpace, COLOR
assert.equal image.meta.compression, 'JPEG'
assert.equal image.meta.quallity, '96'
assert.equal image.meta.exif, undefined
done()
it 'should return exif data if returnExif is set to true', (done) ->
@timeout 10000
image.config.opts.returnExif = true
image.getMeta (err) ->
assert.ifError err
assert.equal typeof image.meta.exif, 'object'
done()
it 'should store gm image instance', (done) ->
@timeout 10000
image.getMeta (err) ->
assert.ifError err
assert image.gm instanceof require('gm')
done()
describe '#resize()', ->
versions = null
beforeEach ->
versions = JSON.parse JSON.stringify upload.opts.versions
versions[0].suffix = ''
image.src = __dirname + '/assets/photo.jpg'
image.gm = gm image.src
image.tmpName = 'ed8d8b72071e731dc9065095c92c3e384d7c1e27'
image.meta =
format: 'jpeg'
fileSize: '617' + SIZE
imageSize: width: 1536, height: 2048
orientation: 'Undefined'
colorSpace: 'RGB'
compression: 'JPEG'
quallity: '96'
exif: undefined
it 'should return updated properties for original image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[0])), (err, version) ->
assert.ifError err
assert.deepEqual version,
original: true,
awsImageAcl: 'private'
suffix: ''
src: image.src
format: image.meta.format
size: image.meta.fileSize
width: image.meta.imageSize.width
height: image.meta.imageSize.height
done()
it 'should throw error when version original is false', ->
assert.throws ->
image.resize original: false
, '/version.original can not be false/'
it 'should return updated properties for resized image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
assert.deepEqual version,
suffix: versions[1].suffix
quality: versions[1].quality
format: 'jpeg'
src: '/tmp/gm-ed8d8b72071e731dc9065095c92c3e384d7c1e27-large.jpeg'
width: versions[1].maxWidth
height: versions[1].maxHeight
done()
it 'should write resized image to temp destination', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
fs.stat version.src, (err, stat) ->
assert.ifError err
assert.equal typeof stat, 'object'
done()
it 'should set hegith and width for reszied image', (done) ->
@timeout 10000
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).size (err, value) ->
assert.ifError err
assert.deepEqual value,
width: 780
height: 1040
done()
it 'should set correct orientation for resized image', (done) ->
@timeout 10000
image.src = __dirname + '/assets/rotate.jpg'
image.gm = gm image.src
image.meta.orientation = 'TopLeft'
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Orientation, 'Undefined'
assert.equal value.size.width, 585
assert.equal value.size.height, 1040
done()
it 'should set colorspace to RGB for resized image', (done) ->
@timeout 10000
image.src = __dirname + '/assets/cmyk.jpg'
image.gm = gm image.src
image.meta.colorSpace = 'CMYK'
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Colorspace, COLOR
done()
it 'should set quality for resized image', (done) ->
@timeout 10000
versions[1].quality = 50
image.src = __dirname + '/assets/photo.jpg'
image.gm = gm image.src
image.resize JSON.parse(JSON.stringify(versions[1])), (err, version) ->
assert.ifError err
gm(version.src).identify (err, value) ->
assert.ifError err
assert.equal value.Quality, versions[1].quality
done()
describe '#upload()', ->
it 'should set object Key to correct location on AWS S3'
it 'should set ojbect ACL to specified ACL'
it 'should set object ACL to default if not specified'
it 'should set object Body to version src file'
it 'should set object ContentType according to version type'
it 'should set object Metadata from default metadata'
it 'should set object Metadata from upload metadata'
it 'should return updated version object on successfull upload'
describe '#resizeAndUpload()', ->
it 'should set version suffix if not provided'
it 'should resize and upload according to image version'
describe '#exec()', ->
it 'should get source image metadata'
it 'should make a copy of master version objects array'
it 'should resize and upload original image accroding to versions'
describe 'Integration Tests', ->
it 'should upload image to new random path', (done) ->
@timeout 40000
upload.upload __dirname + '/assets/photo.jpg', {}, (err, images, meta) ->
assert.ifError err
for image in images
cleanup.push Key: image.path if image.path # clean up in AWS
if image.original
assert.equal typeof image.size, 'string'
assert.equal typeof image.src, 'string'
assert.equal typeof image.format, 'string'
assert.equal typeof image.width, 'number'
assert.equal typeof image.height, 'number'
assert /[0-9a-f]{32}/.test image.etag
assert.equal typeof image.path, 'string'
assert.equal typeof image.url, 'string'
done()
it 'should not upload original if not in versions array', (done) ->
@timeout 40000
upload.opts.versions.shift()
upload.upload __dirname + '/assets/photo.jpg', {}, (err, images, meta) ->
assert.ifError err
for image in images
cleanup.push Key: image.path if image.path # clean up in AWS
assert.equal typeof image.original, 'undefined'
assert.equal typeof image.src, 'string'
assert.equal typeof image.format, 'string'
assert.equal typeof image.width, 'number'
assert.equal typeof image.height, 'number'
assert /[0-9a-f]{32}/.test image.etag
assert.equal typeof image.path, 'string'
assert.equal typeof image.url, 'string'
done()
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998539090156555,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/plugins/block.coffee | codemix/hallo | 1 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.halloblock',
options:
editable: null
toolbar: null
uuid: ''
elements: [
'h1'
'h2'
'h3'
'p'
'pre'
'blockquote'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append buttonset
buttonset.hallobuttonset()
buttonset.append target
buttonset.append @_prepareButton target
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"></div>"
containingElement = @options.editable.element.get(0).tagName.toLowerCase()
addElement = (element) =>
el = jQuery "<button class='blockselector'>
<#{element} class=\"menu-item\">#{element}</#{element}>
</button>"
if containingElement is element
el.addClass 'selected'
unless containingElement is 'div'
el.addClass 'disabled'
el.on 'click', =>
tagName = element.toUpperCase()
if el.hasClass 'disabled'
return
if navigator.appName is 'Microsoft Internet Explorer'
# In IE FormatBlock wants tags inside brackets
@options.editable.execute 'FormatBlock', "<#{tagName}>"
return
@options.editable.execute 'formatBlock', tagName
queryState = (event) =>
block = document.queryCommandValue 'formatBlock'
if block.toLowerCase() is element
el.addClass 'selected'
return
el.removeClass 'selected'
events = 'keyup paste change mouseup'
@options.editable.element.on events, queryState
@options.editable.element.on 'halloenabled', =>
@options.editable.element.on events, queryState
@options.editable.element.on 'hallodisabled', =>
@options.editable.element.off events, queryState
el
for element in @options.elements
contentArea.append addElement element
contentArea
_prepareButton: (target) ->
buttonElement = jQuery '<span></span>'
buttonElement.hallodropdownbutton
uuid: @options.uuid
editable: @options.editable
label: 'block'
icon: 'icon-text-height'
target: target
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
| 58929 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.halloblock',
options:
editable: null
toolbar: null
uuid: ''
elements: [
'h1'
'h2'
'h3'
'p'
'pre'
'blockquote'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append buttonset
buttonset.hallobuttonset()
buttonset.append target
buttonset.append @_prepareButton target
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"></div>"
containingElement = @options.editable.element.get(0).tagName.toLowerCase()
addElement = (element) =>
el = jQuery "<button class='blockselector'>
<#{element} class=\"menu-item\">#{element}</#{element}>
</button>"
if containingElement is element
el.addClass 'selected'
unless containingElement is 'div'
el.addClass 'disabled'
el.on 'click', =>
tagName = element.toUpperCase()
if el.hasClass 'disabled'
return
if navigator.appName is 'Microsoft Internet Explorer'
# In IE FormatBlock wants tags inside brackets
@options.editable.execute 'FormatBlock', "<#{tagName}>"
return
@options.editable.execute 'formatBlock', tagName
queryState = (event) =>
block = document.queryCommandValue 'formatBlock'
if block.toLowerCase() is element
el.addClass 'selected'
return
el.removeClass 'selected'
events = 'keyup paste change mouseup'
@options.editable.element.on events, queryState
@options.editable.element.on 'halloenabled', =>
@options.editable.element.on events, queryState
@options.editable.element.on 'hallodisabled', =>
@options.editable.element.off events, queryState
el
for element in @options.elements
contentArea.append addElement element
contentArea
_prepareButton: (target) ->
buttonElement = jQuery '<span></span>'
buttonElement.hallodropdownbutton
uuid: @options.uuid
editable: @options.editable
label: 'block'
icon: 'icon-text-height'
target: target
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.halloblock',
options:
editable: null
toolbar: null
uuid: ''
elements: [
'h1'
'h2'
'h3'
'p'
'pre'
'blockquote'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append buttonset
buttonset.hallobuttonset()
buttonset.append target
buttonset.append @_prepareButton target
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"></div>"
containingElement = @options.editable.element.get(0).tagName.toLowerCase()
addElement = (element) =>
el = jQuery "<button class='blockselector'>
<#{element} class=\"menu-item\">#{element}</#{element}>
</button>"
if containingElement is element
el.addClass 'selected'
unless containingElement is 'div'
el.addClass 'disabled'
el.on 'click', =>
tagName = element.toUpperCase()
if el.hasClass 'disabled'
return
if navigator.appName is 'Microsoft Internet Explorer'
# In IE FormatBlock wants tags inside brackets
@options.editable.execute 'FormatBlock', "<#{tagName}>"
return
@options.editable.execute 'formatBlock', tagName
queryState = (event) =>
block = document.queryCommandValue 'formatBlock'
if block.toLowerCase() is element
el.addClass 'selected'
return
el.removeClass 'selected'
events = 'keyup paste change mouseup'
@options.editable.element.on events, queryState
@options.editable.element.on 'halloenabled', =>
@options.editable.element.on events, queryState
@options.editable.element.on 'hallodisabled', =>
@options.editable.element.off events, queryState
el
for element in @options.elements
contentArea.append addElement element
contentArea
_prepareButton: (target) ->
buttonElement = jQuery '<span></span>'
buttonElement.hallodropdownbutton
uuid: @options.uuid
editable: @options.editable
label: 'block'
icon: 'icon-text-height'
target: target
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
|
[
{
"context": "leEmitter.on 'tapend', () => @bus.post(\"Circle\", \"Francis Ford Coppola\")\n @triangleEmitter.on 'tapend', () => @bus.po",
"end": 992,
"score": 0.9997887015342712,
"start": 972,
"tag": "NAME",
"value": "Francis Ford Coppola"
},
{
"context": ".on 'tapend', () => @bu... | Santa Maria/ui/coffee/slideshow/event_data_presenter.coffee | coshx/santa-maria | 1 | class EventDataPresenter extends BasePresenter
onCreate: () ->
@bus = Caravel.get("EventData")
@crossReceiver = $('.js-cross-receiver')
@circleReceiver = $('.js-circle-receiver')
@triangleReceiver = $('.js-triangle-receiver')
@squareReceiver = $('.js-square-receiver')
@crossEmitter = $('.js-cross-emitter')
@circleEmitter = $('.js-circle-emitter')
@triangleEmitter = $('.js-triangle-emitter')
@squareEmitter = $('.js-square-emitter')
@addHoldEffect(@crossEmitter)
@addHoldEffect(@circleEmitter)
@addHoldEffect(@triangleEmitter)
@addHoldEffect(@squareEmitter)
@bus.register "Cross", () => @pulse(@crossReceiver)
@bus.register "Circle", () => @pulse(@circleReceiver)
@bus.register "Triangle", () => @pulse(@triangleReceiver)
@bus.register "Square", () => @pulse(@squareReceiver)
@crossEmitter.on 'tapend', () => @bus.post("Cross", 42)
@circleEmitter.on 'tapend', () => @bus.post("Circle", "Francis Ford Coppola")
@triangleEmitter.on 'tapend', () => @bus.post("Triangle", [1, 2, 3, 5, 8])
@squareEmitter.on 'tapend', () => @bus.post("Square", {"name": "Bob", age: 71}) | 180475 | class EventDataPresenter extends BasePresenter
onCreate: () ->
@bus = Caravel.get("EventData")
@crossReceiver = $('.js-cross-receiver')
@circleReceiver = $('.js-circle-receiver')
@triangleReceiver = $('.js-triangle-receiver')
@squareReceiver = $('.js-square-receiver')
@crossEmitter = $('.js-cross-emitter')
@circleEmitter = $('.js-circle-emitter')
@triangleEmitter = $('.js-triangle-emitter')
@squareEmitter = $('.js-square-emitter')
@addHoldEffect(@crossEmitter)
@addHoldEffect(@circleEmitter)
@addHoldEffect(@triangleEmitter)
@addHoldEffect(@squareEmitter)
@bus.register "Cross", () => @pulse(@crossReceiver)
@bus.register "Circle", () => @pulse(@circleReceiver)
@bus.register "Triangle", () => @pulse(@triangleReceiver)
@bus.register "Square", () => @pulse(@squareReceiver)
@crossEmitter.on 'tapend', () => @bus.post("Cross", 42)
@circleEmitter.on 'tapend', () => @bus.post("Circle", "<NAME>")
@triangleEmitter.on 'tapend', () => @bus.post("Triangle", [1, 2, 3, 5, 8])
@squareEmitter.on 'tapend', () => @bus.post("Square", {"name": "<NAME>", age: 71}) | true | class EventDataPresenter extends BasePresenter
onCreate: () ->
@bus = Caravel.get("EventData")
@crossReceiver = $('.js-cross-receiver')
@circleReceiver = $('.js-circle-receiver')
@triangleReceiver = $('.js-triangle-receiver')
@squareReceiver = $('.js-square-receiver')
@crossEmitter = $('.js-cross-emitter')
@circleEmitter = $('.js-circle-emitter')
@triangleEmitter = $('.js-triangle-emitter')
@squareEmitter = $('.js-square-emitter')
@addHoldEffect(@crossEmitter)
@addHoldEffect(@circleEmitter)
@addHoldEffect(@triangleEmitter)
@addHoldEffect(@squareEmitter)
@bus.register "Cross", () => @pulse(@crossReceiver)
@bus.register "Circle", () => @pulse(@circleReceiver)
@bus.register "Triangle", () => @pulse(@triangleReceiver)
@bus.register "Square", () => @pulse(@squareReceiver)
@crossEmitter.on 'tapend', () => @bus.post("Cross", 42)
@circleEmitter.on 'tapend', () => @bus.post("Circle", "PI:NAME:<NAME>END_PI")
@triangleEmitter.on 'tapend', () => @bus.post("Triangle", [1, 2, 3, 5, 8])
@squareEmitter.on 'tapend', () => @bus.post("Square", {"name": "PI:NAME:<NAME>END_PI", age: 71}) |
[
{
"context": "###\n# @author Argi Karunia <https:#github.com/hkyo89>\n# @link https:#gith",
"end": 27,
"score": 0.9998752474784851,
"start": 15,
"tag": "NAME",
"value": "Argi Karunia"
},
{
"context": "###\n# @author Argi Karunia <https:#github.com/hkyo89>\n# @link https:#gith... | src/app.coffee | tokopedia/nodame | 2 | ###
# @author Argi Karunia <https:#github.com/hkyo89>
# @link https:#github.com/tokopedia/nodame
# @license http:#opensource.org/licenses/MIT
#
# @version 1.0.0
###
# third-party modules
CookieParser = require('cookie-parser')
BodyParser = require('body-parser')
XMLBodyParser = require('express-xml-bodyparser')
MethodOverride = require('method-override')
ExpressDevice = require('express-device')
YAMLParser = require('js-yaml')
fs = require('fs')
Async = require('async')
# private modules
Router = require('./router')
View = require('./view')
Locals = require('./locals')
Path = require('./path')
File = require('./file')
Logger = require('./logger')
Parser = require('./parser')
# expressjs initialization
app = nodame.express()
app.env = nodame.env()
# load package information
package_path = Path.safe("#{nodame.sysPath()}/package.json")
Package = File.readJSON(package_path)
nodame.set 'app',
name : Package.name
version : Package.version
homepage: Package.homepage
authors : Package.authors
license : Package.license
# local variables
is_dev = nodame.isDev()
app_path = nodame.appPath()
CONFIG = nodame.config()
# trust proxy setup
app.set('trust proxy', 'uniquelocal')
app.enable('trust proxy')
# load and store assets config
assets_file = if is_dev then 'assets.yaml' else '.assets'
assets_stream = Path.safe("#{app_path}/configs/#{assets_file}")
if is_dev
assets = fs.readFileSync(assets_stream)
assets = YAMLParser.safeLoad(assets)
assets = Parser.to_grunt(assets)
else
assets = File.readJSON(assets_stream)
nodame.set('assets', assets)
# Load build data
build_data_stream = Path.safe("#{app_path}/configs/.build")
build_data = File.readJSON(build_data_stream)
nodame.set('build', build_data)
# x-powered-by header
app.set('x-powered-by', CONFIG.server.powered_by)
# Device capture setup
app.use(ExpressDevice.capture()) if CONFIG.view.device_capture
# log setup
# TODO: disable logger
app.use(Logger.error())
app.use(Logger.output())
# block favicon request
block_favicon = (req, res, next) ->
if req.url is '/favicon.ico'
res.writeHead(200, {'Content-Type': 'image/x-icon'})
res.end()
else
next()
return
app.use(block_favicon) if CONFIG.server.block_favicon
# static server setup
if CONFIG.assets.enable_server
ServeStatic = require('serve-static')
module_root = CONFIG.module.root
unless module_root[0] is '/'
module_root = "/#{module_root}"
static_route = CONFIG.assets.route
if static_route[0] is '/'
static_route = static_route.substr(1)
#TODO FIX THIS FOR WINDOW
static_route = "#{module_root}/#{static_route}"
static_dir = Path.safe("#{app_path}/#{CONFIG.assets.dir}")
app.use(static_route, ServeStatic(static_dir))
# view engine setup
new View(app)
# redirect non-https on production
enforce_secure = (req, res, next) ->
unless is_dev and req.secure
res.redirect("#{CONFIG.url.hostname}#{req.originalUrl}")
next = false
return next() if next
app.use(enforce_secure) if not is_dev and CONFIG.server.enforce_secure
# middlewares Setups
app.use(BodyParser.json())
app.use(BodyParser.urlencoded({ extended: false }))
app.use(XMLBodyParser())
app.use(CookieParser(nodame.config('cookie.secret')))
app.use(MethodOverride())
# Locals setup
locals = new Locals()
locals.set(app)
# i18n setup
require('./locale')(app)
# numeral setup
require('./numeral')(app)
# enforce mobile setup
enforce_mobile = CONFIG.view.device_capture and CONFIG.view.enforce_mobile
app.use(nodame.enforce_mobile()) if enforce_mobile
# locals helper setup
local_path_helper = (req, res, next) ->
fullpath = req.originalUrl
appName = CONFIG.app.name
res.locals.path =
full : fullpath
module : fullpath.replace("/#{appName}", '')
return next() if next
app.use(nodame.locals(app))
app.use(local_path_helper)
# maintenance setup
server_maintenance = (req, res, next) ->
# Bypass whitelist_ips
return next() if next and nodame.is_whitelist(req.ips)
# Set maintenance
Render = require('./render')
render = new Render(req, res)
Async.waterfall [
(cb) => render.cache("error:maintenance", true, cb)
], (err, is_cache) =>
unless is_cache
render.path('errors/503')
render.code(503)
render.send()
return undefined
return
app.use(server_maintenance) if CONFIG.server.maintenance
# routes setup
new Router(app)
# hooks setup
if CONFIG.server.hooks.length > 0
nodame.require("hook/#{hook}") for hook in CONFIG.server.hooks
# errors setup
require('./error')(app)
module.exports = app
| 214022 | ###
# @author <NAME> <https:#github.com/hkyo89>
# @link https:#github.com/tokopedia/nodame
# @license http:#opensource.org/licenses/MIT
#
# @version 1.0.0
###
# third-party modules
CookieParser = require('cookie-parser')
BodyParser = require('body-parser')
XMLBodyParser = require('express-xml-bodyparser')
MethodOverride = require('method-override')
ExpressDevice = require('express-device')
YAMLParser = require('js-yaml')
fs = require('fs')
Async = require('async')
# private modules
Router = require('./router')
View = require('./view')
Locals = require('./locals')
Path = require('./path')
File = require('./file')
Logger = require('./logger')
Parser = require('./parser')
# expressjs initialization
app = nodame.express()
app.env = nodame.env()
# load package information
package_path = Path.safe("#{nodame.sysPath()}/package.json")
Package = File.readJSON(package_path)
nodame.set 'app',
name : Package.name
version : Package.version
homepage: Package.homepage
authors : Package.authors
license : Package.license
# local variables
is_dev = nodame.isDev()
app_path = nodame.appPath()
CONFIG = nodame.config()
# trust proxy setup
app.set('trust proxy', 'uniquelocal')
app.enable('trust proxy')
# load and store assets config
assets_file = if is_dev then 'assets.yaml' else '.assets'
assets_stream = Path.safe("#{app_path}/configs/#{assets_file}")
if is_dev
assets = fs.readFileSync(assets_stream)
assets = YAMLParser.safeLoad(assets)
assets = Parser.to_grunt(assets)
else
assets = File.readJSON(assets_stream)
nodame.set('assets', assets)
# Load build data
build_data_stream = Path.safe("#{app_path}/configs/.build")
build_data = File.readJSON(build_data_stream)
nodame.set('build', build_data)
# x-powered-by header
app.set('x-powered-by', CONFIG.server.powered_by)
# Device capture setup
app.use(ExpressDevice.capture()) if CONFIG.view.device_capture
# log setup
# TODO: disable logger
app.use(Logger.error())
app.use(Logger.output())
# block favicon request
block_favicon = (req, res, next) ->
if req.url is '/favicon.ico'
res.writeHead(200, {'Content-Type': 'image/x-icon'})
res.end()
else
next()
return
app.use(block_favicon) if CONFIG.server.block_favicon
# static server setup
if CONFIG.assets.enable_server
ServeStatic = require('serve-static')
module_root = CONFIG.module.root
unless module_root[0] is '/'
module_root = "/#{module_root}"
static_route = CONFIG.assets.route
if static_route[0] is '/'
static_route = static_route.substr(1)
#TODO FIX THIS FOR WINDOW
static_route = "#{module_root}/#{static_route}"
static_dir = Path.safe("#{app_path}/#{CONFIG.assets.dir}")
app.use(static_route, ServeStatic(static_dir))
# view engine setup
new View(app)
# redirect non-https on production
enforce_secure = (req, res, next) ->
unless is_dev and req.secure
res.redirect("#{CONFIG.url.hostname}#{req.originalUrl}")
next = false
return next() if next
app.use(enforce_secure) if not is_dev and CONFIG.server.enforce_secure
# middlewares Setups
app.use(BodyParser.json())
app.use(BodyParser.urlencoded({ extended: false }))
app.use(XMLBodyParser())
app.use(CookieParser(nodame.config('cookie.secret')))
app.use(MethodOverride())
# Locals setup
locals = new Locals()
locals.set(app)
# i18n setup
require('./locale')(app)
# numeral setup
require('./numeral')(app)
# enforce mobile setup
enforce_mobile = CONFIG.view.device_capture and CONFIG.view.enforce_mobile
app.use(nodame.enforce_mobile()) if enforce_mobile
# locals helper setup
local_path_helper = (req, res, next) ->
fullpath = req.originalUrl
appName = CONFIG.app.name
res.locals.path =
full : fullpath
module : fullpath.replace("/#{appName}", '')
return next() if next
app.use(nodame.locals(app))
app.use(local_path_helper)
# maintenance setup
server_maintenance = (req, res, next) ->
# Bypass whitelist_ips
return next() if next and nodame.is_whitelist(req.ips)
# Set maintenance
Render = require('./render')
render = new Render(req, res)
Async.waterfall [
(cb) => render.cache("error:maintenance", true, cb)
], (err, is_cache) =>
unless is_cache
render.path('errors/503')
render.code(503)
render.send()
return undefined
return
app.use(server_maintenance) if CONFIG.server.maintenance
# routes setup
new Router(app)
# hooks setup
if CONFIG.server.hooks.length > 0
nodame.require("hook/#{hook}") for hook in CONFIG.server.hooks
# errors setup
require('./error')(app)
module.exports = app
| true | ###
# @author PI:NAME:<NAME>END_PI <https:#github.com/hkyo89>
# @link https:#github.com/tokopedia/nodame
# @license http:#opensource.org/licenses/MIT
#
# @version 1.0.0
###
# third-party modules
CookieParser = require('cookie-parser')
BodyParser = require('body-parser')
XMLBodyParser = require('express-xml-bodyparser')
MethodOverride = require('method-override')
ExpressDevice = require('express-device')
YAMLParser = require('js-yaml')
fs = require('fs')
Async = require('async')
# private modules
Router = require('./router')
View = require('./view')
Locals = require('./locals')
Path = require('./path')
File = require('./file')
Logger = require('./logger')
Parser = require('./parser')
# expressjs initialization
app = nodame.express()
app.env = nodame.env()
# load package information
package_path = Path.safe("#{nodame.sysPath()}/package.json")
Package = File.readJSON(package_path)
nodame.set 'app',
name : Package.name
version : Package.version
homepage: Package.homepage
authors : Package.authors
license : Package.license
# local variables
is_dev = nodame.isDev()
app_path = nodame.appPath()
CONFIG = nodame.config()
# trust proxy setup
app.set('trust proxy', 'uniquelocal')
app.enable('trust proxy')
# load and store assets config
assets_file = if is_dev then 'assets.yaml' else '.assets'
assets_stream = Path.safe("#{app_path}/configs/#{assets_file}")
if is_dev
assets = fs.readFileSync(assets_stream)
assets = YAMLParser.safeLoad(assets)
assets = Parser.to_grunt(assets)
else
assets = File.readJSON(assets_stream)
nodame.set('assets', assets)
# Load build data
build_data_stream = Path.safe("#{app_path}/configs/.build")
build_data = File.readJSON(build_data_stream)
nodame.set('build', build_data)
# x-powered-by header
app.set('x-powered-by', CONFIG.server.powered_by)
# Device capture setup
app.use(ExpressDevice.capture()) if CONFIG.view.device_capture
# log setup
# TODO: disable logger
app.use(Logger.error())
app.use(Logger.output())
# block favicon request
block_favicon = (req, res, next) ->
if req.url is '/favicon.ico'
res.writeHead(200, {'Content-Type': 'image/x-icon'})
res.end()
else
next()
return
app.use(block_favicon) if CONFIG.server.block_favicon
# static server setup
if CONFIG.assets.enable_server
ServeStatic = require('serve-static')
module_root = CONFIG.module.root
unless module_root[0] is '/'
module_root = "/#{module_root}"
static_route = CONFIG.assets.route
if static_route[0] is '/'
static_route = static_route.substr(1)
#TODO FIX THIS FOR WINDOW
static_route = "#{module_root}/#{static_route}"
static_dir = Path.safe("#{app_path}/#{CONFIG.assets.dir}")
app.use(static_route, ServeStatic(static_dir))
# view engine setup
new View(app)
# redirect non-https on production
enforce_secure = (req, res, next) ->
unless is_dev and req.secure
res.redirect("#{CONFIG.url.hostname}#{req.originalUrl}")
next = false
return next() if next
app.use(enforce_secure) if not is_dev and CONFIG.server.enforce_secure
# middlewares Setups
app.use(BodyParser.json())
app.use(BodyParser.urlencoded({ extended: false }))
app.use(XMLBodyParser())
app.use(CookieParser(nodame.config('cookie.secret')))
app.use(MethodOverride())
# Locals setup
locals = new Locals()
locals.set(app)
# i18n setup
require('./locale')(app)
# numeral setup
require('./numeral')(app)
# enforce mobile setup
enforce_mobile = CONFIG.view.device_capture and CONFIG.view.enforce_mobile
app.use(nodame.enforce_mobile()) if enforce_mobile
# locals helper setup
local_path_helper = (req, res, next) ->
fullpath = req.originalUrl
appName = CONFIG.app.name
res.locals.path =
full : fullpath
module : fullpath.replace("/#{appName}", '')
return next() if next
app.use(nodame.locals(app))
app.use(local_path_helper)
# maintenance setup
server_maintenance = (req, res, next) ->
# Bypass whitelist_ips
return next() if next and nodame.is_whitelist(req.ips)
# Set maintenance
Render = require('./render')
render = new Render(req, res)
Async.waterfall [
(cb) => render.cache("error:maintenance", true, cb)
], (err, is_cache) =>
unless is_cache
render.path('errors/503')
render.code(503)
render.send()
return undefined
return
app.use(server_maintenance) if CONFIG.server.maintenance
# routes setup
new Router(app)
# hooks setup
if CONFIG.server.hooks.length > 0
nodame.require("hook/#{hook}") for hook in CONFIG.server.hooks
# errors setup
require('./error')(app)
module.exports = app
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9911876916885376,
"start": 16,
"tag": "NAME",
"value": "Konode"
},
{
"context": "Smooth-scroll utility, customized from https://pawelgrzybek.com/page-scroll-in-vanilla-java... | src/utils.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Set of frequently-used utilities used all around the app
Moment = require 'moment'
{TimestampFormat} = require './persist'
{CustomError} = require './persist/utils'
Config = require './config'
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
maxMetricNameLength = 50
# return a list of unsafe file extensions
blockedExtensions = [
'.action',
'.app',
'.application',
'.bat',
'.bin',
'.cmd',
'.com',
'.command',
'.cpl',
'.csh',
'.esf',
'.exe',
'.gadget',
'.hta',
'.inf',
'.jar',
'.js',
'.jse',
'.lnk',
'.msc',
'.msi',
'.msp',
'.osx',
'.ps1',
'.ps2',
'.psc1',
'.psc2',
'.reg',
'.scf',
'.scr',
'.vb',
'.vbs',
'.vbscript',
'.workflow',
'.ws'
]
# Execute variable as a function if it is one
executeIfFunction = (variable, arg) ->
if typeof variable is 'function'
if arg?
return variable arg
else
return variable()
else
return variable
# Shortcut for using Font Awesome icons in React
FaIcon = (name, props = {}) ->
# if the name is an extension, return an appropriate icon (paperclip if unknown)
if /[.]/.test(name)
switch name.toLowerCase()
when '.avi' then name = 'file-video-o'
when '.bmp' then name = 'image'
when '.doc' then name = 'file-word-o'
when '.docx' then name = 'file-word-o'
when '.jpeg' then name = 'image'
when '.jpg' then name = 'image'
when '.mov' then name = 'file-video-o'
when '.ogg' then name = 'file-video-o'
when '.mp3' then name = 'file-audio-o'
when '.mp4' then name = 'file-video-o'
when '.pdf' then name = 'file-pdf-o'
when '.png' then name = 'image'
when '.rtf' then name = 'file-text-o'
when '.tga' then name = 'image'
when '.tiff' then name = 'image'
when '.txt' then name = 'file-text-o'
when '.wav' then name = 'file-audio-o'
when '.xls' then name = 'file-excel-o'
when '.xlsx' then name = 'file-excel-o'
when '.zip' then name = 'file-archive-o'
else name = 'paperclip'
className = "fa fa-#{name}"
# Extend with className from props if any
if props.className?
className += " #{props.className}"
props.className = className
return R.i(props)
# A convenience method for opening a new window
# Callback function (optional) provides window context as argument
openWindow = (params, options = {}, cb=(->)) ->
width = 1200
height = 700
screenWidth = nw.Screen.screens[0].work_area.width
screenHeight = nw.Screen.screens[0].work_area.height
x = null
y = null
if options instanceof Function then cb = options
if options.offset
x = nw.Window.get(win).x + 25
y = nw.Window.get(win).y + 25
if options.maximize or Config.mobile
width = screenWidth
height = screenHeight
else
if screenWidth < 1200
width = screenWidth
if screenHeight < 700
height = screenHeight
switch params.page
when 'clientSelection'
page = 'src/main-clientSelection.html?'
else
page = 'src/main.html?'
nw.Window.open page + $.param(params), {
focus: false
show: false
x
y
width
height
min_width: 640
min_height: 640
icon: "src/icon.png"
}, cb
renderName = (name) ->
result = [name.get('first')]
if name.get('middle')
result.push name.get('middle')
result.push name.get('last')
return result.join ' '
# Returns the clientFileId with label
# Setting 2nd param as true returns nothing if id is empty/nonexistent
renderRecordId = (id, hidden) ->
result = []
result.push Config.clientFileRecordId.label
if not id or id.length is 0
if hidden then return null
result.push "(n/a)"
else
result.push id
return result.join ' '
# Converts line breaks to React <br> tags and trims leading or trailing whitespace
renderLineBreaks = (text) ->
unless text?
console.warn "renderLineBreaks received no input: ", text
return ""
if typeof text isnt 'string'
console.error "Tried to call renderLineBreaks on a non-string:", text
return text
lines = text.trim()
.replace(/\r\n/g, '\n') # Windows -> Unix
.replace(/\r/g, '\n') # old Mac -> Unix
.split('\n')
result = []
for line, lineIndex in lines
if lineIndex > 0
result.push R.br({key: lineIndex})
if line.trim()
result.push line
return result
# Useful for conditionally hiding React components
showWhen = (condition) ->
if condition
return ''
return 'hide'
showWhen3d = (condition) ->
if condition
return ''
return 'shrink'
# Persistent objects come with metadata that makes it difficult to compare
# revisions (e.g. timestamp). This method removes those attributes.
stripMetadata = (persistObj) ->
return persistObj
.delete('revisionId')
.delete('author')
.delete('authorDisplayName')
.delete('timestamp')
.delete('_dirPath')
formatTimestamp = (timestamp, customFormat = '') ->
return Moment(timestamp, TimestampFormat).format(customFormat or Config.timestampFormat)
capitalize = (word) ->
return word.charAt(0).toUpperCase() + word.slice(1)
# Ensures that `text` does not exceed `maxLength` by replacing excess
# characters with an ellipsis character.
truncateText = (maxLength, text) ->
if text.length <= maxLength
return text
return text[...(maxLength - 1)] + '…'
makeMoment = (timestamp) -> Moment timestamp, TimestampFormat
# Takes a list or collection of persistent objects and puts them into a Map
# so that they can be accessed by their ID.
#
# (Imm.Collection<Imm.Map>) -> Imm.Map
objectsAsIdMap = (objects) ->
return objects
.map((o) -> [o.get('id'), o])
.fromEntrySeq()
.toMap()
renderTimeSpan = (startTimestamp, endTimestamp) ->
startMoment = makeMoment(startTimestamp)
if not endTimestamp
# No endMoment means it's a point-event
return startMoment.format(Config.timestampFormat)
# Must be a span-event
endMoment = makeMoment(endTimestamp)
isFromStartOfDay = startMoment.format('HH:mm') is '00:00'
isToEndOfDay = endMoment.format('HH:mm') is '23:59'
if isFromStartOfDay and isToEndOfDay
# Special case to only use date for a full-day event
isSameDay = startMoment.isSame endMoment, 'day'
if isSameDay
return startMoment.format(Config.dateFormat)
else
return "#{startMoment.format(Config.dateFormat)} to #{endMoment.format(Config.dateFormat)}"
# Otherwise, use default timeSpan format
return "#{startMoment.format(Config.timestampFormat)} to #{endMoment.format(Config.timestampFormat)}"
# Smooth-scroll utility, customized from https://pawelgrzybek.com/page-scroll-in-vanilla-javascript/
# Uses nw win for requestAnimationFrame, and can handle scrolling within a container
# paddingOffset makes it scroll a bit less, for more space on top
scrollToElement = (container, element, duration = 500, easing = 'linear', paddingOffset, cb) ->
# paddingOffset is optional arg
if not cb?
cb = paddingOffset
paddingOffset = 10
# container and element must both be valid
if not container or not element
arg = if element then 'container' else element
throw new Error "Missing arg in scrollToElement for #{arg}"
return
easings =
linear: (t) ->
t
easeInQuad: (t) ->
t * t
easeOutQuad: (t) ->
t * (2 - t)
easeInOutQuad: (t) ->
if t < 0.5 then 2 * t * t else -1 + (4 - (2 * t)) * t
easeInCubic: (t) ->
t * t * t
easeOutCubic: (t) ->
--t * t * t + 1
easeInOutCubic: (t) ->
if t < 0.5 then 4 * t * t * t else (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
easeInQuart: (t) ->
t * t * t * t
easeOutQuart: (t) ->
1 - (--t * t * t * t)
easeInOutQuart: (t) ->
if t < 0.5 then 8 * t * t * t * t else 1 - (8 * --t * t * t * t)
easeInQuint: (t) ->
t * t * t * t * t
easeOutQuint: (t) ->
1 + --t * t * t * t * t
easeInOutQuint: (t) ->
if t < 0.5 then 16 * t * t * t * t * t else 1 + 16 * --t * t * t * t * t
start = container.scrollTop
startTime = Date.now()
# Figure out offset from top, minus any offset for the container itself
topOffset = element.offsetTop
containerOffset = $(container).position().top
destination = topOffset - containerOffset
# requestAnimationFrame can inf-loop if we dont set a limit
maxScrollTop = container.scrollHeight - container.offsetTop
# Can't scroll past maximum, otherwise apply paddingOffset
if destination > maxScrollTop
destination = maxScrollTop
else
destination -= paddingOffset
# Can't scroll above top
if destination < 0
destination = 0
# Cancel scroll if we're already at our destination
if start is destination
console.warn "Cancelled scroll (container.scrollTop is already #{start}px)"
cb()
return
# Extra timeout safeguard against inf-loop after duration completes
cancelOp = null
console.log "scrollTop: #{start} -> #{destination}"
setTimeout (-> cancelOp = true), duration + 10
# Start the scroll loop
scroll = ->
now = Date.now()
time = Math.min(1, (now - startTime) / duration)
timeFunction = easings[easing](time)
container.scrollTop = (timeFunction * (destination - start)) + start
if container.scrollTop is destination or cancelOp
console.log "Finished scrolling!"
cb()
return
win.requestAnimationFrame scroll
return
scroll()
return
##### Convenience methods for fetching data from a progNote
getUnitIndex = (progNote, unitId) ->
result = progNote.get('units')
.findIndex (unit) =>
return unit.get('id') is unitId
if result is -1
throw new Error "could not find unit with ID #{JSON.stringify unitId}"
return result
getPlanSectionIndex = (progNote, unitIndex, sectionId) ->
result = progNote.getIn(['units', unitIndex, 'sections'])
.findIndex (section) =>
return section.get('id') is sectionId
if result is -1
throw new Error "could not find unit with ID #{JSON.stringify sectionId}"
return result
getPlanTargetIndex = (progNote, unitIndex, sectionIndex, targetId) ->
result = progNote.getIn(['units', unitIndex, 'sections', sectionIndex, 'targets'])
.findIndex (target) =>
return target.get('id') is targetId
if result is -1
throw new Error "could not find target with ID #{JSON.stringify targetId}"
return result
return {
maxMetricNameLength
blockedExtensions
CustomError
executeIfFunction
FaIcon
openWindow
renderLineBreaks
renderName
renderRecordId
showWhen
showWhen3d
stripMetadata
formatTimestamp
capitalize
truncateText
makeMoment
objectsAsIdMap
renderTimeSpan
scrollToElement
getUnitIndex
getPlanSectionIndex
getPlanTargetIndex
}
module.exports = {
load
CustomError # for modules that can't provide a window object
}
| 46150 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Set of frequently-used utilities used all around the app
Moment = require 'moment'
{TimestampFormat} = require './persist'
{CustomError} = require './persist/utils'
Config = require './config'
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
maxMetricNameLength = 50
# return a list of unsafe file extensions
blockedExtensions = [
'.action',
'.app',
'.application',
'.bat',
'.bin',
'.cmd',
'.com',
'.command',
'.cpl',
'.csh',
'.esf',
'.exe',
'.gadget',
'.hta',
'.inf',
'.jar',
'.js',
'.jse',
'.lnk',
'.msc',
'.msi',
'.msp',
'.osx',
'.ps1',
'.ps2',
'.psc1',
'.psc2',
'.reg',
'.scf',
'.scr',
'.vb',
'.vbs',
'.vbscript',
'.workflow',
'.ws'
]
# Execute variable as a function if it is one
executeIfFunction = (variable, arg) ->
if typeof variable is 'function'
if arg?
return variable arg
else
return variable()
else
return variable
# Shortcut for using Font Awesome icons in React
FaIcon = (name, props = {}) ->
# if the name is an extension, return an appropriate icon (paperclip if unknown)
if /[.]/.test(name)
switch name.toLowerCase()
when '.avi' then name = 'file-video-o'
when '.bmp' then name = 'image'
when '.doc' then name = 'file-word-o'
when '.docx' then name = 'file-word-o'
when '.jpeg' then name = 'image'
when '.jpg' then name = 'image'
when '.mov' then name = 'file-video-o'
when '.ogg' then name = 'file-video-o'
when '.mp3' then name = 'file-audio-o'
when '.mp4' then name = 'file-video-o'
when '.pdf' then name = 'file-pdf-o'
when '.png' then name = 'image'
when '.rtf' then name = 'file-text-o'
when '.tga' then name = 'image'
when '.tiff' then name = 'image'
when '.txt' then name = 'file-text-o'
when '.wav' then name = 'file-audio-o'
when '.xls' then name = 'file-excel-o'
when '.xlsx' then name = 'file-excel-o'
when '.zip' then name = 'file-archive-o'
else name = 'paperclip'
className = "fa fa-#{name}"
# Extend with className from props if any
if props.className?
className += " #{props.className}"
props.className = className
return R.i(props)
# A convenience method for opening a new window
# Callback function (optional) provides window context as argument
openWindow = (params, options = {}, cb=(->)) ->
width = 1200
height = 700
screenWidth = nw.Screen.screens[0].work_area.width
screenHeight = nw.Screen.screens[0].work_area.height
x = null
y = null
if options instanceof Function then cb = options
if options.offset
x = nw.Window.get(win).x + 25
y = nw.Window.get(win).y + 25
if options.maximize or Config.mobile
width = screenWidth
height = screenHeight
else
if screenWidth < 1200
width = screenWidth
if screenHeight < 700
height = screenHeight
switch params.page
when 'clientSelection'
page = 'src/main-clientSelection.html?'
else
page = 'src/main.html?'
nw.Window.open page + $.param(params), {
focus: false
show: false
x
y
width
height
min_width: 640
min_height: 640
icon: "src/icon.png"
}, cb
renderName = (name) ->
result = [name.get('first')]
if name.get('middle')
result.push name.get('middle')
result.push name.get('last')
return result.join ' '
# Returns the clientFileId with label
# Setting 2nd param as true returns nothing if id is empty/nonexistent
renderRecordId = (id, hidden) ->
result = []
result.push Config.clientFileRecordId.label
if not id or id.length is 0
if hidden then return null
result.push "(n/a)"
else
result.push id
return result.join ' '
# Converts line breaks to React <br> tags and trims leading or trailing whitespace
renderLineBreaks = (text) ->
unless text?
console.warn "renderLineBreaks received no input: ", text
return ""
if typeof text isnt 'string'
console.error "Tried to call renderLineBreaks on a non-string:", text
return text
lines = text.trim()
.replace(/\r\n/g, '\n') # Windows -> Unix
.replace(/\r/g, '\n') # old Mac -> Unix
.split('\n')
result = []
for line, lineIndex in lines
if lineIndex > 0
result.push R.br({key: lineIndex})
if line.trim()
result.push line
return result
# Useful for conditionally hiding React components
showWhen = (condition) ->
if condition
return ''
return 'hide'
showWhen3d = (condition) ->
if condition
return ''
return 'shrink'
# Persistent objects come with metadata that makes it difficult to compare
# revisions (e.g. timestamp). This method removes those attributes.
stripMetadata = (persistObj) ->
return persistObj
.delete('revisionId')
.delete('author')
.delete('authorDisplayName')
.delete('timestamp')
.delete('_dirPath')
formatTimestamp = (timestamp, customFormat = '') ->
return Moment(timestamp, TimestampFormat).format(customFormat or Config.timestampFormat)
capitalize = (word) ->
return word.charAt(0).toUpperCase() + word.slice(1)
# Ensures that `text` does not exceed `maxLength` by replacing excess
# characters with an ellipsis character.
truncateText = (maxLength, text) ->
if text.length <= maxLength
return text
return text[...(maxLength - 1)] + '…'
makeMoment = (timestamp) -> Moment timestamp, TimestampFormat
# Takes a list or collection of persistent objects and puts them into a Map
# so that they can be accessed by their ID.
#
# (Imm.Collection<Imm.Map>) -> Imm.Map
objectsAsIdMap = (objects) ->
return objects
.map((o) -> [o.get('id'), o])
.fromEntrySeq()
.toMap()
renderTimeSpan = (startTimestamp, endTimestamp) ->
startMoment = makeMoment(startTimestamp)
if not endTimestamp
# No endMoment means it's a point-event
return startMoment.format(Config.timestampFormat)
# Must be a span-event
endMoment = makeMoment(endTimestamp)
isFromStartOfDay = startMoment.format('HH:mm') is '00:00'
isToEndOfDay = endMoment.format('HH:mm') is '23:59'
if isFromStartOfDay and isToEndOfDay
# Special case to only use date for a full-day event
isSameDay = startMoment.isSame endMoment, 'day'
if isSameDay
return startMoment.format(Config.dateFormat)
else
return "#{startMoment.format(Config.dateFormat)} to #{endMoment.format(Config.dateFormat)}"
# Otherwise, use default timeSpan format
return "#{startMoment.format(Config.timestampFormat)} to #{endMoment.format(Config.timestampFormat)}"
# Smooth-scroll utility, customized from https://pawelgrzybek.com/page-scroll-in-vanilla-javascript/
# Uses nw win for requestAnimationFrame, and can handle scrolling within a container
# paddingOffset makes it scroll a bit less, for more space on top
scrollToElement = (container, element, duration = 500, easing = 'linear', paddingOffset, cb) ->
# paddingOffset is optional arg
if not cb?
cb = paddingOffset
paddingOffset = 10
# container and element must both be valid
if not container or not element
arg = if element then 'container' else element
throw new Error "Missing arg in scrollToElement for #{arg}"
return
easings =
linear: (t) ->
t
easeInQuad: (t) ->
t * t
easeOutQuad: (t) ->
t * (2 - t)
easeInOutQuad: (t) ->
if t < 0.5 then 2 * t * t else -1 + (4 - (2 * t)) * t
easeInCubic: (t) ->
t * t * t
easeOutCubic: (t) ->
--t * t * t + 1
easeInOutCubic: (t) ->
if t < 0.5 then 4 * t * t * t else (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
easeInQuart: (t) ->
t * t * t * t
easeOutQuart: (t) ->
1 - (--t * t * t * t)
easeInOutQuart: (t) ->
if t < 0.5 then 8 * t * t * t * t else 1 - (8 * --t * t * t * t)
easeInQuint: (t) ->
t * t * t * t * t
easeOutQuint: (t) ->
1 + --t * t * t * t * t
easeInOutQuint: (t) ->
if t < 0.5 then 16 * t * t * t * t * t else 1 + 16 * --t * t * t * t * t
start = container.scrollTop
startTime = Date.now()
# Figure out offset from top, minus any offset for the container itself
topOffset = element.offsetTop
containerOffset = $(container).position().top
destination = topOffset - containerOffset
# requestAnimationFrame can inf-loop if we dont set a limit
maxScrollTop = container.scrollHeight - container.offsetTop
# Can't scroll past maximum, otherwise apply paddingOffset
if destination > maxScrollTop
destination = maxScrollTop
else
destination -= paddingOffset
# Can't scroll above top
if destination < 0
destination = 0
# Cancel scroll if we're already at our destination
if start is destination
console.warn "Cancelled scroll (container.scrollTop is already #{start}px)"
cb()
return
# Extra timeout safeguard against inf-loop after duration completes
cancelOp = null
console.log "scrollTop: #{start} -> #{destination}"
setTimeout (-> cancelOp = true), duration + 10
# Start the scroll loop
scroll = ->
now = Date.now()
time = Math.min(1, (now - startTime) / duration)
timeFunction = easings[easing](time)
container.scrollTop = (timeFunction * (destination - start)) + start
if container.scrollTop is destination or cancelOp
console.log "Finished scrolling!"
cb()
return
win.requestAnimationFrame scroll
return
scroll()
return
##### Convenience methods for fetching data from a progNote
getUnitIndex = (progNote, unitId) ->
result = progNote.get('units')
.findIndex (unit) =>
return unit.get('id') is unitId
if result is -1
throw new Error "could not find unit with ID #{JSON.stringify unitId}"
return result
getPlanSectionIndex = (progNote, unitIndex, sectionId) ->
result = progNote.getIn(['units', unitIndex, 'sections'])
.findIndex (section) =>
return section.get('id') is sectionId
if result is -1
throw new Error "could not find unit with ID #{JSON.stringify sectionId}"
return result
getPlanTargetIndex = (progNote, unitIndex, sectionIndex, targetId) ->
result = progNote.getIn(['units', unitIndex, 'sections', sectionIndex, 'targets'])
.findIndex (target) =>
return target.get('id') is targetId
if result is -1
throw new Error "could not find target with ID #{JSON.stringify targetId}"
return result
return {
maxMetricNameLength
blockedExtensions
CustomError
executeIfFunction
FaIcon
openWindow
renderLineBreaks
renderName
renderRecordId
showWhen
showWhen3d
stripMetadata
formatTimestamp
capitalize
truncateText
makeMoment
objectsAsIdMap
renderTimeSpan
scrollToElement
getUnitIndex
getPlanSectionIndex
getPlanTargetIndex
}
module.exports = {
load
CustomError # for modules that can't provide a window object
}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Set of frequently-used utilities used all around the app
Moment = require 'moment'
{TimestampFormat} = require './persist'
{CustomError} = require './persist/utils'
Config = require './config'
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
maxMetricNameLength = 50
# return a list of unsafe file extensions
blockedExtensions = [
'.action',
'.app',
'.application',
'.bat',
'.bin',
'.cmd',
'.com',
'.command',
'.cpl',
'.csh',
'.esf',
'.exe',
'.gadget',
'.hta',
'.inf',
'.jar',
'.js',
'.jse',
'.lnk',
'.msc',
'.msi',
'.msp',
'.osx',
'.ps1',
'.ps2',
'.psc1',
'.psc2',
'.reg',
'.scf',
'.scr',
'.vb',
'.vbs',
'.vbscript',
'.workflow',
'.ws'
]
# Execute variable as a function if it is one
executeIfFunction = (variable, arg) ->
if typeof variable is 'function'
if arg?
return variable arg
else
return variable()
else
return variable
# Shortcut for using Font Awesome icons in React
FaIcon = (name, props = {}) ->
# if the name is an extension, return an appropriate icon (paperclip if unknown)
if /[.]/.test(name)
switch name.toLowerCase()
when '.avi' then name = 'file-video-o'
when '.bmp' then name = 'image'
when '.doc' then name = 'file-word-o'
when '.docx' then name = 'file-word-o'
when '.jpeg' then name = 'image'
when '.jpg' then name = 'image'
when '.mov' then name = 'file-video-o'
when '.ogg' then name = 'file-video-o'
when '.mp3' then name = 'file-audio-o'
when '.mp4' then name = 'file-video-o'
when '.pdf' then name = 'file-pdf-o'
when '.png' then name = 'image'
when '.rtf' then name = 'file-text-o'
when '.tga' then name = 'image'
when '.tiff' then name = 'image'
when '.txt' then name = 'file-text-o'
when '.wav' then name = 'file-audio-o'
when '.xls' then name = 'file-excel-o'
when '.xlsx' then name = 'file-excel-o'
when '.zip' then name = 'file-archive-o'
else name = 'paperclip'
className = "fa fa-#{name}"
# Extend with className from props if any
if props.className?
className += " #{props.className}"
props.className = className
return R.i(props)
# A convenience method for opening a new window
# Callback function (optional) provides window context as argument
openWindow = (params, options = {}, cb=(->)) ->
width = 1200
height = 700
screenWidth = nw.Screen.screens[0].work_area.width
screenHeight = nw.Screen.screens[0].work_area.height
x = null
y = null
if options instanceof Function then cb = options
if options.offset
x = nw.Window.get(win).x + 25
y = nw.Window.get(win).y + 25
if options.maximize or Config.mobile
width = screenWidth
height = screenHeight
else
if screenWidth < 1200
width = screenWidth
if screenHeight < 700
height = screenHeight
switch params.page
when 'clientSelection'
page = 'src/main-clientSelection.html?'
else
page = 'src/main.html?'
nw.Window.open page + $.param(params), {
focus: false
show: false
x
y
width
height
min_width: 640
min_height: 640
icon: "src/icon.png"
}, cb
renderName = (name) ->
result = [name.get('first')]
if name.get('middle')
result.push name.get('middle')
result.push name.get('last')
return result.join ' '
# Returns the clientFileId with label
# Setting 2nd param as true returns nothing if id is empty/nonexistent
renderRecordId = (id, hidden) ->
result = []
result.push Config.clientFileRecordId.label
if not id or id.length is 0
if hidden then return null
result.push "(n/a)"
else
result.push id
return result.join ' '
# Converts line breaks to React <br> tags and trims leading or trailing whitespace
renderLineBreaks = (text) ->
unless text?
console.warn "renderLineBreaks received no input: ", text
return ""
if typeof text isnt 'string'
console.error "Tried to call renderLineBreaks on a non-string:", text
return text
lines = text.trim()
.replace(/\r\n/g, '\n') # Windows -> Unix
.replace(/\r/g, '\n') # old Mac -> Unix
.split('\n')
result = []
for line, lineIndex in lines
if lineIndex > 0
result.push R.br({key: lineIndex})
if line.trim()
result.push line
return result
# Useful for conditionally hiding React components
showWhen = (condition) ->
if condition
return ''
return 'hide'
showWhen3d = (condition) ->
if condition
return ''
return 'shrink'
# Persistent objects come with metadata that makes it difficult to compare
# revisions (e.g. timestamp). This method removes those attributes.
stripMetadata = (persistObj) ->
return persistObj
.delete('revisionId')
.delete('author')
.delete('authorDisplayName')
.delete('timestamp')
.delete('_dirPath')
formatTimestamp = (timestamp, customFormat = '') ->
return Moment(timestamp, TimestampFormat).format(customFormat or Config.timestampFormat)
capitalize = (word) ->
return word.charAt(0).toUpperCase() + word.slice(1)
# Ensures that `text` does not exceed `maxLength` by replacing excess
# characters with an ellipsis character.
truncateText = (maxLength, text) ->
if text.length <= maxLength
return text
return text[...(maxLength - 1)] + '…'
makeMoment = (timestamp) -> Moment timestamp, TimestampFormat
# Takes a list or collection of persistent objects and puts them into a Map
# so that they can be accessed by their ID.
#
# (Imm.Collection<Imm.Map>) -> Imm.Map
objectsAsIdMap = (objects) ->
return objects
.map((o) -> [o.get('id'), o])
.fromEntrySeq()
.toMap()
renderTimeSpan = (startTimestamp, endTimestamp) ->
startMoment = makeMoment(startTimestamp)
if not endTimestamp
# No endMoment means it's a point-event
return startMoment.format(Config.timestampFormat)
# Must be a span-event
endMoment = makeMoment(endTimestamp)
isFromStartOfDay = startMoment.format('HH:mm') is '00:00'
isToEndOfDay = endMoment.format('HH:mm') is '23:59'
if isFromStartOfDay and isToEndOfDay
# Special case to only use date for a full-day event
isSameDay = startMoment.isSame endMoment, 'day'
if isSameDay
return startMoment.format(Config.dateFormat)
else
return "#{startMoment.format(Config.dateFormat)} to #{endMoment.format(Config.dateFormat)}"
# Otherwise, use default timeSpan format
return "#{startMoment.format(Config.timestampFormat)} to #{endMoment.format(Config.timestampFormat)}"
# Smooth-scroll utility, customized from https://pawelgrzybek.com/page-scroll-in-vanilla-javascript/
# Uses nw win for requestAnimationFrame, and can handle scrolling within a container
# paddingOffset makes it scroll a bit less, for more space on top
scrollToElement = (container, element, duration = 500, easing = 'linear', paddingOffset, cb) ->
# paddingOffset is optional arg
if not cb?
cb = paddingOffset
paddingOffset = 10
# container and element must both be valid
if not container or not element
arg = if element then 'container' else element
throw new Error "Missing arg in scrollToElement for #{arg}"
return
easings =
linear: (t) ->
t
easeInQuad: (t) ->
t * t
easeOutQuad: (t) ->
t * (2 - t)
easeInOutQuad: (t) ->
if t < 0.5 then 2 * t * t else -1 + (4 - (2 * t)) * t
easeInCubic: (t) ->
t * t * t
easeOutCubic: (t) ->
--t * t * t + 1
easeInOutCubic: (t) ->
if t < 0.5 then 4 * t * t * t else (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
easeInQuart: (t) ->
t * t * t * t
easeOutQuart: (t) ->
1 - (--t * t * t * t)
easeInOutQuart: (t) ->
if t < 0.5 then 8 * t * t * t * t else 1 - (8 * --t * t * t * t)
easeInQuint: (t) ->
t * t * t * t * t
easeOutQuint: (t) ->
1 + --t * t * t * t * t
easeInOutQuint: (t) ->
if t < 0.5 then 16 * t * t * t * t * t else 1 + 16 * --t * t * t * t * t
start = container.scrollTop
startTime = Date.now()
# Figure out offset from top, minus any offset for the container itself
topOffset = element.offsetTop
containerOffset = $(container).position().top
destination = topOffset - containerOffset
# requestAnimationFrame can inf-loop if we dont set a limit
maxScrollTop = container.scrollHeight - container.offsetTop
# Can't scroll past maximum, otherwise apply paddingOffset
if destination > maxScrollTop
destination = maxScrollTop
else
destination -= paddingOffset
# Can't scroll above top
if destination < 0
destination = 0
# Cancel scroll if we're already at our destination
if start is destination
console.warn "Cancelled scroll (container.scrollTop is already #{start}px)"
cb()
return
# Extra timeout safeguard against inf-loop after duration completes
cancelOp = null
console.log "scrollTop: #{start} -> #{destination}"
setTimeout (-> cancelOp = true), duration + 10
# Start the scroll loop
scroll = ->
now = Date.now()
time = Math.min(1, (now - startTime) / duration)
timeFunction = easings[easing](time)
container.scrollTop = (timeFunction * (destination - start)) + start
if container.scrollTop is destination or cancelOp
console.log "Finished scrolling!"
cb()
return
win.requestAnimationFrame scroll
return
scroll()
return
##### Convenience methods for fetching data from a progNote
getUnitIndex = (progNote, unitId) ->
result = progNote.get('units')
.findIndex (unit) =>
return unit.get('id') is unitId
if result is -1
throw new Error "could not find unit with ID #{JSON.stringify unitId}"
return result
getPlanSectionIndex = (progNote, unitIndex, sectionId) ->
result = progNote.getIn(['units', unitIndex, 'sections'])
.findIndex (section) =>
return section.get('id') is sectionId
if result is -1
throw new Error "could not find unit with ID #{JSON.stringify sectionId}"
return result
getPlanTargetIndex = (progNote, unitIndex, sectionIndex, targetId) ->
result = progNote.getIn(['units', unitIndex, 'sections', sectionIndex, 'targets'])
.findIndex (target) =>
return target.get('id') is targetId
if result is -1
throw new Error "could not find target with ID #{JSON.stringify targetId}"
return result
return {
maxMetricNameLength
blockedExtensions
CustomError
executeIfFunction
FaIcon
openWindow
renderLineBreaks
renderName
renderRecordId
showWhen
showWhen3d
stripMetadata
formatTimestamp
capitalize
truncateText
makeMoment
objectsAsIdMap
renderTimeSpan
scrollToElement
getUnitIndex
getPlanSectionIndex
getPlanTargetIndex
}
module.exports = {
load
CustomError # for modules that can't provide a window object
}
|
[
{
"context": "ire '../lib/model'\n\nparameters =\n\tusernameField: 'username'\n\tpasswordField: 'password'\n\npassport.serializeUs",
"end": 410,
"score": 0.9989186525344849,
"start": 402,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ers =\n\tusernameField: 'username'\n\tpa... | init/auth.coffee | winnlab/Polpharma | 0 | async = require 'async'
Logger = require '../lib/logger'
socialConfig = require '../meta/socialConfig'
passport = require 'passport'
localStrategy = require('passport-local').Strategy
facebookStrategy = require('passport-facebook').Strategy
odnoklassnikiStrategy = require('passport-odnoklassniki').Strategy
mongoose = require 'mongoose'
Model = require '../lib/model'
parameters =
usernameField: 'username'
passwordField: 'password'
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
async.waterfall [
(next)->
Model 'User', 'findOne', next, {_id : id}
(user, next) ->
if user
done null, user
else
Model 'Visitor', 'findOne', done, {_id : id}
], done
validation = (err, user, password, done) ->
if err
return done err
if not user
return done null, false, { message: 'Пользователь с таким именем не существует!' }
if not user.validPassword password
return done null, false, { message: 'Пароль введен неправильно.' }
done null, user
adminStrategy = (username, password, done) ->
cb = (err, user) ->
validation err, user, password, done
Model 'User', 'findOne', cb, {username : username}
userStrategy = (username, password, done) ->
cb = (err, user) ->
validation err, user, password, done
Model 'Client', 'findOne', cb, {username : username}
exports.init = (callback) ->
adminAuth = new localStrategy adminStrategy
clientAuth = new localStrategy userStrategy
facebookAuth = new facebookStrategy
clientID : socialConfig.facebook.clientID
clientSecret : socialConfig.facebook.clientSecret
callbackURL : socialConfig.facebook.callbackURL
profileFields : ['id', 'name', 'picture', 'emails', 'displayName', 'gender']
, (accessToken, refreshToken, profile, done) ->
process.nextTick ->
async.waterfall [
(next) ->
Model 'User', 'findOne', next, {'facebook.id': profile.id}
(user, next) ->
if user
done null, user
else
Model 'User', 'create', done,
facebook:
id: profile.id
token: accessToken
image: "https://graph.facebook.com/" + profile.id + "/picture" + "?width=200&height=200" + "&access_token=" + accessToken
username: profile.name.givenName
email: profile.emails[0].value
role: 'user'
], done
odnoklassnikiAuth = new odnoklassnikiStrategy
clientID: socialConfig.odnoklassniki.clientID
clientPublic: socialConfig.odnoklassniki.clientPublic
clientSecret: socialConfig.odnoklassniki.clientSecret
callbackURL: socialConfig.odnoklassniki.clientID
, (accessToken, refreshToken, profile, done) ->
process.nextTick ->
async.waterfall [
(next) ->
Model 'Visitor', 'findOne', next, {'odnoklassniki.id': profile.id}
(visitor, next) ->
if visitor
done null, visitor
else
Model 'Visitor', 'create', done,
odnoklassniki:
id: profile.id
name: profile.name
birthday: profile._json.birthday
], done
passport.use 'facebook', facebookAuth
passport.use 'odnoklassniki', odnoklassnikiAuth
passport.use 'admin', adminAuth
passport.use 'user', clientAuth
callback() | 69099 | async = require 'async'
Logger = require '../lib/logger'
socialConfig = require '../meta/socialConfig'
passport = require 'passport'
localStrategy = require('passport-local').Strategy
facebookStrategy = require('passport-facebook').Strategy
odnoklassnikiStrategy = require('passport-odnoklassniki').Strategy
mongoose = require 'mongoose'
Model = require '../lib/model'
parameters =
usernameField: 'username'
passwordField: '<PASSWORD>'
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
async.waterfall [
(next)->
Model 'User', 'findOne', next, {_id : id}
(user, next) ->
if user
done null, user
else
Model 'Visitor', 'findOne', done, {_id : id}
], done
validation = (err, user, password, done) ->
if err
return done err
if not user
return done null, false, { message: 'Пользователь с таким именем не существует!' }
if not user.validPassword password
return done null, false, { message: 'Пароль введен неправильно.' }
done null, user
adminStrategy = (username, password, done) ->
cb = (err, user) ->
validation err, user, password, done
Model 'User', 'findOne', cb, {username : username}
userStrategy = (username, password, done) ->
cb = (err, user) ->
validation err, user, password, done
Model 'Client', 'findOne', cb, {username : username}
exports.init = (callback) ->
adminAuth = new localStrategy adminStrategy
clientAuth = new localStrategy userStrategy
facebookAuth = new facebookStrategy
clientID : socialConfig.facebook.clientID
clientSecret : socialConfig.facebook.clientSecret
callbackURL : socialConfig.facebook.callbackURL
profileFields : ['id', 'name', 'picture', 'emails', 'displayName', 'gender']
, (accessToken, refreshToken, profile, done) ->
process.nextTick ->
async.waterfall [
(next) ->
Model 'User', 'findOne', next, {'facebook.id': profile.id}
(user, next) ->
if user
done null, user
else
Model 'User', 'create', done,
facebook:
id: profile.id
token: accessToken
image: "https://graph.facebook.com/" + profile.id + "/picture" + "?width=200&height=200" + "&access_token=" + accessToken
username: profile.name.givenName
email: profile.emails[0].value
role: 'user'
], done
odnoklassnikiAuth = new odnoklassnikiStrategy
clientID: socialConfig.odnoklassniki.clientID
clientPublic: socialConfig.odnoklassniki.clientPublic
clientSecret: socialConfig.odnoklassniki.clientSecret
callbackURL: socialConfig.odnoklassniki.clientID
, (accessToken, refreshToken, profile, done) ->
process.nextTick ->
async.waterfall [
(next) ->
Model 'Visitor', 'findOne', next, {'odnoklassniki.id': profile.id}
(visitor, next) ->
if visitor
done null, visitor
else
Model 'Visitor', 'create', done,
odnoklassniki:
id: profile.id
name: profile.name
birthday: profile._json.birthday
], done
passport.use 'facebook', facebookAuth
passport.use 'odnoklassniki', odnoklassnikiAuth
passport.use 'admin', adminAuth
passport.use 'user', clientAuth
callback() | true | async = require 'async'
Logger = require '../lib/logger'
socialConfig = require '../meta/socialConfig'
passport = require 'passport'
localStrategy = require('passport-local').Strategy
facebookStrategy = require('passport-facebook').Strategy
odnoklassnikiStrategy = require('passport-odnoklassniki').Strategy
mongoose = require 'mongoose'
Model = require '../lib/model'
parameters =
usernameField: 'username'
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
async.waterfall [
(next)->
Model 'User', 'findOne', next, {_id : id}
(user, next) ->
if user
done null, user
else
Model 'Visitor', 'findOne', done, {_id : id}
], done
validation = (err, user, password, done) ->
if err
return done err
if not user
return done null, false, { message: 'Пользователь с таким именем не существует!' }
if not user.validPassword password
return done null, false, { message: 'Пароль введен неправильно.' }
done null, user
adminStrategy = (username, password, done) ->
cb = (err, user) ->
validation err, user, password, done
Model 'User', 'findOne', cb, {username : username}
userStrategy = (username, password, done) ->
cb = (err, user) ->
validation err, user, password, done
Model 'Client', 'findOne', cb, {username : username}
exports.init = (callback) ->
adminAuth = new localStrategy adminStrategy
clientAuth = new localStrategy userStrategy
facebookAuth = new facebookStrategy
clientID : socialConfig.facebook.clientID
clientSecret : socialConfig.facebook.clientSecret
callbackURL : socialConfig.facebook.callbackURL
profileFields : ['id', 'name', 'picture', 'emails', 'displayName', 'gender']
, (accessToken, refreshToken, profile, done) ->
process.nextTick ->
async.waterfall [
(next) ->
Model 'User', 'findOne', next, {'facebook.id': profile.id}
(user, next) ->
if user
done null, user
else
Model 'User', 'create', done,
facebook:
id: profile.id
token: accessToken
image: "https://graph.facebook.com/" + profile.id + "/picture" + "?width=200&height=200" + "&access_token=" + accessToken
username: profile.name.givenName
email: profile.emails[0].value
role: 'user'
], done
odnoklassnikiAuth = new odnoklassnikiStrategy
clientID: socialConfig.odnoklassniki.clientID
clientPublic: socialConfig.odnoklassniki.clientPublic
clientSecret: socialConfig.odnoklassniki.clientSecret
callbackURL: socialConfig.odnoklassniki.clientID
, (accessToken, refreshToken, profile, done) ->
process.nextTick ->
async.waterfall [
(next) ->
Model 'Visitor', 'findOne', next, {'odnoklassniki.id': profile.id}
(visitor, next) ->
if visitor
done null, visitor
else
Model 'Visitor', 'create', done,
odnoklassniki:
id: profile.id
name: profile.name
birthday: profile._json.birthday
], done
passport.use 'facebook', facebookAuth
passport.use 'odnoklassniki', odnoklassnikiAuth
passport.use 'admin', adminAuth
passport.use 'user', clientAuth
callback() |
[
{
"context": " # feature.properties.name =\"慶良間諸島\"\n\n #地種属性を付与\n ",
"end": 3636,
"score": 0.505670428276062,
"start": 3635,
"tag": "NAME",
"value": "慶"
}
] | np/gulpfile.coffee | KamataRyo/my_frontend_apps | 0 | gulp = require 'gulp'
connect = require 'gulp-connect'
path = require 'path'
compass = require 'gulp-compass'
coffee = require 'gulp-coffee'
plumber = require 'gulp-plumber'
notify = require 'gulp-notify'
base = './'
srcs =
watching : [
base + '*.html'
base + 'sass/*.scss'
base + 'coffee/*.coffee'
]
uploading : [
base + '*.html'
base + 'css/*.css'
base + 'js/*.js'
]
host = 'localhost'
port = 8001
# create server
gulp.task "connect", () ->
options =
root: path.resolve base
livereload: true
port: port
host: host
connect.server options
gulp.task "watch", () ->
gulp.watch srcs["watching"], ["compass", "coffee", "reload"]
gulp.task "compass", () ->
options =
config_file: base + 'config.rb'
css: base + 'css/'
sass: base + 'sass/'
image: base + 'img/'
gulp.src base + 'sass/*.scss'
.pipe plumber(errorHandler: notify.onError '<%= error.message %>')
.pipe compass options
.pipe gulp.dest base + 'css/'
gulp.task "coffee", () ->
gulp.src base + 'coffee/*.coffee'
.pipe plumber(errorHandler: notify.onError '<%= error.message %>')
.pipe coffee(bare: true).on 'error', (err) ->
console.log err.stack
.pipe gulp.dest base + 'js/'
gulp.task "reload", ["compass", "coffee"] , () ->
gulp.src srcs["watching"]
.pipe connect.reload()
gulp.task "default", ["compass","coffee","connect", "watch" ]
# ==========upper for developing==========
# ==========lower for data Initialization==========
request = require 'request'
xml2js = require('xml2js').parseString
fs = require 'fs'
_ = require 'underscore'
intercept = require 'gulp-intercept'
#replace = require 'gulp-replace'
#xeditor = require 'gulp-xml-editor'
#xmlEdit = require 'gulp-edit-xml'
xml2json = require 'gulp-xml2json'
jeditor = require 'gulp-json-editor'
download = require 'gulp-download'
unzip = require 'gulp-unzip'
convert = require 'gulp-convert'
geojson = require 'gulp-geojson'
beautify = require 'gulp-jsbeautifier'
rename = require 'gulp-rename'
#runSequence = require 'run-sequence'
#through2 = require 'through2'
concat = require 'gulp-concat-json'
# list of National Park
settingsUrl = './settings.json'
settings = require settingsUrl
#settings.jsonにエントリーポイントを記載した全ての国立公園kmlのURLから、
#gejsonを生成し、地種区分属性を付与する
gulp.task 'download', () ->
for filename, npname of settings.entries
url = settings.base + filename
#url = 'http://www.biodic.go.jp/trialSystem/LinkEnt/nps/NPS_ozeLinkEnt.kml'
download url
.pipe rename extname:'.xml'
.pipe xml2json()
.pipe jeditor (json) ->
kmzUrl = json.kml.Document[0].Folder[0].NetworkLink[0].Link[0].href[0]
basename = path.basename kmzUrl, '.kmz'
download kmzUrl
.pipe unzip()
.pipe rename extname:'.xml'
.pipe xml2json()
# gulp-geojsonがdescription属性下のCDATAを吐き出してくれないので、
# 一旦gulp-xml2jsonで変換して実態参照を含んだjsonに変換
# このJSONから自分でパースしてもよいが
.pipe convert {from:'json', to:'xml'}
.pipe rename extname:'.kml'
.pipe geojson()
.pipe rename extname:'.json'
.pipe jeditor (json) ->
for feature, i in json.features
#なぜか慶良間諸島はname属性が欠けているので、暫定的な処置
#if path.basename kmzUrl is "NPS_keramashotou"
# feature.properties.name ="慶良間諸島"
#地種属性を付与
description = feature.properties.description
for style in settings.styles
if description.match ///#{style.name}///
feature.properties.grade = style.name
break;
else
feature.properties.grade = '地種不明'
json.features[i] = feature
return json
.pipe beautify()
.pipe rename {basename:basename, extname:'.geojson'}
.pipe gulp.dest base + 'geojson'
#慶良間のgeojsonに国立公園名が入ってないので処理
gulp.task 'kerama', () ->
gulp.src 'geojson/NPS_keramashotou.geojson'
.pipe jeditor (json) ->
for feature in json.features
feature.properties.name = '慶良間諸島'
return json
.pipe gulp.dest 'geojson/'
#geojsonフォルダに入っている全ての国立公園geojsonファイルから、
#その分布範囲などを記載したabstractを生成する
gulp.task 'abstract', () ->
filename = ''
gulp.src base + 'geojson/*.geojson'
.pipe rename (filepath) ->
filename = filepath.basename + filepath.extname
.pipe jeditor (json) ->
# abstractの作成用一時変数
latitudes = []
longitudes = []
name = json.features[0].properties.name
for feature in json.features
if feature.geometry.coordinates?
for coordinate in feature.geometry.coordinates[0]
latitudes.push coordinate[0]
longitudes.push coordinate[1]
information = {}
information[filename] =
name: name
top: _.max longitudes
right: _.max latitudes
bottom: _.min longitudes
left: _.min latitudes
return information
.pipe concat 'abstract.json'
.pipe jeditor (json) ->
result = {}
for obj in json
key = _.keys(obj)[0]
result[key] = obj[key]
return result
.pipe beautify()
.pipe gulp.dest base + 'geojson'
| 129109 | gulp = require 'gulp'
connect = require 'gulp-connect'
path = require 'path'
compass = require 'gulp-compass'
coffee = require 'gulp-coffee'
plumber = require 'gulp-plumber'
notify = require 'gulp-notify'
base = './'
srcs =
watching : [
base + '*.html'
base + 'sass/*.scss'
base + 'coffee/*.coffee'
]
uploading : [
base + '*.html'
base + 'css/*.css'
base + 'js/*.js'
]
host = 'localhost'
port = 8001
# create server
gulp.task "connect", () ->
options =
root: path.resolve base
livereload: true
port: port
host: host
connect.server options
gulp.task "watch", () ->
gulp.watch srcs["watching"], ["compass", "coffee", "reload"]
gulp.task "compass", () ->
options =
config_file: base + 'config.rb'
css: base + 'css/'
sass: base + 'sass/'
image: base + 'img/'
gulp.src base + 'sass/*.scss'
.pipe plumber(errorHandler: notify.onError '<%= error.message %>')
.pipe compass options
.pipe gulp.dest base + 'css/'
gulp.task "coffee", () ->
gulp.src base + 'coffee/*.coffee'
.pipe plumber(errorHandler: notify.onError '<%= error.message %>')
.pipe coffee(bare: true).on 'error', (err) ->
console.log err.stack
.pipe gulp.dest base + 'js/'
gulp.task "reload", ["compass", "coffee"] , () ->
gulp.src srcs["watching"]
.pipe connect.reload()
gulp.task "default", ["compass","coffee","connect", "watch" ]
# ==========upper for developing==========
# ==========lower for data Initialization==========
request = require 'request'
xml2js = require('xml2js').parseString
fs = require 'fs'
_ = require 'underscore'
intercept = require 'gulp-intercept'
#replace = require 'gulp-replace'
#xeditor = require 'gulp-xml-editor'
#xmlEdit = require 'gulp-edit-xml'
xml2json = require 'gulp-xml2json'
jeditor = require 'gulp-json-editor'
download = require 'gulp-download'
unzip = require 'gulp-unzip'
convert = require 'gulp-convert'
geojson = require 'gulp-geojson'
beautify = require 'gulp-jsbeautifier'
rename = require 'gulp-rename'
#runSequence = require 'run-sequence'
#through2 = require 'through2'
concat = require 'gulp-concat-json'
# list of National Park
settingsUrl = './settings.json'
settings = require settingsUrl
#settings.jsonにエントリーポイントを記載した全ての国立公園kmlのURLから、
#gejsonを生成し、地種区分属性を付与する
gulp.task 'download', () ->
for filename, npname of settings.entries
url = settings.base + filename
#url = 'http://www.biodic.go.jp/trialSystem/LinkEnt/nps/NPS_ozeLinkEnt.kml'
download url
.pipe rename extname:'.xml'
.pipe xml2json()
.pipe jeditor (json) ->
kmzUrl = json.kml.Document[0].Folder[0].NetworkLink[0].Link[0].href[0]
basename = path.basename kmzUrl, '.kmz'
download kmzUrl
.pipe unzip()
.pipe rename extname:'.xml'
.pipe xml2json()
# gulp-geojsonがdescription属性下のCDATAを吐き出してくれないので、
# 一旦gulp-xml2jsonで変換して実態参照を含んだjsonに変換
# このJSONから自分でパースしてもよいが
.pipe convert {from:'json', to:'xml'}
.pipe rename extname:'.kml'
.pipe geojson()
.pipe rename extname:'.json'
.pipe jeditor (json) ->
for feature, i in json.features
#なぜか慶良間諸島はname属性が欠けているので、暫定的な処置
#if path.basename kmzUrl is "NPS_keramashotou"
# feature.properties.name ="<NAME>良間諸島"
#地種属性を付与
description = feature.properties.description
for style in settings.styles
if description.match ///#{style.name}///
feature.properties.grade = style.name
break;
else
feature.properties.grade = '地種不明'
json.features[i] = feature
return json
.pipe beautify()
.pipe rename {basename:basename, extname:'.geojson'}
.pipe gulp.dest base + 'geojson'
#慶良間のgeojsonに国立公園名が入ってないので処理
gulp.task 'kerama', () ->
gulp.src 'geojson/NPS_keramashotou.geojson'
.pipe jeditor (json) ->
for feature in json.features
feature.properties.name = '慶良間諸島'
return json
.pipe gulp.dest 'geojson/'
#geojsonフォルダに入っている全ての国立公園geojsonファイルから、
#その分布範囲などを記載したabstractを生成する
gulp.task 'abstract', () ->
filename = ''
gulp.src base + 'geojson/*.geojson'
.pipe rename (filepath) ->
filename = filepath.basename + filepath.extname
.pipe jeditor (json) ->
# abstractの作成用一時変数
latitudes = []
longitudes = []
name = json.features[0].properties.name
for feature in json.features
if feature.geometry.coordinates?
for coordinate in feature.geometry.coordinates[0]
latitudes.push coordinate[0]
longitudes.push coordinate[1]
information = {}
information[filename] =
name: name
top: _.max longitudes
right: _.max latitudes
bottom: _.min longitudes
left: _.min latitudes
return information
.pipe concat 'abstract.json'
.pipe jeditor (json) ->
result = {}
for obj in json
key = _.keys(obj)[0]
result[key] = obj[key]
return result
.pipe beautify()
.pipe gulp.dest base + 'geojson'
| true | gulp = require 'gulp'
connect = require 'gulp-connect'
path = require 'path'
compass = require 'gulp-compass'
coffee = require 'gulp-coffee'
plumber = require 'gulp-plumber'
notify = require 'gulp-notify'
base = './'
srcs =
watching : [
base + '*.html'
base + 'sass/*.scss'
base + 'coffee/*.coffee'
]
uploading : [
base + '*.html'
base + 'css/*.css'
base + 'js/*.js'
]
host = 'localhost'
port = 8001
# create server
gulp.task "connect", () ->
options =
root: path.resolve base
livereload: true
port: port
host: host
connect.server options
gulp.task "watch", () ->
gulp.watch srcs["watching"], ["compass", "coffee", "reload"]
gulp.task "compass", () ->
options =
config_file: base + 'config.rb'
css: base + 'css/'
sass: base + 'sass/'
image: base + 'img/'
gulp.src base + 'sass/*.scss'
.pipe plumber(errorHandler: notify.onError '<%= error.message %>')
.pipe compass options
.pipe gulp.dest base + 'css/'
gulp.task "coffee", () ->
gulp.src base + 'coffee/*.coffee'
.pipe plumber(errorHandler: notify.onError '<%= error.message %>')
.pipe coffee(bare: true).on 'error', (err) ->
console.log err.stack
.pipe gulp.dest base + 'js/'
gulp.task "reload", ["compass", "coffee"] , () ->
gulp.src srcs["watching"]
.pipe connect.reload()
gulp.task "default", ["compass","coffee","connect", "watch" ]
# ==========upper for developing==========
# ==========lower for data Initialization==========
request = require 'request'
xml2js = require('xml2js').parseString
fs = require 'fs'
_ = require 'underscore'
intercept = require 'gulp-intercept'
#replace = require 'gulp-replace'
#xeditor = require 'gulp-xml-editor'
#xmlEdit = require 'gulp-edit-xml'
xml2json = require 'gulp-xml2json'
jeditor = require 'gulp-json-editor'
download = require 'gulp-download'
unzip = require 'gulp-unzip'
convert = require 'gulp-convert'
geojson = require 'gulp-geojson'
beautify = require 'gulp-jsbeautifier'
rename = require 'gulp-rename'
#runSequence = require 'run-sequence'
#through2 = require 'through2'
concat = require 'gulp-concat-json'
# list of National Park
settingsUrl = './settings.json'
settings = require settingsUrl
#settings.jsonにエントリーポイントを記載した全ての国立公園kmlのURLから、
#gejsonを生成し、地種区分属性を付与する
gulp.task 'download', () ->
for filename, npname of settings.entries
url = settings.base + filename
#url = 'http://www.biodic.go.jp/trialSystem/LinkEnt/nps/NPS_ozeLinkEnt.kml'
download url
.pipe rename extname:'.xml'
.pipe xml2json()
.pipe jeditor (json) ->
kmzUrl = json.kml.Document[0].Folder[0].NetworkLink[0].Link[0].href[0]
basename = path.basename kmzUrl, '.kmz'
download kmzUrl
.pipe unzip()
.pipe rename extname:'.xml'
.pipe xml2json()
# gulp-geojsonがdescription属性下のCDATAを吐き出してくれないので、
# 一旦gulp-xml2jsonで変換して実態参照を含んだjsonに変換
# このJSONから自分でパースしてもよいが
.pipe convert {from:'json', to:'xml'}
.pipe rename extname:'.kml'
.pipe geojson()
.pipe rename extname:'.json'
.pipe jeditor (json) ->
for feature, i in json.features
#なぜか慶良間諸島はname属性が欠けているので、暫定的な処置
#if path.basename kmzUrl is "NPS_keramashotou"
# feature.properties.name ="PI:NAME:<NAME>END_PI良間諸島"
#地種属性を付与
description = feature.properties.description
for style in settings.styles
if description.match ///#{style.name}///
feature.properties.grade = style.name
break;
else
feature.properties.grade = '地種不明'
json.features[i] = feature
return json
.pipe beautify()
.pipe rename {basename:basename, extname:'.geojson'}
.pipe gulp.dest base + 'geojson'
#慶良間のgeojsonに国立公園名が入ってないので処理
gulp.task 'kerama', () ->
gulp.src 'geojson/NPS_keramashotou.geojson'
.pipe jeditor (json) ->
for feature in json.features
feature.properties.name = '慶良間諸島'
return json
.pipe gulp.dest 'geojson/'
#geojsonフォルダに入っている全ての国立公園geojsonファイルから、
#その分布範囲などを記載したabstractを生成する
gulp.task 'abstract', () ->
filename = ''
gulp.src base + 'geojson/*.geojson'
.pipe rename (filepath) ->
filename = filepath.basename + filepath.extname
.pipe jeditor (json) ->
# abstractの作成用一時変数
latitudes = []
longitudes = []
name = json.features[0].properties.name
for feature in json.features
if feature.geometry.coordinates?
for coordinate in feature.geometry.coordinates[0]
latitudes.push coordinate[0]
longitudes.push coordinate[1]
information = {}
information[filename] =
name: name
top: _.max longitudes
right: _.max latitudes
bottom: _.min longitudes
left: _.min latitudes
return information
.pipe concat 'abstract.json'
.pipe jeditor (json) ->
result = {}
for obj in json
key = _.keys(obj)[0]
result[key] = obj[key]
return result
.pipe beautify()
.pipe gulp.dest base + 'geojson'
|
[
{
"context": "scription', 'keywords', 'datasheet']\n keys = ['D', 'K', 'F']\n empty = true\n for field in fields\n ",
"end": 2132,
"score": 0.997906506061554,
"start": 2121,
"tag": "KEY",
"value": "D', 'K', 'F"
}
] | src/kicad-generator.coffee | cuvoodoo/qeda | 78 | fs = require 'fs'
mkdirp = require 'mkdirp'
sprintf = require('sprintf-js').sprintf
log = require './qeda-log'
#
# Generator of library in KiCad format
#
class KicadGenerator
#
# Constructor
#
constructor: (@library) ->
@f = "%.#{@library.pattern.decimals}f"
#
# Generate symbol library and footprint files
#
generate: (@name) ->
dir = './kicad'
mkdirp.sync "#{dir}/#{@name}.pretty"
mkdirp.sync "#{dir}/#{@name}.3dshapes"
now = new Date
timestamp = sprintf "%02d/%02d/%d %02d:%02d:%02d",
now.getDate(), now.getMonth() + 1, now.getYear() + 1900,
now.getHours(), now.getMinutes(), now.getSeconds()
log.start "KiCad library '#{@name}.lib'"
fd = fs.openSync "#{dir}/#{@name}.lib", 'w'
fs.writeSync fd, "EESchema-LIBRARY Version 2.3 Date: #{timestamp}\n"
fs.writeSync fd, '#encoding utf-8\n'
patterns = {}
# Symbols
for element in @library.elements
@_generateSymbol fd, element
if element.pattern? then patterns[element.pattern.name] = element.pattern
fs.writeSync fd, '# End Library\n'
fs.closeSync fd
log.ok()
# Doc
log.start "KiCad library doc '#{@name}.dcm'"
fd = fs.openSync "#{dir}/#{@name}.dcm", 'w'
fs.writeSync fd, "EESchema-DOCLIB Version 2.0 Date: #{timestamp}\n#\n"
for element in @library.elements
@_generateDoc fd, element
fs.writeSync fd, '# End Doc Library\n'
fs.closeSync fd
log.ok()
# Footprints
for patternName, pattern of patterns
log.start "KiCad footprint '#{patternName}.kicad_mod'"
fd = fs.openSync "#{dir}/#{@name}.pretty/#{patternName}.kicad_mod", 'w'
@_generatePattern fd, pattern
fs.closeSync fd
log.ok()
# 3D shapes
for patternName, pattern of patterns
log.start "KiCad 3D shape '#{patternName}.wrl'"
fd = fs.openSync "#{dir}/#{@name}.3dshapes/#{patternName}.wrl", 'w'
@_generateVrml fd, pattern
fs.closeSync fd
log.ok()
#
# Write doc entry to library doc file
#
_generateDoc: (fd, element) ->
fields = ['description', 'keywords', 'datasheet']
keys = ['D', 'K', 'F']
empty = true
for field in fields
if element[field]?
empty = false
break
if empty then return
fs.writeSync fd, "$CMP #{element.name}\n"
for i in [0..(fields.length - 1)]
if element[fields[i]]? then fs.writeSync fd, "#{keys[i]} #{element[fields[i]]}\n"
fs.writeSync fd, '$ENDCMP\n#\n'
#
# Write pattern file
#
_generatePattern: (fd, pattern) ->
fs.writeSync fd, "(module #{pattern.name} (layer F.Cu)\n"
if pattern.type is 'smd' then fs.writeSync fd, " (attr smd)\n"
for shape in pattern.shapes
patObj = @_patternObj shape
switch patObj.kind
when 'attribute'
fs.writeSync(fd,
sprintf(" (fp_text %s %s (at #{@f} #{@f}%s)%s (layer %s)\n",
patObj.name, patObj.text, patObj.x, patObj.y,
if patObj.angle? then (' ' + patObj.angle.toString()) else '',
unless patObj.visible then ' hide' else '',
patObj.layer)
)
fs.writeSync(fd,
sprintf(" (effects (font (size #{@f} #{@f}) (thickness #{@f})))\n",
patObj.fontSize, patObj.fontSize, patObj.lineWidth)
)
fs.writeSync fd, " )\n"
when 'circle'
fs.writeSync(fd,
sprintf(" (fp_circle (center #{@f} #{@f}) (end #{@f} #{@f}) (layer %s) (width #{@f}))\n",
patObj.x, patObj.y, patObj.x, patObj.y + patObj.radius, patObj.layer, patObj.lineWidth)
)
when 'line'
fs.writeSync(fd,
sprintf(" (fp_line (start #{@f} #{@f}) (end #{@f} #{@f}) (layer %s) (width #{@f}))\n"
patObj.x1, patObj.y1, patObj.x2, patObj.y2, patObj.layer, patObj.lineWidth)
)
when 'pad'
if patObj.shape is 'rect' and @library.pattern.smoothPadCorners
cornerRadius = Math.min(patObj.width, patObj.height) * @library.pattern.ratio.cornerToWidth
if cornerRadius > @library.pattern.maximum.cornerRadius then cornerRadius = @library.pattern.maximum.cornerRadius
if cornerRadius > 0 then patObj.shape = 'roundrect'
fs.writeSync(fd,
sprintf(" (pad %s %s %s (at #{@f} #{@f}) (size #{@f} #{@f}) (layers %s)"
patObj.name, patObj.type, patObj.shape, patObj.x, patObj.y, patObj.width, patObj.height, patObj.layer)
)
if patObj.slotWidth? and patObj.slotHeight?
fs.writeSync fd, sprintf("\n (drill oval #{@f} #{@f})", patObj.slotWidth, patObj.slotHeight)
else if patObj.hole?
fs.writeSync fd, sprintf("\n (drill #{@f})", patObj.hole)
if patObj.mask? then fs.writeSync fd, sprintf("\n (solder_mask_margin #{@f})", patObj.mask)
if patObj.paste? then fs.writeSync fd, sprintf("\n (solder_paste_margin #{@f})", patObj.paste)
if patObj.shape is 'roundrect'
ratio = cornerRadius / Math.min(patObj.width, patObj.height)
fs.writeSync fd, sprintf("\n (roundrect_rratio #{@f})", ratio)
fs.writeSync fd, ")\n"
fs.writeSync fd, " (model #{pattern.name}.wrl\n"
fs.writeSync fd, " (at (xyz 0 0 0))\n"
fs.writeSync fd, " (scale (xyz 0.3937 0.3937 0.3937))\n"
fs.writeSync fd, " (rotate (xyz 0 0 0 ))\n"
fs.writeSync fd, " )\n" # model
fs.writeSync fd, ")\n" # module
#
# Write symbol entry to library file
#
_generateSymbol: (fd, element) ->
for symbol in element.symbols
symbol.resize 50, true # Resize to grid 50 mil with rounding
symbol.invertVertical() # Positive vertical axis is pointing up in KiCad
symbol = element.symbols[0]
refObj = @_symbolObj symbol.attributes['refDes']
nameObj = @_symbolObj symbol.attributes['name']
fs.writeSync fd, "#\n# #{element.name}\n#\n"
showPinNumbers = if element.schematic?.showPinNumbers then 'Y' else 'N'
showPinNames = if element.schematic?.showPinNames then 'Y' else 'N'
pinNameSpace = 0
for shape in symbol.shapes
if shape.kind is 'pin'
pinNameSpace = Math.round shape.space
break
patternName = ''
if element.pattern? then patternName = "#{@name}:#{element.pattern.name}"
powerSymbol = 'N'
if element.power then powerSymbol = 'P'
fs.writeSync fd, "DEF #{element.name} #{element.refDes} 0 #{pinNameSpace} #{showPinNumbers} #{showPinNames} #{element.symbols.length} L #{powerSymbol}\n"
fs.writeSync fd, "F0 \"#{element.refDes}\" #{refObj.x} #{refObj.y} #{refObj.fontSize} #{refObj.orientation} #{refObj.visible} #{refObj.halign} #{refObj.valign}NN\n"
fs.writeSync fd, "F1 \"#{element.name}\" #{nameObj.x} #{nameObj.y} #{nameObj.fontSize} #{nameObj.orientation} #{nameObj.visible} #{nameObj.halign} #{nameObj.valign}NN\n"
fs.writeSync fd, "F2 \"#{patternName}\" 0 0 0 H I C CNN\n"
if element.datasheet?
fs.writeSync fd, "F3 \"#{element.datasheet}\" 0 0 0 H I C CNN\n"
i = 0
for shape in symbol.shapes
if (shape.kind is 'attribute') and (shape.name isnt 'refDes') and (shape.name isnt 'name')
attrObj = @_symbolObj shape
fs.writeSync fd, "F#{4 + i} \"#{attrObj.text}\" #{attrObj.x} #{attrObj.y} #{attrObj.fontSize} #{attrObj.orientation} V #{attrObj.halign} #{attrObj.valign}NN \"#{attrObj.name}\"\n"
++i
if element.aliases? and element.aliases.length then fs.writeSync fd, "ALIAS #{element.aliases.join(' ')}\n"
if element.pattern?
fs.writeSync fd, "$FPLIST\n"
fs.writeSync fd, " #{element.pattern.name}\n"
fs.writeSync fd, "$ENDFPLIST\n"
fs.writeSync fd, "DRAW\n"
i = 1
for symbol in element.symbols
for shape in symbol.shapes
symObj = @_symbolObj shape
switch symObj.kind
when 'pin' then fs.writeSync fd, "X #{symObj.name} #{symObj.number} #{symObj.x} #{symObj.y} #{symObj.length} #{symObj.orientation} #{symObj.fontSize} #{symObj.fontSize} #{i} 1 #{symObj.type}#{symObj.shape}\n"
when 'rectangle' then fs.writeSync fd, "S #{symObj.x1} #{symObj.y1} #{symObj.x2} #{symObj.y2} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'line' then fs.writeSync fd, "P 2 #{i} 1 #{symObj.lineWidth} #{symObj.x1} #{symObj.y1} #{symObj.x2} #{symObj.y2} N\n"
when 'circle' then fs.writeSync fd, "C #{symObj.x} #{symObj.y} #{symObj.radius} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'arc'
symObj.start = Math.round symObj.start*10
symObj.end = Math.round symObj.end*10
fs.writeSync fd, "A #{symObj.x} #{symObj.y} #{symObj.radius} #{symObj.start} #{symObj.end} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'poly'
pointCount = symObj.points.length / 2
polyPoints = symObj.points.reduce((p, v) -> p + ' ' + v)
fs.writeSync fd, "P #{pointCount} #{i} 1 #{symObj.lineWidth} #{polyPoints} #{symObj.fillStyle}\n"
when 'text'
hidden = if symObj.visible is 'I' then 1 else 0
fs.writeSync fd, "T #{symObj.angle} #{symObj.x} #{symObj.y} #{symObj.fontSize} #{hidden} #{i} 1 \"#{symObj.text}\" #{symObj.italic} #{symObj.bold} #{symObj.halign} #{symObj.valign}\n"
++i
fs.writeSync fd, "ENDDRAW\n"
fs.writeSync fd, "ENDDEF\n"
#
# Write 3D shape file in VRML format
#
_generateVrml: (fd, pattern) ->
x1 = pattern.box.x - pattern.box.width/2
x2 = pattern.box.x + pattern.box.width/2
y1 = pattern.box.y - pattern.box.length/2
y2 = pattern.box.y + pattern.box.length/2
z1 = 0
z2 = pattern.box.height
fs.writeSync fd, "#VRML V2.0 utf8\n"
fs.writeSync fd, "Shape {\n"
fs.writeSync fd, " appearance Appearance {\n"
fs.writeSync fd, " material Material {\n"
fs.writeSync fd, " diffuseColor 0.37 0.37 0.37\n"
fs.writeSync fd, " emissiveColor 0.0 0.0 0.0\n"
fs.writeSync fd, " specularColor 1.0 1.0 1.0\n"
fs.writeSync fd, " ambientIntensity 1.0\n"
fs.writeSync fd, " transparency 0.5\n"
fs.writeSync fd, " shininess 1.0\n"
fs.writeSync fd, " }\n" # Material
fs.writeSync fd, " }\n" # Appearance
fs.writeSync fd, " geometry IndexedFaceSet {\n"
fs.writeSync fd, " coord Coordinate {\n"
fs.writeSync fd, " point [\n"
fs.writeSync fd, " #{x1} #{y1} #{z1},\n"
fs.writeSync fd, " #{x2} #{y1} #{z1},\n"
fs.writeSync fd, " #{x2} #{y2} #{z1},\n"
fs.writeSync fd, " #{x1} #{y2} #{z1},\n"
fs.writeSync fd, " #{x1} #{y1} #{z2},\n"
fs.writeSync fd, " #{x2} #{y1} #{z2},\n"
fs.writeSync fd, " #{x2} #{y2} #{z2},\n"
fs.writeSync fd, " #{x1} #{y2} #{z2}\n"
fs.writeSync fd, " ]\n" # point
fs.writeSync fd, " }\n" # Coordinate
fs.writeSync fd, " coordIndex [\n"
fs.writeSync fd, " 0,1,2,3,-1\n" # bottom
fs.writeSync fd, " 4,5,6,7,-1\n" # top
fs.writeSync fd, " 0,1,5,4,-1\n" # front
fs.writeSync fd, " 2,3,7,6,-1\n" # back
fs.writeSync fd, " 0,3,7,4,-1\n" # left
fs.writeSync fd, " 1,2,6,5,-1\n" # right
fs.writeSync fd, " ]\n" # coordIndex
fs.writeSync fd, " }\n" # IndexedFaceSet
fs.writeSync fd, "}\n" # Shape
#
# Convert definition to pattern object
#
_patternObj: (shape) ->
obj = shape
obj.visible ?= true
if obj.shape is 'rectangle' then obj.shape = 'rect'
if obj.shape is 'circle' and obj.width != obj.height then obj.shape = 'oval'
layers =
topCopper: 'F.Cu'
topMask: 'F.Mask'
topPaste: 'F.Paste'
topSilkscreen: 'F.SilkS'
topAssembly: 'F.Fab'
topCourtyard: 'F.CrtYd'
intCopper: '*.Cu'
bottomCopper: 'B.Cu'
bottomMask: 'B.Mask'
bottomPaste: 'B.Paste'
bottomSilkscreen: 'B.SilkS'
bottomAssembly: 'B.Fab'
bottomCourtyard: 'B.CrtYd'
obj.layer = obj.layer.map((v) => layers[v]).join(' ')
if obj.mask? and (obj.mask < 0.001) then obj.mask = 0.001 # KiCad does not support zero value
if obj.paste? and (obj.paste > -0.001) then obj.paste = -0.001 # KiCad does not support zero value
if obj.kind is 'attribute'
switch obj.name
when 'refDes'
obj.name = 'reference'
obj.text = 'REF**'
obj.fontSize ?= @library.pattern.fontSize.refDes
when 'value'
obj.fontSize ?= @library.pattern.fontSize.value
else
obj.name = 'user'
obj.fontSize ?= @library.pattern.fontSize.default
else if obj.kind is 'pad'
if obj.type is 'mount' then obj.shape ?= 'circle'
obj.width ?= obj.hole ? obj.size
obj.height ?= obj.hole ? obj.size
types =
'smd': 'smd'
'through-hole': 'thru_hole'
'mounting-hole': 'np_thru_hole'
obj.type = types[obj.type]
obj
#
# Convert definition to symbol object
#
_symbolObj: (shape) ->
unless shape? then return
obj = shape
obj.name ?= '~'
if obj.name is '' then obj.name = '~'
obj.visible ?= true
obj.visible = if obj.visible then 'V' else 'I'
obj.halign = switch obj.halign
when 'center' then 'C'
when 'right' then 'R'
else 'L'
obj.valign = switch obj.valign
when 'center' then 'C'
when 'bottom' then 'B'
else 'T'
obj.orientation = switch obj.orientation
when 'left' then 'L'
when 'right' then 'R'
when 'up' then 'U'
when 'down' then 'D'
when 'horizontal' then 'H'
when 'vertical' then 'V'
else 'H'
obj.fontSize = Math.round(obj.fontSize)
obj.italic = if obj.italic then 'Italic' else 'Normal'
obj.bold = if obj.bold then 1 else 0
obj.type = 'U'
if obj.power or obj.ground
obj.type = 'W' # Power input
if obj.out then obj.type = 'w' # Power output
else
if obj.bidir or (obj.in and obj.out)
obj.type = 'B' # Bidirectional
else if obj.in
obj.type = 'I' # Input
else if obj.out
obj.type = 'O' # Output
else if obj.passive
obj.type = 'P' # Passive
else if obj.nc
obj.type = 'N' # Not connected
else if obj.z
obj.type = 'T' # Tristate
else
obj.type = 'U' # Unspecified
obj.shape = ''
if obj.invisible then obj.shape += 'N'
if obj.inverted
obj.shape += 'I'
if obj.shape isnt '' then obj.shape = ' ' + obj.shape
switch obj.fill
when 'foreground' then obj.fillStyle = 'f'
when 'background' then obj.fillStyle = 'F'
else obj.fillStyle = 'N'
obj
module.exports = KicadGenerator
| 121203 | fs = require 'fs'
mkdirp = require 'mkdirp'
sprintf = require('sprintf-js').sprintf
log = require './qeda-log'
#
# Generator of library in KiCad format
#
class KicadGenerator
#
# Constructor
#
constructor: (@library) ->
@f = "%.#{@library.pattern.decimals}f"
#
# Generate symbol library and footprint files
#
generate: (@name) ->
dir = './kicad'
mkdirp.sync "#{dir}/#{@name}.pretty"
mkdirp.sync "#{dir}/#{@name}.3dshapes"
now = new Date
timestamp = sprintf "%02d/%02d/%d %02d:%02d:%02d",
now.getDate(), now.getMonth() + 1, now.getYear() + 1900,
now.getHours(), now.getMinutes(), now.getSeconds()
log.start "KiCad library '#{@name}.lib'"
fd = fs.openSync "#{dir}/#{@name}.lib", 'w'
fs.writeSync fd, "EESchema-LIBRARY Version 2.3 Date: #{timestamp}\n"
fs.writeSync fd, '#encoding utf-8\n'
patterns = {}
# Symbols
for element in @library.elements
@_generateSymbol fd, element
if element.pattern? then patterns[element.pattern.name] = element.pattern
fs.writeSync fd, '# End Library\n'
fs.closeSync fd
log.ok()
# Doc
log.start "KiCad library doc '#{@name}.dcm'"
fd = fs.openSync "#{dir}/#{@name}.dcm", 'w'
fs.writeSync fd, "EESchema-DOCLIB Version 2.0 Date: #{timestamp}\n#\n"
for element in @library.elements
@_generateDoc fd, element
fs.writeSync fd, '# End Doc Library\n'
fs.closeSync fd
log.ok()
# Footprints
for patternName, pattern of patterns
log.start "KiCad footprint '#{patternName}.kicad_mod'"
fd = fs.openSync "#{dir}/#{@name}.pretty/#{patternName}.kicad_mod", 'w'
@_generatePattern fd, pattern
fs.closeSync fd
log.ok()
# 3D shapes
for patternName, pattern of patterns
log.start "KiCad 3D shape '#{patternName}.wrl'"
fd = fs.openSync "#{dir}/#{@name}.3dshapes/#{patternName}.wrl", 'w'
@_generateVrml fd, pattern
fs.closeSync fd
log.ok()
#
# Write doc entry to library doc file
#
_generateDoc: (fd, element) ->
fields = ['description', 'keywords', 'datasheet']
keys = ['<KEY>']
empty = true
for field in fields
if element[field]?
empty = false
break
if empty then return
fs.writeSync fd, "$CMP #{element.name}\n"
for i in [0..(fields.length - 1)]
if element[fields[i]]? then fs.writeSync fd, "#{keys[i]} #{element[fields[i]]}\n"
fs.writeSync fd, '$ENDCMP\n#\n'
#
# Write pattern file
#
_generatePattern: (fd, pattern) ->
fs.writeSync fd, "(module #{pattern.name} (layer F.Cu)\n"
if pattern.type is 'smd' then fs.writeSync fd, " (attr smd)\n"
for shape in pattern.shapes
patObj = @_patternObj shape
switch patObj.kind
when 'attribute'
fs.writeSync(fd,
sprintf(" (fp_text %s %s (at #{@f} #{@f}%s)%s (layer %s)\n",
patObj.name, patObj.text, patObj.x, patObj.y,
if patObj.angle? then (' ' + patObj.angle.toString()) else '',
unless patObj.visible then ' hide' else '',
patObj.layer)
)
fs.writeSync(fd,
sprintf(" (effects (font (size #{@f} #{@f}) (thickness #{@f})))\n",
patObj.fontSize, patObj.fontSize, patObj.lineWidth)
)
fs.writeSync fd, " )\n"
when 'circle'
fs.writeSync(fd,
sprintf(" (fp_circle (center #{@f} #{@f}) (end #{@f} #{@f}) (layer %s) (width #{@f}))\n",
patObj.x, patObj.y, patObj.x, patObj.y + patObj.radius, patObj.layer, patObj.lineWidth)
)
when 'line'
fs.writeSync(fd,
sprintf(" (fp_line (start #{@f} #{@f}) (end #{@f} #{@f}) (layer %s) (width #{@f}))\n"
patObj.x1, patObj.y1, patObj.x2, patObj.y2, patObj.layer, patObj.lineWidth)
)
when 'pad'
if patObj.shape is 'rect' and @library.pattern.smoothPadCorners
cornerRadius = Math.min(patObj.width, patObj.height) * @library.pattern.ratio.cornerToWidth
if cornerRadius > @library.pattern.maximum.cornerRadius then cornerRadius = @library.pattern.maximum.cornerRadius
if cornerRadius > 0 then patObj.shape = 'roundrect'
fs.writeSync(fd,
sprintf(" (pad %s %s %s (at #{@f} #{@f}) (size #{@f} #{@f}) (layers %s)"
patObj.name, patObj.type, patObj.shape, patObj.x, patObj.y, patObj.width, patObj.height, patObj.layer)
)
if patObj.slotWidth? and patObj.slotHeight?
fs.writeSync fd, sprintf("\n (drill oval #{@f} #{@f})", patObj.slotWidth, patObj.slotHeight)
else if patObj.hole?
fs.writeSync fd, sprintf("\n (drill #{@f})", patObj.hole)
if patObj.mask? then fs.writeSync fd, sprintf("\n (solder_mask_margin #{@f})", patObj.mask)
if patObj.paste? then fs.writeSync fd, sprintf("\n (solder_paste_margin #{@f})", patObj.paste)
if patObj.shape is 'roundrect'
ratio = cornerRadius / Math.min(patObj.width, patObj.height)
fs.writeSync fd, sprintf("\n (roundrect_rratio #{@f})", ratio)
fs.writeSync fd, ")\n"
fs.writeSync fd, " (model #{pattern.name}.wrl\n"
fs.writeSync fd, " (at (xyz 0 0 0))\n"
fs.writeSync fd, " (scale (xyz 0.3937 0.3937 0.3937))\n"
fs.writeSync fd, " (rotate (xyz 0 0 0 ))\n"
fs.writeSync fd, " )\n" # model
fs.writeSync fd, ")\n" # module
#
# Write symbol entry to library file
#
_generateSymbol: (fd, element) ->
for symbol in element.symbols
symbol.resize 50, true # Resize to grid 50 mil with rounding
symbol.invertVertical() # Positive vertical axis is pointing up in KiCad
symbol = element.symbols[0]
refObj = @_symbolObj symbol.attributes['refDes']
nameObj = @_symbolObj symbol.attributes['name']
fs.writeSync fd, "#\n# #{element.name}\n#\n"
showPinNumbers = if element.schematic?.showPinNumbers then 'Y' else 'N'
showPinNames = if element.schematic?.showPinNames then 'Y' else 'N'
pinNameSpace = 0
for shape in symbol.shapes
if shape.kind is 'pin'
pinNameSpace = Math.round shape.space
break
patternName = ''
if element.pattern? then patternName = "#{@name}:#{element.pattern.name}"
powerSymbol = 'N'
if element.power then powerSymbol = 'P'
fs.writeSync fd, "DEF #{element.name} #{element.refDes} 0 #{pinNameSpace} #{showPinNumbers} #{showPinNames} #{element.symbols.length} L #{powerSymbol}\n"
fs.writeSync fd, "F0 \"#{element.refDes}\" #{refObj.x} #{refObj.y} #{refObj.fontSize} #{refObj.orientation} #{refObj.visible} #{refObj.halign} #{refObj.valign}NN\n"
fs.writeSync fd, "F1 \"#{element.name}\" #{nameObj.x} #{nameObj.y} #{nameObj.fontSize} #{nameObj.orientation} #{nameObj.visible} #{nameObj.halign} #{nameObj.valign}NN\n"
fs.writeSync fd, "F2 \"#{patternName}\" 0 0 0 H I C CNN\n"
if element.datasheet?
fs.writeSync fd, "F3 \"#{element.datasheet}\" 0 0 0 H I C CNN\n"
i = 0
for shape in symbol.shapes
if (shape.kind is 'attribute') and (shape.name isnt 'refDes') and (shape.name isnt 'name')
attrObj = @_symbolObj shape
fs.writeSync fd, "F#{4 + i} \"#{attrObj.text}\" #{attrObj.x} #{attrObj.y} #{attrObj.fontSize} #{attrObj.orientation} V #{attrObj.halign} #{attrObj.valign}NN \"#{attrObj.name}\"\n"
++i
if element.aliases? and element.aliases.length then fs.writeSync fd, "ALIAS #{element.aliases.join(' ')}\n"
if element.pattern?
fs.writeSync fd, "$FPLIST\n"
fs.writeSync fd, " #{element.pattern.name}\n"
fs.writeSync fd, "$ENDFPLIST\n"
fs.writeSync fd, "DRAW\n"
i = 1
for symbol in element.symbols
for shape in symbol.shapes
symObj = @_symbolObj shape
switch symObj.kind
when 'pin' then fs.writeSync fd, "X #{symObj.name} #{symObj.number} #{symObj.x} #{symObj.y} #{symObj.length} #{symObj.orientation} #{symObj.fontSize} #{symObj.fontSize} #{i} 1 #{symObj.type}#{symObj.shape}\n"
when 'rectangle' then fs.writeSync fd, "S #{symObj.x1} #{symObj.y1} #{symObj.x2} #{symObj.y2} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'line' then fs.writeSync fd, "P 2 #{i} 1 #{symObj.lineWidth} #{symObj.x1} #{symObj.y1} #{symObj.x2} #{symObj.y2} N\n"
when 'circle' then fs.writeSync fd, "C #{symObj.x} #{symObj.y} #{symObj.radius} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'arc'
symObj.start = Math.round symObj.start*10
symObj.end = Math.round symObj.end*10
fs.writeSync fd, "A #{symObj.x} #{symObj.y} #{symObj.radius} #{symObj.start} #{symObj.end} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'poly'
pointCount = symObj.points.length / 2
polyPoints = symObj.points.reduce((p, v) -> p + ' ' + v)
fs.writeSync fd, "P #{pointCount} #{i} 1 #{symObj.lineWidth} #{polyPoints} #{symObj.fillStyle}\n"
when 'text'
hidden = if symObj.visible is 'I' then 1 else 0
fs.writeSync fd, "T #{symObj.angle} #{symObj.x} #{symObj.y} #{symObj.fontSize} #{hidden} #{i} 1 \"#{symObj.text}\" #{symObj.italic} #{symObj.bold} #{symObj.halign} #{symObj.valign}\n"
++i
fs.writeSync fd, "ENDDRAW\n"
fs.writeSync fd, "ENDDEF\n"
#
# Write 3D shape file in VRML format
#
_generateVrml: (fd, pattern) ->
x1 = pattern.box.x - pattern.box.width/2
x2 = pattern.box.x + pattern.box.width/2
y1 = pattern.box.y - pattern.box.length/2
y2 = pattern.box.y + pattern.box.length/2
z1 = 0
z2 = pattern.box.height
fs.writeSync fd, "#VRML V2.0 utf8\n"
fs.writeSync fd, "Shape {\n"
fs.writeSync fd, " appearance Appearance {\n"
fs.writeSync fd, " material Material {\n"
fs.writeSync fd, " diffuseColor 0.37 0.37 0.37\n"
fs.writeSync fd, " emissiveColor 0.0 0.0 0.0\n"
fs.writeSync fd, " specularColor 1.0 1.0 1.0\n"
fs.writeSync fd, " ambientIntensity 1.0\n"
fs.writeSync fd, " transparency 0.5\n"
fs.writeSync fd, " shininess 1.0\n"
fs.writeSync fd, " }\n" # Material
fs.writeSync fd, " }\n" # Appearance
fs.writeSync fd, " geometry IndexedFaceSet {\n"
fs.writeSync fd, " coord Coordinate {\n"
fs.writeSync fd, " point [\n"
fs.writeSync fd, " #{x1} #{y1} #{z1},\n"
fs.writeSync fd, " #{x2} #{y1} #{z1},\n"
fs.writeSync fd, " #{x2} #{y2} #{z1},\n"
fs.writeSync fd, " #{x1} #{y2} #{z1},\n"
fs.writeSync fd, " #{x1} #{y1} #{z2},\n"
fs.writeSync fd, " #{x2} #{y1} #{z2},\n"
fs.writeSync fd, " #{x2} #{y2} #{z2},\n"
fs.writeSync fd, " #{x1} #{y2} #{z2}\n"
fs.writeSync fd, " ]\n" # point
fs.writeSync fd, " }\n" # Coordinate
fs.writeSync fd, " coordIndex [\n"
fs.writeSync fd, " 0,1,2,3,-1\n" # bottom
fs.writeSync fd, " 4,5,6,7,-1\n" # top
fs.writeSync fd, " 0,1,5,4,-1\n" # front
fs.writeSync fd, " 2,3,7,6,-1\n" # back
fs.writeSync fd, " 0,3,7,4,-1\n" # left
fs.writeSync fd, " 1,2,6,5,-1\n" # right
fs.writeSync fd, " ]\n" # coordIndex
fs.writeSync fd, " }\n" # IndexedFaceSet
fs.writeSync fd, "}\n" # Shape
#
# Convert definition to pattern object
#
_patternObj: (shape) ->
obj = shape
obj.visible ?= true
if obj.shape is 'rectangle' then obj.shape = 'rect'
if obj.shape is 'circle' and obj.width != obj.height then obj.shape = 'oval'
layers =
topCopper: 'F.Cu'
topMask: 'F.Mask'
topPaste: 'F.Paste'
topSilkscreen: 'F.SilkS'
topAssembly: 'F.Fab'
topCourtyard: 'F.CrtYd'
intCopper: '*.Cu'
bottomCopper: 'B.Cu'
bottomMask: 'B.Mask'
bottomPaste: 'B.Paste'
bottomSilkscreen: 'B.SilkS'
bottomAssembly: 'B.Fab'
bottomCourtyard: 'B.CrtYd'
obj.layer = obj.layer.map((v) => layers[v]).join(' ')
if obj.mask? and (obj.mask < 0.001) then obj.mask = 0.001 # KiCad does not support zero value
if obj.paste? and (obj.paste > -0.001) then obj.paste = -0.001 # KiCad does not support zero value
if obj.kind is 'attribute'
switch obj.name
when 'refDes'
obj.name = 'reference'
obj.text = 'REF**'
obj.fontSize ?= @library.pattern.fontSize.refDes
when 'value'
obj.fontSize ?= @library.pattern.fontSize.value
else
obj.name = 'user'
obj.fontSize ?= @library.pattern.fontSize.default
else if obj.kind is 'pad'
if obj.type is 'mount' then obj.shape ?= 'circle'
obj.width ?= obj.hole ? obj.size
obj.height ?= obj.hole ? obj.size
types =
'smd': 'smd'
'through-hole': 'thru_hole'
'mounting-hole': 'np_thru_hole'
obj.type = types[obj.type]
obj
#
# Convert definition to symbol object
#
_symbolObj: (shape) ->
unless shape? then return
obj = shape
obj.name ?= '~'
if obj.name is '' then obj.name = '~'
obj.visible ?= true
obj.visible = if obj.visible then 'V' else 'I'
obj.halign = switch obj.halign
when 'center' then 'C'
when 'right' then 'R'
else 'L'
obj.valign = switch obj.valign
when 'center' then 'C'
when 'bottom' then 'B'
else 'T'
obj.orientation = switch obj.orientation
when 'left' then 'L'
when 'right' then 'R'
when 'up' then 'U'
when 'down' then 'D'
when 'horizontal' then 'H'
when 'vertical' then 'V'
else 'H'
obj.fontSize = Math.round(obj.fontSize)
obj.italic = if obj.italic then 'Italic' else 'Normal'
obj.bold = if obj.bold then 1 else 0
obj.type = 'U'
if obj.power or obj.ground
obj.type = 'W' # Power input
if obj.out then obj.type = 'w' # Power output
else
if obj.bidir or (obj.in and obj.out)
obj.type = 'B' # Bidirectional
else if obj.in
obj.type = 'I' # Input
else if obj.out
obj.type = 'O' # Output
else if obj.passive
obj.type = 'P' # Passive
else if obj.nc
obj.type = 'N' # Not connected
else if obj.z
obj.type = 'T' # Tristate
else
obj.type = 'U' # Unspecified
obj.shape = ''
if obj.invisible then obj.shape += 'N'
if obj.inverted
obj.shape += 'I'
if obj.shape isnt '' then obj.shape = ' ' + obj.shape
switch obj.fill
when 'foreground' then obj.fillStyle = 'f'
when 'background' then obj.fillStyle = 'F'
else obj.fillStyle = 'N'
obj
module.exports = KicadGenerator
| true | fs = require 'fs'
mkdirp = require 'mkdirp'
sprintf = require('sprintf-js').sprintf
log = require './qeda-log'
#
# Generator of library in KiCad format
#
class KicadGenerator
#
# Constructor
#
constructor: (@library) ->
@f = "%.#{@library.pattern.decimals}f"
#
# Generate symbol library and footprint files
#
generate: (@name) ->
dir = './kicad'
mkdirp.sync "#{dir}/#{@name}.pretty"
mkdirp.sync "#{dir}/#{@name}.3dshapes"
now = new Date
timestamp = sprintf "%02d/%02d/%d %02d:%02d:%02d",
now.getDate(), now.getMonth() + 1, now.getYear() + 1900,
now.getHours(), now.getMinutes(), now.getSeconds()
log.start "KiCad library '#{@name}.lib'"
fd = fs.openSync "#{dir}/#{@name}.lib", 'w'
fs.writeSync fd, "EESchema-LIBRARY Version 2.3 Date: #{timestamp}\n"
fs.writeSync fd, '#encoding utf-8\n'
patterns = {}
# Symbols
for element in @library.elements
@_generateSymbol fd, element
if element.pattern? then patterns[element.pattern.name] = element.pattern
fs.writeSync fd, '# End Library\n'
fs.closeSync fd
log.ok()
# Doc
log.start "KiCad library doc '#{@name}.dcm'"
fd = fs.openSync "#{dir}/#{@name}.dcm", 'w'
fs.writeSync fd, "EESchema-DOCLIB Version 2.0 Date: #{timestamp}\n#\n"
for element in @library.elements
@_generateDoc fd, element
fs.writeSync fd, '# End Doc Library\n'
fs.closeSync fd
log.ok()
# Footprints
for patternName, pattern of patterns
log.start "KiCad footprint '#{patternName}.kicad_mod'"
fd = fs.openSync "#{dir}/#{@name}.pretty/#{patternName}.kicad_mod", 'w'
@_generatePattern fd, pattern
fs.closeSync fd
log.ok()
# 3D shapes
for patternName, pattern of patterns
log.start "KiCad 3D shape '#{patternName}.wrl'"
fd = fs.openSync "#{dir}/#{@name}.3dshapes/#{patternName}.wrl", 'w'
@_generateVrml fd, pattern
fs.closeSync fd
log.ok()
#
# Write doc entry to library doc file
#
_generateDoc: (fd, element) ->
fields = ['description', 'keywords', 'datasheet']
keys = ['PI:KEY:<KEY>END_PI']
empty = true
for field in fields
if element[field]?
empty = false
break
if empty then return
fs.writeSync fd, "$CMP #{element.name}\n"
for i in [0..(fields.length - 1)]
if element[fields[i]]? then fs.writeSync fd, "#{keys[i]} #{element[fields[i]]}\n"
fs.writeSync fd, '$ENDCMP\n#\n'
#
# Write pattern file
#
_generatePattern: (fd, pattern) ->
fs.writeSync fd, "(module #{pattern.name} (layer F.Cu)\n"
if pattern.type is 'smd' then fs.writeSync fd, " (attr smd)\n"
for shape in pattern.shapes
patObj = @_patternObj shape
switch patObj.kind
when 'attribute'
fs.writeSync(fd,
sprintf(" (fp_text %s %s (at #{@f} #{@f}%s)%s (layer %s)\n",
patObj.name, patObj.text, patObj.x, patObj.y,
if patObj.angle? then (' ' + patObj.angle.toString()) else '',
unless patObj.visible then ' hide' else '',
patObj.layer)
)
fs.writeSync(fd,
sprintf(" (effects (font (size #{@f} #{@f}) (thickness #{@f})))\n",
patObj.fontSize, patObj.fontSize, patObj.lineWidth)
)
fs.writeSync fd, " )\n"
when 'circle'
fs.writeSync(fd,
sprintf(" (fp_circle (center #{@f} #{@f}) (end #{@f} #{@f}) (layer %s) (width #{@f}))\n",
patObj.x, patObj.y, patObj.x, patObj.y + patObj.radius, patObj.layer, patObj.lineWidth)
)
when 'line'
fs.writeSync(fd,
sprintf(" (fp_line (start #{@f} #{@f}) (end #{@f} #{@f}) (layer %s) (width #{@f}))\n"
patObj.x1, patObj.y1, patObj.x2, patObj.y2, patObj.layer, patObj.lineWidth)
)
when 'pad'
if patObj.shape is 'rect' and @library.pattern.smoothPadCorners
cornerRadius = Math.min(patObj.width, patObj.height) * @library.pattern.ratio.cornerToWidth
if cornerRadius > @library.pattern.maximum.cornerRadius then cornerRadius = @library.pattern.maximum.cornerRadius
if cornerRadius > 0 then patObj.shape = 'roundrect'
fs.writeSync(fd,
sprintf(" (pad %s %s %s (at #{@f} #{@f}) (size #{@f} #{@f}) (layers %s)"
patObj.name, patObj.type, patObj.shape, patObj.x, patObj.y, patObj.width, patObj.height, patObj.layer)
)
if patObj.slotWidth? and patObj.slotHeight?
fs.writeSync fd, sprintf("\n (drill oval #{@f} #{@f})", patObj.slotWidth, patObj.slotHeight)
else if patObj.hole?
fs.writeSync fd, sprintf("\n (drill #{@f})", patObj.hole)
if patObj.mask? then fs.writeSync fd, sprintf("\n (solder_mask_margin #{@f})", patObj.mask)
if patObj.paste? then fs.writeSync fd, sprintf("\n (solder_paste_margin #{@f})", patObj.paste)
if patObj.shape is 'roundrect'
ratio = cornerRadius / Math.min(patObj.width, patObj.height)
fs.writeSync fd, sprintf("\n (roundrect_rratio #{@f})", ratio)
fs.writeSync fd, ")\n"
fs.writeSync fd, " (model #{pattern.name}.wrl\n"
fs.writeSync fd, " (at (xyz 0 0 0))\n"
fs.writeSync fd, " (scale (xyz 0.3937 0.3937 0.3937))\n"
fs.writeSync fd, " (rotate (xyz 0 0 0 ))\n"
fs.writeSync fd, " )\n" # model
fs.writeSync fd, ")\n" # module
#
# Write symbol entry to library file
#
_generateSymbol: (fd, element) ->
for symbol in element.symbols
symbol.resize 50, true # Resize to grid 50 mil with rounding
symbol.invertVertical() # Positive vertical axis is pointing up in KiCad
symbol = element.symbols[0]
refObj = @_symbolObj symbol.attributes['refDes']
nameObj = @_symbolObj symbol.attributes['name']
fs.writeSync fd, "#\n# #{element.name}\n#\n"
showPinNumbers = if element.schematic?.showPinNumbers then 'Y' else 'N'
showPinNames = if element.schematic?.showPinNames then 'Y' else 'N'
pinNameSpace = 0
for shape in symbol.shapes
if shape.kind is 'pin'
pinNameSpace = Math.round shape.space
break
patternName = ''
if element.pattern? then patternName = "#{@name}:#{element.pattern.name}"
powerSymbol = 'N'
if element.power then powerSymbol = 'P'
fs.writeSync fd, "DEF #{element.name} #{element.refDes} 0 #{pinNameSpace} #{showPinNumbers} #{showPinNames} #{element.symbols.length} L #{powerSymbol}\n"
fs.writeSync fd, "F0 \"#{element.refDes}\" #{refObj.x} #{refObj.y} #{refObj.fontSize} #{refObj.orientation} #{refObj.visible} #{refObj.halign} #{refObj.valign}NN\n"
fs.writeSync fd, "F1 \"#{element.name}\" #{nameObj.x} #{nameObj.y} #{nameObj.fontSize} #{nameObj.orientation} #{nameObj.visible} #{nameObj.halign} #{nameObj.valign}NN\n"
fs.writeSync fd, "F2 \"#{patternName}\" 0 0 0 H I C CNN\n"
if element.datasheet?
fs.writeSync fd, "F3 \"#{element.datasheet}\" 0 0 0 H I C CNN\n"
i = 0
for shape in symbol.shapes
if (shape.kind is 'attribute') and (shape.name isnt 'refDes') and (shape.name isnt 'name')
attrObj = @_symbolObj shape
fs.writeSync fd, "F#{4 + i} \"#{attrObj.text}\" #{attrObj.x} #{attrObj.y} #{attrObj.fontSize} #{attrObj.orientation} V #{attrObj.halign} #{attrObj.valign}NN \"#{attrObj.name}\"\n"
++i
if element.aliases? and element.aliases.length then fs.writeSync fd, "ALIAS #{element.aliases.join(' ')}\n"
if element.pattern?
fs.writeSync fd, "$FPLIST\n"
fs.writeSync fd, " #{element.pattern.name}\n"
fs.writeSync fd, "$ENDFPLIST\n"
fs.writeSync fd, "DRAW\n"
i = 1
for symbol in element.symbols
for shape in symbol.shapes
symObj = @_symbolObj shape
switch symObj.kind
when 'pin' then fs.writeSync fd, "X #{symObj.name} #{symObj.number} #{symObj.x} #{symObj.y} #{symObj.length} #{symObj.orientation} #{symObj.fontSize} #{symObj.fontSize} #{i} 1 #{symObj.type}#{symObj.shape}\n"
when 'rectangle' then fs.writeSync fd, "S #{symObj.x1} #{symObj.y1} #{symObj.x2} #{symObj.y2} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'line' then fs.writeSync fd, "P 2 #{i} 1 #{symObj.lineWidth} #{symObj.x1} #{symObj.y1} #{symObj.x2} #{symObj.y2} N\n"
when 'circle' then fs.writeSync fd, "C #{symObj.x} #{symObj.y} #{symObj.radius} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'arc'
symObj.start = Math.round symObj.start*10
symObj.end = Math.round symObj.end*10
fs.writeSync fd, "A #{symObj.x} #{symObj.y} #{symObj.radius} #{symObj.start} #{symObj.end} #{i} 1 #{symObj.lineWidth} #{symObj.fillStyle}\n"
when 'poly'
pointCount = symObj.points.length / 2
polyPoints = symObj.points.reduce((p, v) -> p + ' ' + v)
fs.writeSync fd, "P #{pointCount} #{i} 1 #{symObj.lineWidth} #{polyPoints} #{symObj.fillStyle}\n"
when 'text'
hidden = if symObj.visible is 'I' then 1 else 0
fs.writeSync fd, "T #{symObj.angle} #{symObj.x} #{symObj.y} #{symObj.fontSize} #{hidden} #{i} 1 \"#{symObj.text}\" #{symObj.italic} #{symObj.bold} #{symObj.halign} #{symObj.valign}\n"
++i
fs.writeSync fd, "ENDDRAW\n"
fs.writeSync fd, "ENDDEF\n"
#
# Write 3D shape file in VRML format
#
_generateVrml: (fd, pattern) ->
x1 = pattern.box.x - pattern.box.width/2
x2 = pattern.box.x + pattern.box.width/2
y1 = pattern.box.y - pattern.box.length/2
y2 = pattern.box.y + pattern.box.length/2
z1 = 0
z2 = pattern.box.height
fs.writeSync fd, "#VRML V2.0 utf8\n"
fs.writeSync fd, "Shape {\n"
fs.writeSync fd, " appearance Appearance {\n"
fs.writeSync fd, " material Material {\n"
fs.writeSync fd, " diffuseColor 0.37 0.37 0.37\n"
fs.writeSync fd, " emissiveColor 0.0 0.0 0.0\n"
fs.writeSync fd, " specularColor 1.0 1.0 1.0\n"
fs.writeSync fd, " ambientIntensity 1.0\n"
fs.writeSync fd, " transparency 0.5\n"
fs.writeSync fd, " shininess 1.0\n"
fs.writeSync fd, " }\n" # Material
fs.writeSync fd, " }\n" # Appearance
fs.writeSync fd, " geometry IndexedFaceSet {\n"
fs.writeSync fd, " coord Coordinate {\n"
fs.writeSync fd, " point [\n"
fs.writeSync fd, " #{x1} #{y1} #{z1},\n"
fs.writeSync fd, " #{x2} #{y1} #{z1},\n"
fs.writeSync fd, " #{x2} #{y2} #{z1},\n"
fs.writeSync fd, " #{x1} #{y2} #{z1},\n"
fs.writeSync fd, " #{x1} #{y1} #{z2},\n"
fs.writeSync fd, " #{x2} #{y1} #{z2},\n"
fs.writeSync fd, " #{x2} #{y2} #{z2},\n"
fs.writeSync fd, " #{x1} #{y2} #{z2}\n"
fs.writeSync fd, " ]\n" # point
fs.writeSync fd, " }\n" # Coordinate
fs.writeSync fd, " coordIndex [\n"
fs.writeSync fd, " 0,1,2,3,-1\n" # bottom
fs.writeSync fd, " 4,5,6,7,-1\n" # top
fs.writeSync fd, " 0,1,5,4,-1\n" # front
fs.writeSync fd, " 2,3,7,6,-1\n" # back
fs.writeSync fd, " 0,3,7,4,-1\n" # left
fs.writeSync fd, " 1,2,6,5,-1\n" # right
fs.writeSync fd, " ]\n" # coordIndex
fs.writeSync fd, " }\n" # IndexedFaceSet
fs.writeSync fd, "}\n" # Shape
#
# Convert definition to pattern object
#
_patternObj: (shape) ->
obj = shape
obj.visible ?= true
if obj.shape is 'rectangle' then obj.shape = 'rect'
if obj.shape is 'circle' and obj.width != obj.height then obj.shape = 'oval'
layers =
topCopper: 'F.Cu'
topMask: 'F.Mask'
topPaste: 'F.Paste'
topSilkscreen: 'F.SilkS'
topAssembly: 'F.Fab'
topCourtyard: 'F.CrtYd'
intCopper: '*.Cu'
bottomCopper: 'B.Cu'
bottomMask: 'B.Mask'
bottomPaste: 'B.Paste'
bottomSilkscreen: 'B.SilkS'
bottomAssembly: 'B.Fab'
bottomCourtyard: 'B.CrtYd'
obj.layer = obj.layer.map((v) => layers[v]).join(' ')
if obj.mask? and (obj.mask < 0.001) then obj.mask = 0.001 # KiCad does not support zero value
if obj.paste? and (obj.paste > -0.001) then obj.paste = -0.001 # KiCad does not support zero value
if obj.kind is 'attribute'
switch obj.name
when 'refDes'
obj.name = 'reference'
obj.text = 'REF**'
obj.fontSize ?= @library.pattern.fontSize.refDes
when 'value'
obj.fontSize ?= @library.pattern.fontSize.value
else
obj.name = 'user'
obj.fontSize ?= @library.pattern.fontSize.default
else if obj.kind is 'pad'
if obj.type is 'mount' then obj.shape ?= 'circle'
obj.width ?= obj.hole ? obj.size
obj.height ?= obj.hole ? obj.size
types =
'smd': 'smd'
'through-hole': 'thru_hole'
'mounting-hole': 'np_thru_hole'
obj.type = types[obj.type]
obj
#
# Convert definition to symbol object
#
_symbolObj: (shape) ->
unless shape? then return
obj = shape
obj.name ?= '~'
if obj.name is '' then obj.name = '~'
obj.visible ?= true
obj.visible = if obj.visible then 'V' else 'I'
obj.halign = switch obj.halign
when 'center' then 'C'
when 'right' then 'R'
else 'L'
obj.valign = switch obj.valign
when 'center' then 'C'
when 'bottom' then 'B'
else 'T'
obj.orientation = switch obj.orientation
when 'left' then 'L'
when 'right' then 'R'
when 'up' then 'U'
when 'down' then 'D'
when 'horizontal' then 'H'
when 'vertical' then 'V'
else 'H'
obj.fontSize = Math.round(obj.fontSize)
obj.italic = if obj.italic then 'Italic' else 'Normal'
obj.bold = if obj.bold then 1 else 0
obj.type = 'U'
if obj.power or obj.ground
obj.type = 'W' # Power input
if obj.out then obj.type = 'w' # Power output
else
if obj.bidir or (obj.in and obj.out)
obj.type = 'B' # Bidirectional
else if obj.in
obj.type = 'I' # Input
else if obj.out
obj.type = 'O' # Output
else if obj.passive
obj.type = 'P' # Passive
else if obj.nc
obj.type = 'N' # Not connected
else if obj.z
obj.type = 'T' # Tristate
else
obj.type = 'U' # Unspecified
obj.shape = ''
if obj.invisible then obj.shape += 'N'
if obj.inverted
obj.shape += 'I'
if obj.shape isnt '' then obj.shape = ' ' + obj.shape
switch obj.fill
when 'foreground' then obj.fillStyle = 'f'
when 'background' then obj.fillStyle = 'F'
else obj.fillStyle = 'N'
obj
module.exports = KicadGenerator
|
[
{
"context": "xports.greeting = greeting\n\nconsole.log greeting \"Marcus Hammarberg\"",
"end": 115,
"score": 0.9998927712440491,
"start": 98,
"tag": "NAME",
"value": "Marcus Hammarberg"
}
] | src/index.coffee | marcusoftnet/FirstCoffeeDemo | 1 | greeting = (name) ->
"Hello #{name}!"
module.exports.greeting = greeting
console.log greeting "Marcus Hammarberg" | 71636 | greeting = (name) ->
"Hello #{name}!"
module.exports.greeting = greeting
console.log greeting "<NAME>" | true | greeting = (name) ->
"Hello #{name}!"
module.exports.greeting = greeting
console.log greeting "PI:NAME:<NAME>END_PI" |
[
{
"context": "leric\n * @package Spells\n */`\n {name: \"titan strength\", spellPower: 8, cost: 900, class: \"Cleric\", leve",
"end": 1867,
"score": 0.8705074787139893,
"start": 1853,
"tag": "NAME",
"value": "titan strength"
}
] | src/character/spells/buffs/single/BoarStrength.coffee | sadbear-/IdleLands | 3 |
Spell = require "../../../base/Spell"
class BoarStrength extends Spell
name: "boar strength"
@element = BoarStrength::element = Spell::Element.buff
@tiers = BoarStrength::tiers = [
`/**
* This spell buffs the strength of an ally.
*
* @name boar strength
* @requirement {class} Cleric
* @requirement {mp} 300
* @requirement {level} 4
* @element buff
* @targets {ally} 1
* @effect +15% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "boar strength", spellPower: 1, cost: 300, class: "Cleric", level: 4}
`/**
* This spell buffs the strength of an ally.
*
* @name demon strength
* @requirement {class} Cleric
* @requirement {mp} 500
* @requirement {level} 29
* @element buff
* @targets {ally} 1
* @effect +30% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "demon strength", spellPower: 2, cost: 500, class: "Cleric", level: 29}
`/**
* This spell buffs the strength of an ally.
*
* @name dragon strength
* @requirement {class} Cleric
* @requirement {mp} 700
* @requirement {level} 54
* @element buff
* @targets {ally} 1
* @effect +60% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "dragon strength", spellPower: 4, cost: 700, class: "Cleric", level: 54}
`/**
* This spell buffs the strength of an ally.
*
* @name titan strength
* @requirement {class} Cleric
* @requirement {mp} 900
* @requirement {level} 79
* @element buff
* @targets {ally} 1
* @effect +120% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "titan strength", spellPower: 8, cost: 900, class: "Cleric", level: 79}
]
calcDuration: -> super()+4
determineTargets: ->
@targetSomeAllies()
strPercent: -> 15*@spellPower
cast: (player) ->
message = "%casterName infused %targetName with %spellName!"
@broadcast player, message
tick: (player) ->
message = "%casterName's %spellName on %targetName is fading slowly!"
@broadcastBuffMessage player, message
uncast: (player) ->
message = "%targetName no longer has %spellName."
@broadcast player, message
constructor: (@game, @caster) ->
super @game, @caster
@bindings =
doSpellCast: @cast
doSpellUncast: @uncast
"combat.self.turn.end": @tick
module.exports = exports = BoarStrength | 74690 |
Spell = require "../../../base/Spell"
class BoarStrength extends Spell
name: "boar strength"
@element = BoarStrength::element = Spell::Element.buff
@tiers = BoarStrength::tiers = [
`/**
* This spell buffs the strength of an ally.
*
* @name boar strength
* @requirement {class} Cleric
* @requirement {mp} 300
* @requirement {level} 4
* @element buff
* @targets {ally} 1
* @effect +15% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "boar strength", spellPower: 1, cost: 300, class: "Cleric", level: 4}
`/**
* This spell buffs the strength of an ally.
*
* @name demon strength
* @requirement {class} Cleric
* @requirement {mp} 500
* @requirement {level} 29
* @element buff
* @targets {ally} 1
* @effect +30% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "demon strength", spellPower: 2, cost: 500, class: "Cleric", level: 29}
`/**
* This spell buffs the strength of an ally.
*
* @name dragon strength
* @requirement {class} Cleric
* @requirement {mp} 700
* @requirement {level} 54
* @element buff
* @targets {ally} 1
* @effect +60% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "dragon strength", spellPower: 4, cost: 700, class: "Cleric", level: 54}
`/**
* This spell buffs the strength of an ally.
*
* @name titan strength
* @requirement {class} Cleric
* @requirement {mp} 900
* @requirement {level} 79
* @element buff
* @targets {ally} 1
* @effect +120% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "<NAME>", spellPower: 8, cost: 900, class: "Cleric", level: 79}
]
calcDuration: -> super()+4
determineTargets: ->
@targetSomeAllies()
strPercent: -> 15*@spellPower
cast: (player) ->
message = "%casterName infused %targetName with %spellName!"
@broadcast player, message
tick: (player) ->
message = "%casterName's %spellName on %targetName is fading slowly!"
@broadcastBuffMessage player, message
uncast: (player) ->
message = "%targetName no longer has %spellName."
@broadcast player, message
constructor: (@game, @caster) ->
super @game, @caster
@bindings =
doSpellCast: @cast
doSpellUncast: @uncast
"combat.self.turn.end": @tick
module.exports = exports = BoarStrength | true |
Spell = require "../../../base/Spell"
class BoarStrength extends Spell
name: "boar strength"
@element = BoarStrength::element = Spell::Element.buff
@tiers = BoarStrength::tiers = [
`/**
* This spell buffs the strength of an ally.
*
* @name boar strength
* @requirement {class} Cleric
* @requirement {mp} 300
* @requirement {level} 4
* @element buff
* @targets {ally} 1
* @effect +15% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "boar strength", spellPower: 1, cost: 300, class: "Cleric", level: 4}
`/**
* This spell buffs the strength of an ally.
*
* @name demon strength
* @requirement {class} Cleric
* @requirement {mp} 500
* @requirement {level} 29
* @element buff
* @targets {ally} 1
* @effect +30% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "demon strength", spellPower: 2, cost: 500, class: "Cleric", level: 29}
`/**
* This spell buffs the strength of an ally.
*
* @name dragon strength
* @requirement {class} Cleric
* @requirement {mp} 700
* @requirement {level} 54
* @element buff
* @targets {ally} 1
* @effect +60% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "dragon strength", spellPower: 4, cost: 700, class: "Cleric", level: 54}
`/**
* This spell buffs the strength of an ally.
*
* @name titan strength
* @requirement {class} Cleric
* @requirement {mp} 900
* @requirement {level} 79
* @element buff
* @targets {ally} 1
* @effect +120% STR
* @duration 4 rounds
* @category Cleric
* @package Spells
*/`
{name: "PI:NAME:<NAME>END_PI", spellPower: 8, cost: 900, class: "Cleric", level: 79}
]
calcDuration: -> super()+4
determineTargets: ->
@targetSomeAllies()
strPercent: -> 15*@spellPower
cast: (player) ->
message = "%casterName infused %targetName with %spellName!"
@broadcast player, message
tick: (player) ->
message = "%casterName's %spellName on %targetName is fading slowly!"
@broadcastBuffMessage player, message
uncast: (player) ->
message = "%targetName no longer has %spellName."
@broadcast player, message
constructor: (@game, @caster) ->
super @game, @caster
@bindings =
doSpellCast: @cast
doSpellUncast: @uncast
"combat.self.turn.end": @tick
module.exports = exports = BoarStrength |
[
{
"context": "est.deepEqual sieved.params(),\n [true, 'gmail.com', 'fake', 100, 200, 1000, 10, 20]\n\n test.do",
"end": 1559,
"score": 0.6136332154273987,
"start": 1559,
"tag": "EMAIL",
"value": ""
}
] | test/siv.coffee | snd/siv | 0 | mesa = require 'mesa'
moment = require 'moment'
qs = require 'qs'
siv = require '../src/siv'
userTable = mesa.table('user')
error = new siv.Error {error: 'i am an error'}
module.exports =
'readme example': (test) ->
querystring = [
'limit=10',
'offset=20',
'order=name',
'asc=true',
'where[is_active]=true',
'where[email][ends]=gmail.com',
'where[email][notcontains]=fake',
'where[id][notin][]=100',
'where[id][notin][]=200',
'where[id][lt]=1000',
].join('&')
query = qs.parse(querystring)
test.deepEqual query,
limit: '10'
offset: '20'
order: 'name'
asc: 'true'
where:
is_active: 'true'
email:
ends: 'gmail.com'
notcontains: 'fake'
id:
notin: ['100', '200']
lt: '1000'
sieved = mesa.table('user')
sieved = siv.limit(sieved, query)
sieved = siv.offset(sieved, query)
sieved = siv.order(sieved, query, {allow: ['name']})
sieved = siv.boolean(sieved, query, 'is_active')
sieved = siv.string(sieved, query, 'email')
sieved = siv.integer(sieved, query, 'id')
test.ok not siv.isError sieved
test.equal sieved.sql(), [
'SELECT * FROM "user"'
'WHERE ("is_active" = ?)'
'AND email ILIKE \'%\' || ?'
'AND email NOT ILIKE \'%\' || ? || \'%\''
'AND ("id" NOT IN (?, ?))'
'AND ("id" < ?)'
'ORDER BY name ASC'
'LIMIT ?'
'OFFSET ?'
].join(' ')
test.deepEqual sieved.params(),
[true, 'gmail.com', 'fake', 100, 200, 1000, 10, 20]
test.done()
'limit':
'ignore if not set': (test) ->
sieved = siv.limit userTable, qs.parse 'foo=10'
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'set': (test) ->
sieved = siv.limit userTable, qs.parse 'limit=10'
test.equal sieved.sql(), 'SELECT * FROM "user" LIMIT ?'
test.deepEqual sieved.params(), [10]
test.done()
'error create': (test) ->
sieved = siv.limit userTable, qs.parse 'limit=a'
test.ok siv.isError sieved
test.deepEqual sieved.json,
limit: 'must be an integer'
test.done()
'error passthrough when set': (test) ->
sieved = siv.limit error, qs.parse 'limit=10'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.limit error, qs.parse 'limit=a'
test.ok siv.isError sieved
test.notEqual error, sieved
test.deepEqual sieved.json,
error: 'i am an error'
limit: 'must be an integer'
test.done()
'offset':
'ignore if not set': (test) ->
sieved = siv.offset userTable, qs.parse 'foo=10'
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'set': (test) ->
sieved = siv.offset userTable, qs.parse 'offset=10'
test.equal sieved.sql(), 'SELECT * FROM "user" OFFSET ?'
test.deepEqual sieved.params(), [10]
test.done()
'error create': (test) ->
sieved = siv.offset userTable, qs.parse 'offset=a'
test.ok siv.isError sieved
test.deepEqual sieved.json,
offset: 'must be an integer'
test.done()
'error passthrough when set': (test) ->
sieved = siv.offset error, qs.parse 'offset=10'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.offset error, qs.parse 'offset=a'
test.ok siv.isError sieved
test.notEqual error, sieved
test.deepEqual sieved.json,
error: 'i am an error'
offset: 'must be an integer'
test.done()
'order':
'throw when none allowed': (test) ->
test.expect 2
try
siv.order userTable, {}
catch e
test.equal e.message, '`options.allow` must be an array with at least one element'
try
siv.order userTable, {}, {allow: []}
catch e
test.equal e.message, '`options.allow` must be an array with at least one element'
test.done()
'throw when only options.asc set': (test) ->
try
siv.order userTable, {},
allow: ['id']
asc: true
catch e
test.equal e.message, 'if `options.asc` is set then `options.order` must also be set'
test.done()
'ignored when no default and not set': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'default order': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
order: 'created_at'
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY created_at ASC'
test.deepEqual sieved.params(), []
test.done()
'default order and asc': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
order: 'created_at'
asc: false
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY created_at DESC'
test.deepEqual sieved.params(), []
test.done()
'error when blank query.order': (test) ->
sieved = siv.order userTable, qs.parse('order='),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
order: 'must not be blank if set'
test.done()
'error when not allowed': (test) ->
sieved = siv.order userTable, qs.parse('order=name'),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
order: 'ordering by this column is not allowed'
test.done()
'error when query.asc is not the string `true` or the string `false`': (test) ->
sieved = siv.order userTable, qs.parse('asc=foo'),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
asc: 'must be either the string `true` or the string `false`'
test.done()
'error when no default and only asc': (test) ->
sieved = siv.order userTable, qs.parse('asc=true'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
asc: 'if `asc` is set then `order` must also be set'
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.order error, qs.parse('foo=true'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.order error, qs.parse('order=id'),
allow: ['name', 'id']
order: 'name'
asc: true
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.order error, qs.parse('order=name'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
order: 'ordering by this column is not allowed'
test.done()
'error extend twice': (test) ->
sieved = siv.order error, qs.parse('order=name&asc=foo'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
order: 'ordering by this column is not allowed'
asc: 'must be either the string `true` or the string `false`'
test.done()
'set order': (test) ->
sieved = siv.order userTable, qs.parse('order=id'),
allow: ['name', 'id']
order: 'name'
asc: true
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY id ASC'
test.deepEqual sieved.params(), []
test.done()
'set order and asc': (test) ->
sieved = siv.order userTable, qs.parse('order=id&asc=false'),
allow: ['name', 'id']
order: 'name'
asc: true
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY id DESC'
test.deepEqual sieved.params(), []
test.done()
'nullable':
'ignore if not set': (test) ->
sieved = siv.nullable userTable, {foo: '10'}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not the string `true` or the string `false`': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {null: 'must be either the string `true` or the string `false`'}}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.nullable error, {foo: 'true'}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.nullable error, {where: {name: {null: 'true'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.nullable error, {where: {name: {null: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {null: 'must be either the string `true` or the string `false`'}}
error: 'i am an error'
test.done()
'set null': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'true'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IS NULL'
test.done()
'set not null': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'false'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IS NOT NULL'
test.done()
'integer':
'ignore if not set': (test) ->
sieved = siv.integer userTable, {foo: '10'}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.integer error, {foo: 'true'}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'short form':
'error passthrough when set': (test) ->
sieved = siv.integer error, {where: {id: '10'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error when not integer': (test) ->
sieved = siv.integer userTable, {where: {id: 'foo'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: 'must be parsable as an integer'}
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: 'foo'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: 'must be parsable as an integer'}
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.integer userTable, {where: {id: '10'}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" = ?'
test.deepEqual sieved.params(), [10]
test.done()
'long form':
'error passthrough when set': (test) ->
sieved = siv.integer error, {where: {id: {equals: '10'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'create error when not integer': (test) ->
sieved = siv.integer userTable, {where: {id: {equals: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {equals: 'must be parsable as an integer'}}
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: {equals: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {equals: 'must be parsable as an integer'}}
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.integer userTable, {where: {id: {equals: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" = ?'
test.deepEqual sieved.params(), [10]
test.done()
'notequals': (test) ->
sieved = siv.integer userTable, {where: {id: {notequals: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" != ?'
test.deepEqual sieved.params(), [10]
test.done()
'lt': (test) ->
sieved = siv.integer userTable, {where: {id: {lt: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" < ?'
test.deepEqual sieved.params(), [10]
test.done()
'lte': (test) ->
sieved = siv.integer userTable, {where: {id: {lte: '1000'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" <= ?'
test.deepEqual sieved.params(), [1000]
test.done()
'gt': (test) ->
sieved = siv.integer userTable, {where: {id: {gt: '439'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" > ?'
test.deepEqual sieved.params(), [439]
test.done()
'gte': (test) ->
sieved = siv.integer userTable, {where: {id: {gte: '9383498'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" >= ?'
test.deepEqual sieved.params(), [9383498]
test.done()
'in & notin':
'create error when not array': (test) ->
sieved = siv.integer userTable, {where: {id: {in: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must be an array'}}
test.done()
'create error when empty array': (test) ->
sieved = siv.integer userTable, {where: {id: {in: []}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must not be empty'}}
test.done()
'create error when items not parsable': (test) ->
sieved = siv.integer userTable, {where: {id: {in: ['foo', '1', '2', 'bar', '3']}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where:
id:
in:
0: 'must be parsable as an integer'
3: 'must be parsable as an integer'
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: {in: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must be an array'}}
error: 'i am an error'
test.done()
'in': (test) ->
sieved = siv.integer userTable, {where: {id: {in: [1, 2, 3]}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" IN (?, ?, ?)'
test.deepEqual sieved.params(), [1, 2, 3]
test.done()
'notin': (test) ->
sieved = siv.integer userTable, {where: {id: {notin: [1, 2, 3]}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" NOT IN (?, ?, ?)'
test.deepEqual sieved.params(), [1, 2, 3]
test.done()
'string':
'ignore if not set': (test) ->
sieved = siv.string userTable, {foo: '10'}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.string error, {foo: 'true'}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'short form':
'error passthrough when set': (test) ->
sieved = siv.string error, {where: {name: 'ann'}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.string userTable, {where: {name: 'ann'}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" = ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'long form':
'error passthrough when set': (test) ->
sieved = siv.string error, {where: {name: {equals: 'ann'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.string userTable, {where: {name: {equals: 'ann'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE name = ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'notequals': (test) ->
sieved = siv.string userTable, {where: {name: {notequals: 'ann'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE name != ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'contains': (test) ->
sieved = siv.string userTable, {where: {name: {contains: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE '%' || ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'notcontains': (test) ->
sieved = siv.string userTable, {where: {name: {notcontains: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE '%' || ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'begins': (test) ->
sieved = siv.string userTable, {where: {name: {begins: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'notbegins': (test) ->
sieved = siv.string userTable, {where: {name: {notbegins: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'ends': (test) ->
sieved = siv.string userTable, {where: {name: {ends: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE '%' || ?"
test.deepEqual sieved.params(), ['ann']
test.done()
'notends': (test) ->
sieved = siv.string userTable, {where: {name: {notends: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE '%' || ?"
test.deepEqual sieved.params(), ['ann']
test.done()
'in & notin':
'create error when not array': (test) ->
sieved = siv.string userTable, {where: {name: {in: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must be an array'}}
test.done()
'create error when empty array': (test) ->
sieved = siv.string userTable, {where: {name: {in: []}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must not be empty'}}
test.done()
'error extend': (test) ->
sieved = siv.string error, {where: {name: {in: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must be an array'}}
error: 'i am an error'
test.done()
'in': (test) ->
sieved = siv.string userTable, {where: {name: {in: ['a', 'b', 'c']}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IN (?, ?, ?)'
test.deepEqual sieved.params(), ['a', 'b', 'c']
test.done()
'notin': (test) ->
sieved = siv.string userTable, {where: {name: {notin: ['a', 'b', 'c']}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" NOT IN (?, ?, ?)'
test.deepEqual sieved.params(), ['a', 'b', 'c']
test.done()
'bool':
'ignore if not set': (test) ->
sieved = siv.boolean userTable, {foo: '10'}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not the string `true` or the string `false`': (test) ->
sieved = siv.boolean userTable, {where: {active: 'foo'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {active: 'must be either the string `true` or the string `false`'}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.boolean error, {foo: 'true'}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.boolean error, {where: {active: 'true'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.boolean error, {where: {active: 'foo'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {active: 'must be either the string `true` or the string `false`'}
error: 'i am an error'
test.done()
'set true': (test) ->
sieved = siv.boolean userTable, {where: {active: 'true'}}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "active" = ?'
test.deepEqual sieved.params(), [true]
test.done()
'set false': (test) ->
sieved = siv.boolean userTable, {where: {active: 'false'}}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "active" = ?'
test.deepEqual sieved.params(), [false]
test.done()
'date':
'ignore if not set': (test) ->
sieved = siv.date userTable, {foo: '10'}, 'created'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not parsable as a date': (test) ->
sieved = siv.date userTable, {where: {created: 'foo'}}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {created: 'cant parse a date from the string'}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.date error, {foo: 'true'}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.date error, {where: {created: 'today'}}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
# 'equals shorthand':
# 'set':
# 'yesterday': (test) ->
# sieved = siv.date userTable, {where: {created: 'yesterday'}}, 'created',
# moment('2015-04-15').toDate()
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.ok moment(params[0]).isSame(moment('2015-04-14'))
# test.done()
# 'today': (test) ->
# sieved = siv.date userTable, {where: {created: 'today'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
#
# 'tomorrow': (test) ->
# sieved = siv.date userTable, {where: {created: 'today'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
#
# '5 days ago': (test) ->
# sieved = siv.date userTable, {where: {created: '5 days ago'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
# 'error extend': (test) ->
# sieved = siv.integer error, {where: {id: 'foo'}}, 'id'
# test.ok siv.isError sieved
# test.deepEqual sieved.json,
# where: {id: 'must be parsable as an integer'}
# error: 'i am an error'
# test.done()
'all at once':
'success': (test) ->
test.done()
'error': (test) ->
# TODO produce all possible errors
test.done()
| 120591 | mesa = require 'mesa'
moment = require 'moment'
qs = require 'qs'
siv = require '../src/siv'
userTable = mesa.table('user')
error = new siv.Error {error: 'i am an error'}
module.exports =
'readme example': (test) ->
querystring = [
'limit=10',
'offset=20',
'order=name',
'asc=true',
'where[is_active]=true',
'where[email][ends]=gmail.com',
'where[email][notcontains]=fake',
'where[id][notin][]=100',
'where[id][notin][]=200',
'where[id][lt]=1000',
].join('&')
query = qs.parse(querystring)
test.deepEqual query,
limit: '10'
offset: '20'
order: 'name'
asc: 'true'
where:
is_active: 'true'
email:
ends: 'gmail.com'
notcontains: 'fake'
id:
notin: ['100', '200']
lt: '1000'
sieved = mesa.table('user')
sieved = siv.limit(sieved, query)
sieved = siv.offset(sieved, query)
sieved = siv.order(sieved, query, {allow: ['name']})
sieved = siv.boolean(sieved, query, 'is_active')
sieved = siv.string(sieved, query, 'email')
sieved = siv.integer(sieved, query, 'id')
test.ok not siv.isError sieved
test.equal sieved.sql(), [
'SELECT * FROM "user"'
'WHERE ("is_active" = ?)'
'AND email ILIKE \'%\' || ?'
'AND email NOT ILIKE \'%\' || ? || \'%\''
'AND ("id" NOT IN (?, ?))'
'AND ("id" < ?)'
'ORDER BY name ASC'
'LIMIT ?'
'OFFSET ?'
].join(' ')
test.deepEqual sieved.params(),
[true, 'gmail<EMAIL>.com', 'fake', 100, 200, 1000, 10, 20]
test.done()
'limit':
'ignore if not set': (test) ->
sieved = siv.limit userTable, qs.parse 'foo=10'
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'set': (test) ->
sieved = siv.limit userTable, qs.parse 'limit=10'
test.equal sieved.sql(), 'SELECT * FROM "user" LIMIT ?'
test.deepEqual sieved.params(), [10]
test.done()
'error create': (test) ->
sieved = siv.limit userTable, qs.parse 'limit=a'
test.ok siv.isError sieved
test.deepEqual sieved.json,
limit: 'must be an integer'
test.done()
'error passthrough when set': (test) ->
sieved = siv.limit error, qs.parse 'limit=10'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.limit error, qs.parse 'limit=a'
test.ok siv.isError sieved
test.notEqual error, sieved
test.deepEqual sieved.json,
error: 'i am an error'
limit: 'must be an integer'
test.done()
'offset':
'ignore if not set': (test) ->
sieved = siv.offset userTable, qs.parse 'foo=10'
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'set': (test) ->
sieved = siv.offset userTable, qs.parse 'offset=10'
test.equal sieved.sql(), 'SELECT * FROM "user" OFFSET ?'
test.deepEqual sieved.params(), [10]
test.done()
'error create': (test) ->
sieved = siv.offset userTable, qs.parse 'offset=a'
test.ok siv.isError sieved
test.deepEqual sieved.json,
offset: 'must be an integer'
test.done()
'error passthrough when set': (test) ->
sieved = siv.offset error, qs.parse 'offset=10'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.offset error, qs.parse 'offset=a'
test.ok siv.isError sieved
test.notEqual error, sieved
test.deepEqual sieved.json,
error: 'i am an error'
offset: 'must be an integer'
test.done()
'order':
'throw when none allowed': (test) ->
test.expect 2
try
siv.order userTable, {}
catch e
test.equal e.message, '`options.allow` must be an array with at least one element'
try
siv.order userTable, {}, {allow: []}
catch e
test.equal e.message, '`options.allow` must be an array with at least one element'
test.done()
'throw when only options.asc set': (test) ->
try
siv.order userTable, {},
allow: ['id']
asc: true
catch e
test.equal e.message, 'if `options.asc` is set then `options.order` must also be set'
test.done()
'ignored when no default and not set': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'default order': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
order: 'created_at'
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY created_at ASC'
test.deepEqual sieved.params(), []
test.done()
'default order and asc': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
order: 'created_at'
asc: false
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY created_at DESC'
test.deepEqual sieved.params(), []
test.done()
'error when blank query.order': (test) ->
sieved = siv.order userTable, qs.parse('order='),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
order: 'must not be blank if set'
test.done()
'error when not allowed': (test) ->
sieved = siv.order userTable, qs.parse('order=name'),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
order: 'ordering by this column is not allowed'
test.done()
'error when query.asc is not the string `true` or the string `false`': (test) ->
sieved = siv.order userTable, qs.parse('asc=foo'),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
asc: 'must be either the string `true` or the string `false`'
test.done()
'error when no default and only asc': (test) ->
sieved = siv.order userTable, qs.parse('asc=true'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
asc: 'if `asc` is set then `order` must also be set'
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.order error, qs.parse('foo=true'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.order error, qs.parse('order=id'),
allow: ['name', 'id']
order: 'name'
asc: true
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.order error, qs.parse('order=name'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
order: 'ordering by this column is not allowed'
test.done()
'error extend twice': (test) ->
sieved = siv.order error, qs.parse('order=name&asc=foo'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
order: 'ordering by this column is not allowed'
asc: 'must be either the string `true` or the string `false`'
test.done()
'set order': (test) ->
sieved = siv.order userTable, qs.parse('order=id'),
allow: ['name', 'id']
order: 'name'
asc: true
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY id ASC'
test.deepEqual sieved.params(), []
test.done()
'set order and asc': (test) ->
sieved = siv.order userTable, qs.parse('order=id&asc=false'),
allow: ['name', 'id']
order: 'name'
asc: true
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY id DESC'
test.deepEqual sieved.params(), []
test.done()
'nullable':
'ignore if not set': (test) ->
sieved = siv.nullable userTable, {foo: '10'}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not the string `true` or the string `false`': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {null: 'must be either the string `true` or the string `false`'}}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.nullable error, {foo: 'true'}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.nullable error, {where: {name: {null: 'true'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.nullable error, {where: {name: {null: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {null: 'must be either the string `true` or the string `false`'}}
error: 'i am an error'
test.done()
'set null': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'true'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IS NULL'
test.done()
'set not null': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'false'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IS NOT NULL'
test.done()
'integer':
'ignore if not set': (test) ->
sieved = siv.integer userTable, {foo: '10'}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.integer error, {foo: 'true'}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'short form':
'error passthrough when set': (test) ->
sieved = siv.integer error, {where: {id: '10'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error when not integer': (test) ->
sieved = siv.integer userTable, {where: {id: 'foo'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: 'must be parsable as an integer'}
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: 'foo'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: 'must be parsable as an integer'}
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.integer userTable, {where: {id: '10'}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" = ?'
test.deepEqual sieved.params(), [10]
test.done()
'long form':
'error passthrough when set': (test) ->
sieved = siv.integer error, {where: {id: {equals: '10'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'create error when not integer': (test) ->
sieved = siv.integer userTable, {where: {id: {equals: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {equals: 'must be parsable as an integer'}}
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: {equals: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {equals: 'must be parsable as an integer'}}
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.integer userTable, {where: {id: {equals: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" = ?'
test.deepEqual sieved.params(), [10]
test.done()
'notequals': (test) ->
sieved = siv.integer userTable, {where: {id: {notequals: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" != ?'
test.deepEqual sieved.params(), [10]
test.done()
'lt': (test) ->
sieved = siv.integer userTable, {where: {id: {lt: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" < ?'
test.deepEqual sieved.params(), [10]
test.done()
'lte': (test) ->
sieved = siv.integer userTable, {where: {id: {lte: '1000'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" <= ?'
test.deepEqual sieved.params(), [1000]
test.done()
'gt': (test) ->
sieved = siv.integer userTable, {where: {id: {gt: '439'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" > ?'
test.deepEqual sieved.params(), [439]
test.done()
'gte': (test) ->
sieved = siv.integer userTable, {where: {id: {gte: '9383498'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" >= ?'
test.deepEqual sieved.params(), [9383498]
test.done()
'in & notin':
'create error when not array': (test) ->
sieved = siv.integer userTable, {where: {id: {in: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must be an array'}}
test.done()
'create error when empty array': (test) ->
sieved = siv.integer userTable, {where: {id: {in: []}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must not be empty'}}
test.done()
'create error when items not parsable': (test) ->
sieved = siv.integer userTable, {where: {id: {in: ['foo', '1', '2', 'bar', '3']}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where:
id:
in:
0: 'must be parsable as an integer'
3: 'must be parsable as an integer'
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: {in: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must be an array'}}
error: 'i am an error'
test.done()
'in': (test) ->
sieved = siv.integer userTable, {where: {id: {in: [1, 2, 3]}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" IN (?, ?, ?)'
test.deepEqual sieved.params(), [1, 2, 3]
test.done()
'notin': (test) ->
sieved = siv.integer userTable, {where: {id: {notin: [1, 2, 3]}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" NOT IN (?, ?, ?)'
test.deepEqual sieved.params(), [1, 2, 3]
test.done()
'string':
'ignore if not set': (test) ->
sieved = siv.string userTable, {foo: '10'}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.string error, {foo: 'true'}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'short form':
'error passthrough when set': (test) ->
sieved = siv.string error, {where: {name: 'ann'}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.string userTable, {where: {name: 'ann'}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" = ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'long form':
'error passthrough when set': (test) ->
sieved = siv.string error, {where: {name: {equals: 'ann'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.string userTable, {where: {name: {equals: 'ann'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE name = ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'notequals': (test) ->
sieved = siv.string userTable, {where: {name: {notequals: 'ann'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE name != ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'contains': (test) ->
sieved = siv.string userTable, {where: {name: {contains: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE '%' || ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'notcontains': (test) ->
sieved = siv.string userTable, {where: {name: {notcontains: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE '%' || ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'begins': (test) ->
sieved = siv.string userTable, {where: {name: {begins: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'notbegins': (test) ->
sieved = siv.string userTable, {where: {name: {notbegins: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'ends': (test) ->
sieved = siv.string userTable, {where: {name: {ends: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE '%' || ?"
test.deepEqual sieved.params(), ['ann']
test.done()
'notends': (test) ->
sieved = siv.string userTable, {where: {name: {notends: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE '%' || ?"
test.deepEqual sieved.params(), ['ann']
test.done()
'in & notin':
'create error when not array': (test) ->
sieved = siv.string userTable, {where: {name: {in: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must be an array'}}
test.done()
'create error when empty array': (test) ->
sieved = siv.string userTable, {where: {name: {in: []}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must not be empty'}}
test.done()
'error extend': (test) ->
sieved = siv.string error, {where: {name: {in: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must be an array'}}
error: 'i am an error'
test.done()
'in': (test) ->
sieved = siv.string userTable, {where: {name: {in: ['a', 'b', 'c']}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IN (?, ?, ?)'
test.deepEqual sieved.params(), ['a', 'b', 'c']
test.done()
'notin': (test) ->
sieved = siv.string userTable, {where: {name: {notin: ['a', 'b', 'c']}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" NOT IN (?, ?, ?)'
test.deepEqual sieved.params(), ['a', 'b', 'c']
test.done()
'bool':
'ignore if not set': (test) ->
sieved = siv.boolean userTable, {foo: '10'}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not the string `true` or the string `false`': (test) ->
sieved = siv.boolean userTable, {where: {active: 'foo'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {active: 'must be either the string `true` or the string `false`'}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.boolean error, {foo: 'true'}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.boolean error, {where: {active: 'true'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.boolean error, {where: {active: 'foo'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {active: 'must be either the string `true` or the string `false`'}
error: 'i am an error'
test.done()
'set true': (test) ->
sieved = siv.boolean userTable, {where: {active: 'true'}}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "active" = ?'
test.deepEqual sieved.params(), [true]
test.done()
'set false': (test) ->
sieved = siv.boolean userTable, {where: {active: 'false'}}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "active" = ?'
test.deepEqual sieved.params(), [false]
test.done()
'date':
'ignore if not set': (test) ->
sieved = siv.date userTable, {foo: '10'}, 'created'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not parsable as a date': (test) ->
sieved = siv.date userTable, {where: {created: 'foo'}}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {created: 'cant parse a date from the string'}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.date error, {foo: 'true'}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.date error, {where: {created: 'today'}}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
# 'equals shorthand':
# 'set':
# 'yesterday': (test) ->
# sieved = siv.date userTable, {where: {created: 'yesterday'}}, 'created',
# moment('2015-04-15').toDate()
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.ok moment(params[0]).isSame(moment('2015-04-14'))
# test.done()
# 'today': (test) ->
# sieved = siv.date userTable, {where: {created: 'today'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
#
# 'tomorrow': (test) ->
# sieved = siv.date userTable, {where: {created: 'today'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
#
# '5 days ago': (test) ->
# sieved = siv.date userTable, {where: {created: '5 days ago'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
# 'error extend': (test) ->
# sieved = siv.integer error, {where: {id: 'foo'}}, 'id'
# test.ok siv.isError sieved
# test.deepEqual sieved.json,
# where: {id: 'must be parsable as an integer'}
# error: 'i am an error'
# test.done()
'all at once':
'success': (test) ->
test.done()
'error': (test) ->
# TODO produce all possible errors
test.done()
| true | mesa = require 'mesa'
moment = require 'moment'
qs = require 'qs'
siv = require '../src/siv'
userTable = mesa.table('user')
error = new siv.Error {error: 'i am an error'}
module.exports =
'readme example': (test) ->
querystring = [
'limit=10',
'offset=20',
'order=name',
'asc=true',
'where[is_active]=true',
'where[email][ends]=gmail.com',
'where[email][notcontains]=fake',
'where[id][notin][]=100',
'where[id][notin][]=200',
'where[id][lt]=1000',
].join('&')
query = qs.parse(querystring)
test.deepEqual query,
limit: '10'
offset: '20'
order: 'name'
asc: 'true'
where:
is_active: 'true'
email:
ends: 'gmail.com'
notcontains: 'fake'
id:
notin: ['100', '200']
lt: '1000'
sieved = mesa.table('user')
sieved = siv.limit(sieved, query)
sieved = siv.offset(sieved, query)
sieved = siv.order(sieved, query, {allow: ['name']})
sieved = siv.boolean(sieved, query, 'is_active')
sieved = siv.string(sieved, query, 'email')
sieved = siv.integer(sieved, query, 'id')
test.ok not siv.isError sieved
test.equal sieved.sql(), [
'SELECT * FROM "user"'
'WHERE ("is_active" = ?)'
'AND email ILIKE \'%\' || ?'
'AND email NOT ILIKE \'%\' || ? || \'%\''
'AND ("id" NOT IN (?, ?))'
'AND ("id" < ?)'
'ORDER BY name ASC'
'LIMIT ?'
'OFFSET ?'
].join(' ')
test.deepEqual sieved.params(),
[true, 'gmailPI:EMAIL:<EMAIL>END_PI.com', 'fake', 100, 200, 1000, 10, 20]
test.done()
'limit':
'ignore if not set': (test) ->
sieved = siv.limit userTable, qs.parse 'foo=10'
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'set': (test) ->
sieved = siv.limit userTable, qs.parse 'limit=10'
test.equal sieved.sql(), 'SELECT * FROM "user" LIMIT ?'
test.deepEqual sieved.params(), [10]
test.done()
'error create': (test) ->
sieved = siv.limit userTable, qs.parse 'limit=a'
test.ok siv.isError sieved
test.deepEqual sieved.json,
limit: 'must be an integer'
test.done()
'error passthrough when set': (test) ->
sieved = siv.limit error, qs.parse 'limit=10'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.limit error, qs.parse 'limit=a'
test.ok siv.isError sieved
test.notEqual error, sieved
test.deepEqual sieved.json,
error: 'i am an error'
limit: 'must be an integer'
test.done()
'offset':
'ignore if not set': (test) ->
sieved = siv.offset userTable, qs.parse 'foo=10'
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'set': (test) ->
sieved = siv.offset userTable, qs.parse 'offset=10'
test.equal sieved.sql(), 'SELECT * FROM "user" OFFSET ?'
test.deepEqual sieved.params(), [10]
test.done()
'error create': (test) ->
sieved = siv.offset userTable, qs.parse 'offset=a'
test.ok siv.isError sieved
test.deepEqual sieved.json,
offset: 'must be an integer'
test.done()
'error passthrough when set': (test) ->
sieved = siv.offset error, qs.parse 'offset=10'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.offset error, qs.parse 'offset=a'
test.ok siv.isError sieved
test.notEqual error, sieved
test.deepEqual sieved.json,
error: 'i am an error'
offset: 'must be an integer'
test.done()
'order':
'throw when none allowed': (test) ->
test.expect 2
try
siv.order userTable, {}
catch e
test.equal e.message, '`options.allow` must be an array with at least one element'
try
siv.order userTable, {}, {allow: []}
catch e
test.equal e.message, '`options.allow` must be an array with at least one element'
test.done()
'throw when only options.asc set': (test) ->
try
siv.order userTable, {},
allow: ['id']
asc: true
catch e
test.equal e.message, 'if `options.asc` is set then `options.order` must also be set'
test.done()
'ignored when no default and not set': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
test.equal sieved, userTable
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'default order': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
order: 'created_at'
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY created_at ASC'
test.deepEqual sieved.params(), []
test.done()
'default order and asc': (test) ->
sieved = siv.order userTable, qs.parse('foo=10'),
allow: ['id']
order: 'created_at'
asc: false
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY created_at DESC'
test.deepEqual sieved.params(), []
test.done()
'error when blank query.order': (test) ->
sieved = siv.order userTable, qs.parse('order='),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
order: 'must not be blank if set'
test.done()
'error when not allowed': (test) ->
sieved = siv.order userTable, qs.parse('order=name'),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
order: 'ordering by this column is not allowed'
test.done()
'error when query.asc is not the string `true` or the string `false`': (test) ->
sieved = siv.order userTable, qs.parse('asc=foo'),
allow: ['id']
order: 'created_at'
asc: false
test.ok siv.isError sieved
test.deepEqual sieved.json,
asc: 'must be either the string `true` or the string `false`'
test.done()
'error when no default and only asc': (test) ->
sieved = siv.order userTable, qs.parse('asc=true'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
asc: 'if `asc` is set then `order` must also be set'
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.order error, qs.parse('foo=true'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.order error, qs.parse('order=id'),
allow: ['name', 'id']
order: 'name'
asc: true
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.order error, qs.parse('order=name'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
order: 'ordering by this column is not allowed'
test.done()
'error extend twice': (test) ->
sieved = siv.order error, qs.parse('order=name&asc=foo'),
allow: ['id']
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
order: 'ordering by this column is not allowed'
asc: 'must be either the string `true` or the string `false`'
test.done()
'set order': (test) ->
sieved = siv.order userTable, qs.parse('order=id'),
allow: ['name', 'id']
order: 'name'
asc: true
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY id ASC'
test.deepEqual sieved.params(), []
test.done()
'set order and asc': (test) ->
sieved = siv.order userTable, qs.parse('order=id&asc=false'),
allow: ['name', 'id']
order: 'name'
asc: true
test.equal sieved.sql(), 'SELECT * FROM "user" ORDER BY id DESC'
test.deepEqual sieved.params(), []
test.done()
'nullable':
'ignore if not set': (test) ->
sieved = siv.nullable userTable, {foo: '10'}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not the string `true` or the string `false`': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {null: 'must be either the string `true` or the string `false`'}}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.nullable error, {foo: 'true'}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.nullable error, {where: {name: {null: 'true'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.nullable error, {where: {name: {null: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {null: 'must be either the string `true` or the string `false`'}}
error: 'i am an error'
test.done()
'set null': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'true'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IS NULL'
test.done()
'set not null': (test) ->
sieved = siv.nullable userTable, {where: {name: {null: 'false'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IS NOT NULL'
test.done()
'integer':
'ignore if not set': (test) ->
sieved = siv.integer userTable, {foo: '10'}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.integer error, {foo: 'true'}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'short form':
'error passthrough when set': (test) ->
sieved = siv.integer error, {where: {id: '10'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error when not integer': (test) ->
sieved = siv.integer userTable, {where: {id: 'foo'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: 'must be parsable as an integer'}
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: 'foo'}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: 'must be parsable as an integer'}
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.integer userTable, {where: {id: '10'}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" = ?'
test.deepEqual sieved.params(), [10]
test.done()
'long form':
'error passthrough when set': (test) ->
sieved = siv.integer error, {where: {id: {equals: '10'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'create error when not integer': (test) ->
sieved = siv.integer userTable, {where: {id: {equals: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {equals: 'must be parsable as an integer'}}
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: {equals: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {equals: 'must be parsable as an integer'}}
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.integer userTable, {where: {id: {equals: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" = ?'
test.deepEqual sieved.params(), [10]
test.done()
'notequals': (test) ->
sieved = siv.integer userTable, {where: {id: {notequals: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" != ?'
test.deepEqual sieved.params(), [10]
test.done()
'lt': (test) ->
sieved = siv.integer userTable, {where: {id: {lt: '10'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" < ?'
test.deepEqual sieved.params(), [10]
test.done()
'lte': (test) ->
sieved = siv.integer userTable, {where: {id: {lte: '1000'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" <= ?'
test.deepEqual sieved.params(), [1000]
test.done()
'gt': (test) ->
sieved = siv.integer userTable, {where: {id: {gt: '439'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" > ?'
test.deepEqual sieved.params(), [439]
test.done()
'gte': (test) ->
sieved = siv.integer userTable, {where: {id: {gte: '9383498'}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" >= ?'
test.deepEqual sieved.params(), [9383498]
test.done()
'in & notin':
'create error when not array': (test) ->
sieved = siv.integer userTable, {where: {id: {in: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must be an array'}}
test.done()
'create error when empty array': (test) ->
sieved = siv.integer userTable, {where: {id: {in: []}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must not be empty'}}
test.done()
'create error when items not parsable': (test) ->
sieved = siv.integer userTable, {where: {id: {in: ['foo', '1', '2', 'bar', '3']}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where:
id:
in:
0: 'must be parsable as an integer'
3: 'must be parsable as an integer'
test.done()
'error extend': (test) ->
sieved = siv.integer error, {where: {id: {in: 'foo'}}}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {id: {in: 'must be an array'}}
error: 'i am an error'
test.done()
'in': (test) ->
sieved = siv.integer userTable, {where: {id: {in: [1, 2, 3]}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" IN (?, ?, ?)'
test.deepEqual sieved.params(), [1, 2, 3]
test.done()
'notin': (test) ->
sieved = siv.integer userTable, {where: {id: {notin: [1, 2, 3]}}}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "id" NOT IN (?, ?, ?)'
test.deepEqual sieved.params(), [1, 2, 3]
test.done()
'string':
'ignore if not set': (test) ->
sieved = siv.string userTable, {foo: '10'}, 'id'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.string error, {foo: 'true'}, 'id'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'short form':
'error passthrough when set': (test) ->
sieved = siv.string error, {where: {name: 'ann'}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.string userTable, {where: {name: 'ann'}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" = ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'long form':
'error passthrough when set': (test) ->
sieved = siv.string error, {where: {name: {equals: 'ann'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'equals': (test) ->
sieved = siv.string userTable, {where: {name: {equals: 'ann'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE name = ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'notequals': (test) ->
sieved = siv.string userTable, {where: {name: {notequals: 'ann'}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE name != ?'
test.deepEqual sieved.params(), ['ann']
test.done()
'contains': (test) ->
sieved = siv.string userTable, {where: {name: {contains: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE '%' || ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'notcontains': (test) ->
sieved = siv.string userTable, {where: {name: {notcontains: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE '%' || ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'begins': (test) ->
sieved = siv.string userTable, {where: {name: {begins: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'notbegins': (test) ->
sieved = siv.string userTable, {where: {name: {notbegins: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE ? || '%'"
test.deepEqual sieved.params(), ['ann']
test.done()
'ends': (test) ->
sieved = siv.string userTable, {where: {name: {ends: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name ILIKE '%' || ?"
test.deepEqual sieved.params(), ['ann']
test.done()
'notends': (test) ->
sieved = siv.string userTable, {where: {name: {notends: 'ann'}}}, 'name'
test.equal sieved.sql(), "SELECT * FROM \"user\" WHERE name NOT ILIKE '%' || ?"
test.deepEqual sieved.params(), ['ann']
test.done()
'in & notin':
'create error when not array': (test) ->
sieved = siv.string userTable, {where: {name: {in: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must be an array'}}
test.done()
'create error when empty array': (test) ->
sieved = siv.string userTable, {where: {name: {in: []}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must not be empty'}}
test.done()
'error extend': (test) ->
sieved = siv.string error, {where: {name: {in: 'foo'}}}, 'name'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {name: {in: 'must be an array'}}
error: 'i am an error'
test.done()
'in': (test) ->
sieved = siv.string userTable, {where: {name: {in: ['a', 'b', 'c']}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" IN (?, ?, ?)'
test.deepEqual sieved.params(), ['a', 'b', 'c']
test.done()
'notin': (test) ->
sieved = siv.string userTable, {where: {name: {notin: ['a', 'b', 'c']}}}, 'name'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "name" NOT IN (?, ?, ?)'
test.deepEqual sieved.params(), ['a', 'b', 'c']
test.done()
'bool':
'ignore if not set': (test) ->
sieved = siv.boolean userTable, {foo: '10'}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not the string `true` or the string `false`': (test) ->
sieved = siv.boolean userTable, {where: {active: 'foo'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {active: 'must be either the string `true` or the string `false`'}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.boolean error, {foo: 'true'}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.boolean error, {where: {active: 'true'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error extend': (test) ->
sieved = siv.boolean error, {where: {active: 'foo'}}, 'active'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {active: 'must be either the string `true` or the string `false`'}
error: 'i am an error'
test.done()
'set true': (test) ->
sieved = siv.boolean userTable, {where: {active: 'true'}}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "active" = ?'
test.deepEqual sieved.params(), [true]
test.done()
'set false': (test) ->
sieved = siv.boolean userTable, {where: {active: 'false'}}, 'active'
test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "active" = ?'
test.deepEqual sieved.params(), [false]
test.done()
'date':
'ignore if not set': (test) ->
sieved = siv.date userTable, {foo: '10'}, 'created'
test.equal sieved.sql(), 'SELECT * FROM "user"'
test.deepEqual sieved.params(), []
test.done()
'error when not parsable as a date': (test) ->
sieved = siv.date userTable, {where: {created: 'foo'}}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
where: {created: 'cant parse a date from the string'}
test.done()
'error passthrough when ignored': (test) ->
sieved = siv.date error, {foo: 'true'}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
'error passthrough when set': (test) ->
sieved = siv.date error, {where: {created: 'today'}}, 'created'
test.ok siv.isError sieved
test.deepEqual sieved.json,
error: 'i am an error'
test.done()
# 'equals shorthand':
# 'set':
# 'yesterday': (test) ->
# sieved = siv.date userTable, {where: {created: 'yesterday'}}, 'created',
# moment('2015-04-15').toDate()
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.ok moment(params[0]).isSame(moment('2015-04-14'))
# test.done()
# 'today': (test) ->
# sieved = siv.date userTable, {where: {created: 'today'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
#
# 'tomorrow': (test) ->
# sieved = siv.date userTable, {where: {created: 'today'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
#
# '5 days ago': (test) ->
# sieved = siv.date userTable, {where: {created: '5 days ago'}}, 'created'
# test.equal sieved.sql(), 'SELECT * FROM "user" WHERE "created" = ?'
# params = sieved.params()
# test.equal params.length, 1
# console.log params
# test.done()
# 'error extend': (test) ->
# sieved = siv.integer error, {where: {id: 'foo'}}, 'id'
# test.ok siv.isError sieved
# test.deepEqual sieved.json,
# where: {id: 'must be parsable as an integer'}
# error: 'i am an error'
# test.done()
'all at once':
'success': (test) ->
test.done()
'error': (test) ->
# TODO produce all possible errors
test.done()
|
[
{
"context": " returns the latest Nashville news\n#\n# Author:\n# Stephen Yeargin <stephen.yeargin@gmail.com>\n\ncheerio = require 'c",
"end": 178,
"score": 0.9998997449874878,
"start": 163,
"tag": "NAME",
"value": "Stephen Yeargin"
},
{
"context": "t Nashville news\n#\n# Author:\n... | src/nashville-news.coffee | stephenyeargin/hubot-nashville-news | 1 | # Description
# Retrieves top local news from Nashville media outlet RSS feeds.
#
# Commands:
# hubot news - returns the latest Nashville news
#
# Author:
# Stephen Yeargin <stephen.yeargin@gmail.com>
cheerio = require 'cheerio'
_ = require 'underscore'
fs = require 'fs'
# Configure the RSS feeds
rssFeeds = require './feeds.json'
storyCount = process.env.HUBOT_NEWS_ITEM_COUNT || 3
module.exports = (robot) ->
# Use enhanced formatting?
isSlack = robot.adapterName == 'slack'
robot.respond /news$/i, (msg) ->
msg.send 'Retrieving local news (this may take a bit) ...'
promises = getAllFeeds(msg)
Promise.all(promises).then (storyLists) ->
for storyList in storyLists
postMessage storyList, msg
.catch (error) ->
msg.send error
##
# Gets a Single Feed
#
# @return Promise
getFeed = (feed) ->
return new Promise (resolve, reject) ->
storyList = []
robot.http(feed.rss_url).get() (err, res, body) ->
if err or res.statusCode != 200
# reject("Unable to retrieve feed for #{feed.name}. :cry:")
storyList.push({
title: "Unable to retrieve news for #{feed.name} :cry:",
link: feed.rss_url,
feed: feed
})
return resolve(storyList)
$ = cheerio.load(body, { ignoreWhitespace : true, xmlMode : true})
# Loop through every item
$('item').each (i, xmlItem) ->
# Peel off the top stories
if i+1 > storyCount
return
# array to hold each item being converted into an array
newsItem = []
# Loop through each child of <item>
$(xmlItem).children().each (i, xmlItem) ->
# Get the name and set the contents
newsItem[$(this)[0].name] = $(this).text()
# Hack to grab the thumbnail url
newsItem['media:thumbnail'] = $(xmlItem).children().filter('media\\:thumbnail').attr('url')
# Attach feed item to each story item
newsItem['feed'] = feed
# Add to list
storyList.push newsItem
resolve(storyList)
##
# Post Message
postMessage = (storyList, msg) ->
# Build the payload and send
if isSlack
payload = {
"text": "*#{storyList[0].feed.name}*",
"attachments": [],
"unfurl_links": false
}
robot.logger.debug storyList
_(storyList).each (attachment, i) ->
payload.attachments.push
title: attachment.title
title_link: attachment.link
thumb_url: if attachment['media:thumbnail'] then attachment['media:thumbnail'] else false
msg.send payload
else
payload = []
for story in storyList
payload.push "> #{story.title} - #{story.link}"
msg.send "**#{storyList[0].feed.name}**\n" + payload.join("\n")
##
# Gets All Feeds in a Loop
getAllFeeds = (msg) ->
promises = []
for feed, id in rssFeeds
promises.push getFeed(feed)
return promises
| 19048 | # Description
# Retrieves top local news from Nashville media outlet RSS feeds.
#
# Commands:
# hubot news - returns the latest Nashville news
#
# Author:
# <NAME> <<EMAIL>>
cheerio = require 'cheerio'
_ = require 'underscore'
fs = require 'fs'
# Configure the RSS feeds
rssFeeds = require './feeds.json'
storyCount = process.env.HUBOT_NEWS_ITEM_COUNT || 3
module.exports = (robot) ->
# Use enhanced formatting?
isSlack = robot.adapterName == 'slack'
robot.respond /news$/i, (msg) ->
msg.send 'Retrieving local news (this may take a bit) ...'
promises = getAllFeeds(msg)
Promise.all(promises).then (storyLists) ->
for storyList in storyLists
postMessage storyList, msg
.catch (error) ->
msg.send error
##
# Gets a Single Feed
#
# @return Promise
getFeed = (feed) ->
return new Promise (resolve, reject) ->
storyList = []
robot.http(feed.rss_url).get() (err, res, body) ->
if err or res.statusCode != 200
# reject("Unable to retrieve feed for #{feed.name}. :cry:")
storyList.push({
title: "Unable to retrieve news for #{feed.name} :cry:",
link: feed.rss_url,
feed: feed
})
return resolve(storyList)
$ = cheerio.load(body, { ignoreWhitespace : true, xmlMode : true})
# Loop through every item
$('item').each (i, xmlItem) ->
# Peel off the top stories
if i+1 > storyCount
return
# array to hold each item being converted into an array
newsItem = []
# Loop through each child of <item>
$(xmlItem).children().each (i, xmlItem) ->
# Get the name and set the contents
newsItem[$(this)[0].name] = $(this).text()
# Hack to grab the thumbnail url
newsItem['media:thumbnail'] = $(xmlItem).children().filter('media\\:thumbnail').attr('url')
# Attach feed item to each story item
newsItem['feed'] = feed
# Add to list
storyList.push newsItem
resolve(storyList)
##
# Post Message
postMessage = (storyList, msg) ->
# Build the payload and send
if isSlack
payload = {
"text": "*#{storyList[0].feed.name}*",
"attachments": [],
"unfurl_links": false
}
robot.logger.debug storyList
_(storyList).each (attachment, i) ->
payload.attachments.push
title: attachment.title
title_link: attachment.link
thumb_url: if attachment['media:thumbnail'] then attachment['media:thumbnail'] else false
msg.send payload
else
payload = []
for story in storyList
payload.push "> #{story.title} - #{story.link}"
msg.send "**#{storyList[0].feed.name}**\n" + payload.join("\n")
##
# Gets All Feeds in a Loop
getAllFeeds = (msg) ->
promises = []
for feed, id in rssFeeds
promises.push getFeed(feed)
return promises
| true | # Description
# Retrieves top local news from Nashville media outlet RSS feeds.
#
# Commands:
# hubot news - returns the latest Nashville news
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
cheerio = require 'cheerio'
_ = require 'underscore'
fs = require 'fs'
# Configure the RSS feeds
rssFeeds = require './feeds.json'
storyCount = process.env.HUBOT_NEWS_ITEM_COUNT || 3
module.exports = (robot) ->
# Use enhanced formatting?
isSlack = robot.adapterName == 'slack'
robot.respond /news$/i, (msg) ->
msg.send 'Retrieving local news (this may take a bit) ...'
promises = getAllFeeds(msg)
Promise.all(promises).then (storyLists) ->
for storyList in storyLists
postMessage storyList, msg
.catch (error) ->
msg.send error
##
# Gets a Single Feed
#
# @return Promise
getFeed = (feed) ->
return new Promise (resolve, reject) ->
storyList = []
robot.http(feed.rss_url).get() (err, res, body) ->
if err or res.statusCode != 200
# reject("Unable to retrieve feed for #{feed.name}. :cry:")
storyList.push({
title: "Unable to retrieve news for #{feed.name} :cry:",
link: feed.rss_url,
feed: feed
})
return resolve(storyList)
$ = cheerio.load(body, { ignoreWhitespace : true, xmlMode : true})
# Loop through every item
$('item').each (i, xmlItem) ->
# Peel off the top stories
if i+1 > storyCount
return
# array to hold each item being converted into an array
newsItem = []
# Loop through each child of <item>
$(xmlItem).children().each (i, xmlItem) ->
# Get the name and set the contents
newsItem[$(this)[0].name] = $(this).text()
# Hack to grab the thumbnail url
newsItem['media:thumbnail'] = $(xmlItem).children().filter('media\\:thumbnail').attr('url')
# Attach feed item to each story item
newsItem['feed'] = feed
# Add to list
storyList.push newsItem
resolve(storyList)
##
# Post Message
postMessage = (storyList, msg) ->
# Build the payload and send
if isSlack
payload = {
"text": "*#{storyList[0].feed.name}*",
"attachments": [],
"unfurl_links": false
}
robot.logger.debug storyList
_(storyList).each (attachment, i) ->
payload.attachments.push
title: attachment.title
title_link: attachment.link
thumb_url: if attachment['media:thumbnail'] then attachment['media:thumbnail'] else false
msg.send payload
else
payload = []
for story in storyList
payload.push "> #{story.title} - #{story.link}"
msg.send "**#{storyList[0].feed.name}**\n" + payload.join("\n")
##
# Gets All Feeds in a Loop
getAllFeeds = (msg) ->
promises = []
for feed, id in rssFeeds
promises.push getFeed(feed)
return promises
|
[
{
"context": "er.getErrorMessage(err))\n\t\telse\n\t\t\tuser.password = undefined\n\t\t\tuser.salt = undefined\n\t\t\treq.login user, (err)",
"end": 596,
"score": 0.9985404014587402,
"start": 587,
"tag": "PASSWORD",
"value": "undefined"
},
{
"context": "es.status(400).send info\n\t\t... | app/controllers/users/users.authentication.server.controller.coffee | amIwho/words | 0 | 'use strict'
_ = require('lodash')
errorHandler = require('../errors.server.controller')
mongoose = require('mongoose')
passport = require('passport')
User = mongoose.model('User')
jwt = require 'jsonwebtoken'
secret = require('../../../config/secret').localtokensecret
exports.signup = (req, res) ->
delete req.body.roles
user = new User(req.body)
user.provider = 'local'
user.displayName = user.firstName + ' ' + user.lastName
# Then save the user
user.save (err) ->
if err
return res.status(400).send(message: errorHandler.getErrorMessage(err))
else
user.password = undefined
user.salt = undefined
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
return
exports.signin = (req, res, next) ->
passport.authenticate('local-token', (err, user, info) ->
if err or !user
res.status(400).send info
else
user.password = undefined
user.salt = undefined
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
) req, res, next
return
exports.signout = (req, res) ->
req.logout()
res.redirect '/'
return
exports.oauthCallback = (strategy) ->
(req, res, next) ->
passport.authenticate(strategy, (err, user, redirectURL) ->
if err or !user
return res.redirect('/#!/signin')
req.login user, (err) ->
if err
return res.redirect('/#!/signin')
res.redirect redirectURL or '/'
return
) req, res, next
return
exports.saveOAuthUserProfile = (req, providerUserProfile, done) ->
if !req.user
# Define a search query fields
searchMainProviderIdentifierField = 'providerData.' + providerUserProfile.providerIdentifierField
searchAdditionalProviderIdentifierField = 'additionalProvidersData.' + providerUserProfile.provider + '.' + providerUserProfile.providerIdentifierField
# Define main provider search query
mainProviderSearchQuery = {}
mainProviderSearchQuery.provider = providerUserProfile.provider
mainProviderSearchQuery[searchMainProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]
# Define additional provider search query
additionalProviderSearchQuery = {}
additionalProviderSearchQuery[searchAdditionalProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]
# Define a search query to find existing user with current provider profile
searchQuery = $or: [
mainProviderSearchQuery
additionalProviderSearchQuery
]
User.findOne searchQuery, (err, user) ->
if err
return done(err)
else
if !user
possibleUsername = providerUserProfile.username or (if providerUserProfile.email then providerUserProfile.email.split('@')[0] else '')
User.findUniqueUsername possibleUsername, null, (availableUsername) ->
user = new User(
firstName: providerUserProfile.firstName
lastName: providerUserProfile.lastName
username: availableUsername
displayName: providerUserProfile.displayName
email: providerUserProfile.email
provider: providerUserProfile.provider
providerData: providerUserProfile.providerData)
# And save the user
user.save (err) ->
done err, user
return
else
return done(err, user)
return
else
# User is already logged in, join the provider data to the existing user
user = req.user
# Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured
if user.provider != providerUserProfile.provider and (!user.additionalProvidersData or !user.additionalProvidersData[providerUserProfile.provider])
# Add the provider data to the additional provider data field
if !user.additionalProvidersData
user.additionalProvidersData = {}
user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData
# Then tell mongoose that we've updated the additionalProvidersData field
user.markModified 'additionalProvidersData'
# And save the user
user.save (err) ->
done err, user, '/#!/settings/accounts'
else
return done(new Error('User is already connected using this provider'), user)
return
###*
# Remove OAuth provider
###
exports.removeOAuthProvider = (req, res, next) ->
user = req.user
provider = req.param('provider')
if user and provider
# Delete the additional provider
if user.additionalProvidersData[provider]
delete user.additionalProvidersData[provider]
# Then tell mongoose that we've updated the additionalProvidersData field
user.markModified 'additionalProvidersData'
user.save (err) ->
if err
return res.status(400).send(message: errorHandler.getErrorMessage(err))
else
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
return
| 14676 | 'use strict'
_ = require('lodash')
errorHandler = require('../errors.server.controller')
mongoose = require('mongoose')
passport = require('passport')
User = mongoose.model('User')
jwt = require 'jsonwebtoken'
secret = require('../../../config/secret').localtokensecret
exports.signup = (req, res) ->
delete req.body.roles
user = new User(req.body)
user.provider = 'local'
user.displayName = user.firstName + ' ' + user.lastName
# Then save the user
user.save (err) ->
if err
return res.status(400).send(message: errorHandler.getErrorMessage(err))
else
user.password = <PASSWORD>
user.salt = undefined
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
return
exports.signin = (req, res, next) ->
passport.authenticate('local-token', (err, user, info) ->
if err or !user
res.status(400).send info
else
user.password = <PASSWORD>
user.salt = undefined
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
) req, res, next
return
exports.signout = (req, res) ->
req.logout()
res.redirect '/'
return
exports.oauthCallback = (strategy) ->
(req, res, next) ->
passport.authenticate(strategy, (err, user, redirectURL) ->
if err or !user
return res.redirect('/#!/signin')
req.login user, (err) ->
if err
return res.redirect('/#!/signin')
res.redirect redirectURL or '/'
return
) req, res, next
return
exports.saveOAuthUserProfile = (req, providerUserProfile, done) ->
if !req.user
# Define a search query fields
searchMainProviderIdentifierField = 'providerData.' + providerUserProfile.providerIdentifierField
searchAdditionalProviderIdentifierField = 'additionalProvidersData.' + providerUserProfile.provider + '.' + providerUserProfile.providerIdentifierField
# Define main provider search query
mainProviderSearchQuery = {}
mainProviderSearchQuery.provider = providerUserProfile.provider
mainProviderSearchQuery[searchMainProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]
# Define additional provider search query
additionalProviderSearchQuery = {}
additionalProviderSearchQuery[searchAdditionalProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]
# Define a search query to find existing user with current provider profile
searchQuery = $or: [
mainProviderSearchQuery
additionalProviderSearchQuery
]
User.findOne searchQuery, (err, user) ->
if err
return done(err)
else
if !user
possibleUsername = providerUserProfile.username or (if providerUserProfile.email then providerUserProfile.email.split('@')[0] else '')
User.findUniqueUsername possibleUsername, null, (availableUsername) ->
user = new User(
firstName: providerUserProfile.firstName
lastName: providerUserProfile.lastName
username: availableUsername
displayName: providerUserProfile.displayName
email: providerUserProfile.email
provider: providerUserProfile.provider
providerData: providerUserProfile.providerData)
# And save the user
user.save (err) ->
done err, user
return
else
return done(err, user)
return
else
# User is already logged in, join the provider data to the existing user
user = req.user
# Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured
if user.provider != providerUserProfile.provider and (!user.additionalProvidersData or !user.additionalProvidersData[providerUserProfile.provider])
# Add the provider data to the additional provider data field
if !user.additionalProvidersData
user.additionalProvidersData = {}
user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData
# Then tell mongoose that we've updated the additionalProvidersData field
user.markModified 'additionalProvidersData'
# And save the user
user.save (err) ->
done err, user, '/#!/settings/accounts'
else
return done(new Error('User is already connected using this provider'), user)
return
###*
# Remove OAuth provider
###
exports.removeOAuthProvider = (req, res, next) ->
user = req.user
provider = req.param('provider')
if user and provider
# Delete the additional provider
if user.additionalProvidersData[provider]
delete user.additionalProvidersData[provider]
# Then tell mongoose that we've updated the additionalProvidersData field
user.markModified 'additionalProvidersData'
user.save (err) ->
if err
return res.status(400).send(message: errorHandler.getErrorMessage(err))
else
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
return
| true | 'use strict'
_ = require('lodash')
errorHandler = require('../errors.server.controller')
mongoose = require('mongoose')
passport = require('passport')
User = mongoose.model('User')
jwt = require 'jsonwebtoken'
secret = require('../../../config/secret').localtokensecret
exports.signup = (req, res) ->
delete req.body.roles
user = new User(req.body)
user.provider = 'local'
user.displayName = user.firstName + ' ' + user.lastName
# Then save the user
user.save (err) ->
if err
return res.status(400).send(message: errorHandler.getErrorMessage(err))
else
user.password = PI:PASSWORD:<PASSWORD>END_PI
user.salt = undefined
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
return
exports.signin = (req, res, next) ->
passport.authenticate('local-token', (err, user, info) ->
if err or !user
res.status(400).send info
else
user.password = PI:PASSWORD:<PASSWORD>END_PI
user.salt = undefined
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
) req, res, next
return
exports.signout = (req, res) ->
req.logout()
res.redirect '/'
return
exports.oauthCallback = (strategy) ->
(req, res, next) ->
passport.authenticate(strategy, (err, user, redirectURL) ->
if err or !user
return res.redirect('/#!/signin')
req.login user, (err) ->
if err
return res.redirect('/#!/signin')
res.redirect redirectURL or '/'
return
) req, res, next
return
exports.saveOAuthUserProfile = (req, providerUserProfile, done) ->
if !req.user
# Define a search query fields
searchMainProviderIdentifierField = 'providerData.' + providerUserProfile.providerIdentifierField
searchAdditionalProviderIdentifierField = 'additionalProvidersData.' + providerUserProfile.provider + '.' + providerUserProfile.providerIdentifierField
# Define main provider search query
mainProviderSearchQuery = {}
mainProviderSearchQuery.provider = providerUserProfile.provider
mainProviderSearchQuery[searchMainProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]
# Define additional provider search query
additionalProviderSearchQuery = {}
additionalProviderSearchQuery[searchAdditionalProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField]
# Define a search query to find existing user with current provider profile
searchQuery = $or: [
mainProviderSearchQuery
additionalProviderSearchQuery
]
User.findOne searchQuery, (err, user) ->
if err
return done(err)
else
if !user
possibleUsername = providerUserProfile.username or (if providerUserProfile.email then providerUserProfile.email.split('@')[0] else '')
User.findUniqueUsername possibleUsername, null, (availableUsername) ->
user = new User(
firstName: providerUserProfile.firstName
lastName: providerUserProfile.lastName
username: availableUsername
displayName: providerUserProfile.displayName
email: providerUserProfile.email
provider: providerUserProfile.provider
providerData: providerUserProfile.providerData)
# And save the user
user.save (err) ->
done err, user
return
else
return done(err, user)
return
else
# User is already logged in, join the provider data to the existing user
user = req.user
# Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured
if user.provider != providerUserProfile.provider and (!user.additionalProvidersData or !user.additionalProvidersData[providerUserProfile.provider])
# Add the provider data to the additional provider data field
if !user.additionalProvidersData
user.additionalProvidersData = {}
user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData
# Then tell mongoose that we've updated the additionalProvidersData field
user.markModified 'additionalProvidersData'
# And save the user
user.save (err) ->
done err, user, '/#!/settings/accounts'
else
return done(new Error('User is already connected using this provider'), user)
return
###*
# Remove OAuth provider
###
exports.removeOAuthProvider = (req, res, next) ->
user = req.user
provider = req.param('provider')
if user and provider
# Delete the additional provider
if user.additionalProvidersData[provider]
delete user.additionalProvidersData[provider]
# Then tell mongoose that we've updated the additionalProvidersData field
user.markModified 'additionalProvidersData'
user.save (err) ->
if err
return res.status(400).send(message: errorHandler.getErrorMessage(err))
else
req.login user, (err) ->
if err
res.status(400).send err
else
res.json user
return
return
return
|
[
{
"context": " if !@isAnonymousSelected()\n @username = @usernameEditor.getModel().getText().trim();\n @refreshError(",
"end": 3710,
"score": 0.9824296236038208,
"start": 3696,
"tag": "USERNAME",
"value": "usernameEditor"
},
{
"context": "rver.\n populateFields: (config... | lib/dialogs/ftp-dialog.coffee | morassman/atom-commander | 43 | Client = require 'ftp'
FTPFileSystem = require '../fs/ftp/ftp-filesystem'
{View, TextEditorView} = require 'atom-space-pen-views'
module.exports =
class FTPDialog extends View
constructor: ->
super();
@username = "";
@client = null;
setParentDialog: (@parentDialog) ->
@content: ->
@div class: "atom-commander-ftp-dialog", =>
# @div "New FTP Connection", {class: "heading"}
@table =>
@tbody =>
@tr =>
@td "Name", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "nameEditor", new TextEditorView(mini: true)
@tr =>
@td "URL", {class: "text-highlight", style: "width:40%"}
@td "ftp://", {outlet: "url", style: "padding-bottom: 0.5em"}
@tr =>
@td "Host", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "serverEditor", new TextEditorView(mini: true)
@tr =>
@td "Port", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "portEditor", new TextEditorView(mini: true)
@tr =>
@td "Folder", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "folderEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "checkbox", outlet: "anonymous"}
@span "Anonymous", {class: "text-highlight", style: "margin-left:5px"}
@tr =>
@td "Username", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "usernameEditor", new TextEditorView(mini: true)
@tr =>
@td "Password", {class: "text-highlight", style: "width:40%"}
@td =>
@div {class: "password"}, =>
@subview "passwordEditor", new TextEditorView(mini: true)
@tr =>
@td ""
@td "Leave empty to prompt for password", {class:"encrypted"}
@tr =>
@td =>
@input {type: "checkbox", outlet: "storeCheckBox"}
@span "Store password", {class: "text-highlight", style: "margin-left:5px"}
@td =>
@span "Passwords are encrypted", {class: "encrypted"}
@div {class: "test-button-panel"}, =>
@button "Test", {class: "btn", click: "test", outlet: "testButton"}
@div {class: "bottom-button-panel"}, =>
@button "Cancel", {class: "btn", click: "cancel", outlet: "cancelButton"}
@button "OK", {class: "btn", click: "confirm", outlet: "okButton"}
@div =>
@span {class: "loading loading-spinner-tiny inline-block", outlet: "spinner"}
@span {class: "message", outlet: "message"}
initialize: ->
@nameEditor.attr("tabindex", 1);
@serverEditor.attr("tabindex", 2);
@portEditor.attr("tabindex", 3);
@folderEditor.attr("tabindex", 4);
@anonymous.attr("tabindex", 5);
@usernameEditor.attr("tabindex", 6);
@passwordEditor.attr("tabindex", 7);
@storeCheckBox.attr("tabindex", 8);
@testButton.attr("tabindex", 9);
@okButton.attr("tabindex", 10);
@cancelButton.attr("tabindex", 11);
@passwordEditor.addClass("password-editor");
@spinner.hide();
@portEditor.getModel().setText("21");
@storeCheckBox.prop("checked", true);
@serverEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@portEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@folderEditor.getModel().onDidChange =>
@refreshURL();
@usernameEditor.getModel().onDidChange =>
if !@isAnonymousSelected()
@username = @usernameEditor.getModel().getText().trim();
@refreshError();
@passwordEditor.getModel().onDidChange =>
@refreshError();
@anonymous.change =>
@anonymousChanged();
atom.commands.add @element,
"core:confirm": => @confirm()
"core:cancel": => @cancel()
@refreshError();
# Populates the fields with an existing server's config. This is used
# when editing a server.
populateFields: (config) ->
password = config.password;
if !password?
password = "";
@nameEditor.getModel().setText(config.name);
@serverEditor.getModel().setText(config.host);
@portEditor.getModel().setText(config.port + "");
@usernameEditor.getModel().setText(config.user);
@passwordEditor.getModel().setText(password);
@folderEditor.getModel().setText(config.folder);
@anonymous.prop("checked", config.anonymous);
@storeCheckBox.prop("checked", config.storePassword);
getPort: ->
port = @portEditor.getModel().getText().trim();
if port.length == 0
return 21;
port = parseInt(port);
if isNaN(port)
return null;
return port;
anonymousChanged: ->
selected = @isAnonymousSelected();
if selected
@usernameEditor.getModel().setText("anonymous");
else
@usernameEditor.getModel().setText(@username);
@refreshError();
isAnonymousSelected: ->
return @anonymous.is(":checked");
isStoreCheckBoxSelected: ->
return @storeCheckBox.is(":checked");
getFolder: ->
folder = @folderEditor.getModel().getText().trim();
if (folder.length > 0)
if folder[0] != "/"
folder = "/"+folder;
else
folder = "/";
return folder;
refreshURL: ->
server = @serverEditor.getModel().getText().trim();
port = @portEditor.getModel().getText().trim();
url = "ftp://" + server;
if (server.length > 0)
port = @getPort();
if (port != null) and (port != 21)
url += ":" + port;
url += @getFolder();
@url.text(url);
refreshError: ->
message = @getErrorMessage();
if message != null
@showMessage(message, 2);
return;
message = @getWarningMessage();
if message != null
@showMessage(message, 1);
return;
@showMessage("", 0);
getErrorMessage: ->
server = @getServer();
if server.length == 0
return "Host must be specified."
port = @getPort();
if port == null
return "Invalid port number.";
if @serverExists(server, port, @getUsername())
return "This server has already been added.";
return null;
getWarningMessage: ->
if !@isAnonymousSelected()
if @passwordEditor.getModel().getText().trim().length == 0
return "Password not specified."
return null;
showMessage: (text, type) ->
@messageType = type;
@message.removeClass("text-error");
@message.removeClass("text-warning");
@message.removeClass("text-success");
if @messageType == 0
@message.addClass("text-success");
else if @messageType == 1
@message.addClass("text-warning");
else
@message.addClass("text-error");
@message.text(text);
serverExists: (server, port, username) ->
id = "ftp_"+server+"_"+port+"_"+username;
return @parentDialog.serverExists(id);
getName: ->
return @nameEditor.getModel().getText().trim();
getServer: ->
return @serverEditor.getModel().getText().trim();
getUsername: ->
return @usernameEditor.getModel().getText().trim();
getFTPConfig: ->
config = {};
config.protocol = "ftp";
config.name = @getName();
config.host = @getServer();
config.port = @getPort();
config.folder = @getFolder();
config.passwordDecrypted = true;
if @isAnonymousSelected()
config.anonymous = true;
config.user = @getUsername();
config.password = "anonymous@";
config.storePassword = true;
else
config.anonymous = false;
config.user = @getUsername();
config.password = @passwordEditor.getModel().getText().trim();
config.storePassword = @isStoreCheckBoxSelected();
return config;
selected: ->
@nameEditor.focus();
# attach: ->
# @panel = atom.workspace.addModalPanel(item: this.element);
# @serverEditor.focus();
# @serverEditor.getModel().scrollToCursorPosition();
close: ->
@parentDialog.close();
# panelToDestroy = @panel;
# @panel = null;
# panelToDestroy?.destroy();
# @containerView.requestFocus();
confirm: ->
if @hasError()
return;
config = @getFTPConfig();
if !config.storePassword and (config.password.length == 0)
delete config.password;
@parentDialog.addServer(config);
cancel: ->
@parentDialog.close();
hasError: ->
return @messageType == 2;
test: ->
if @hasError() or (@client != null)
return;
@client = new Client();
@client.on "ready", =>
@spinner.hide();
@showMessage("Connection successful", 0);
if @client != null
@client.end();
@client = null;
@client.on "error", (err) =>
@spinner.hide();
@showMessage("Connection failed", 1);
if @client != null
@client.end();
@client = null;
@spinner.show();
@client.connect(@getFTPConfig());
| 61832 | Client = require 'ftp'
FTPFileSystem = require '../fs/ftp/ftp-filesystem'
{View, TextEditorView} = require 'atom-space-pen-views'
module.exports =
class FTPDialog extends View
constructor: ->
super();
@username = "";
@client = null;
setParentDialog: (@parentDialog) ->
@content: ->
@div class: "atom-commander-ftp-dialog", =>
# @div "New FTP Connection", {class: "heading"}
@table =>
@tbody =>
@tr =>
@td "Name", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "nameEditor", new TextEditorView(mini: true)
@tr =>
@td "URL", {class: "text-highlight", style: "width:40%"}
@td "ftp://", {outlet: "url", style: "padding-bottom: 0.5em"}
@tr =>
@td "Host", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "serverEditor", new TextEditorView(mini: true)
@tr =>
@td "Port", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "portEditor", new TextEditorView(mini: true)
@tr =>
@td "Folder", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "folderEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "checkbox", outlet: "anonymous"}
@span "Anonymous", {class: "text-highlight", style: "margin-left:5px"}
@tr =>
@td "Username", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "usernameEditor", new TextEditorView(mini: true)
@tr =>
@td "Password", {class: "text-highlight", style: "width:40%"}
@td =>
@div {class: "password"}, =>
@subview "passwordEditor", new TextEditorView(mini: true)
@tr =>
@td ""
@td "Leave empty to prompt for password", {class:"encrypted"}
@tr =>
@td =>
@input {type: "checkbox", outlet: "storeCheckBox"}
@span "Store password", {class: "text-highlight", style: "margin-left:5px"}
@td =>
@span "Passwords are encrypted", {class: "encrypted"}
@div {class: "test-button-panel"}, =>
@button "Test", {class: "btn", click: "test", outlet: "testButton"}
@div {class: "bottom-button-panel"}, =>
@button "Cancel", {class: "btn", click: "cancel", outlet: "cancelButton"}
@button "OK", {class: "btn", click: "confirm", outlet: "okButton"}
@div =>
@span {class: "loading loading-spinner-tiny inline-block", outlet: "spinner"}
@span {class: "message", outlet: "message"}
initialize: ->
@nameEditor.attr("tabindex", 1);
@serverEditor.attr("tabindex", 2);
@portEditor.attr("tabindex", 3);
@folderEditor.attr("tabindex", 4);
@anonymous.attr("tabindex", 5);
@usernameEditor.attr("tabindex", 6);
@passwordEditor.attr("tabindex", 7);
@storeCheckBox.attr("tabindex", 8);
@testButton.attr("tabindex", 9);
@okButton.attr("tabindex", 10);
@cancelButton.attr("tabindex", 11);
@passwordEditor.addClass("password-editor");
@spinner.hide();
@portEditor.getModel().setText("21");
@storeCheckBox.prop("checked", true);
@serverEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@portEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@folderEditor.getModel().onDidChange =>
@refreshURL();
@usernameEditor.getModel().onDidChange =>
if !@isAnonymousSelected()
@username = @usernameEditor.getModel().getText().trim();
@refreshError();
@passwordEditor.getModel().onDidChange =>
@refreshError();
@anonymous.change =>
@anonymousChanged();
atom.commands.add @element,
"core:confirm": => @confirm()
"core:cancel": => @cancel()
@refreshError();
# Populates the fields with an existing server's config. This is used
# when editing a server.
populateFields: (config) ->
password = <PASSWORD>;
if !password?
password = "";
@nameEditor.getModel().setText(config.name);
@serverEditor.getModel().setText(config.host);
@portEditor.getModel().setText(config.port + "");
@usernameEditor.getModel().setText(config.user);
@passwordEditor.getModel().setText(password);
@folderEditor.getModel().setText(config.folder);
@anonymous.prop("checked", config.anonymous);
@storeCheckBox.prop("checked", config.storePassword);
getPort: ->
port = @portEditor.getModel().getText().trim();
if port.length == 0
return 21;
port = parseInt(port);
if isNaN(port)
return null;
return port;
anonymousChanged: ->
selected = @isAnonymousSelected();
if selected
@usernameEditor.getModel().setText("anonymous");
else
@usernameEditor.getModel().setText(@username);
@refreshError();
isAnonymousSelected: ->
return @anonymous.is(":checked");
isStoreCheckBoxSelected: ->
return @storeCheckBox.is(":checked");
getFolder: ->
folder = @folderEditor.getModel().getText().trim();
if (folder.length > 0)
if folder[0] != "/"
folder = "/"+folder;
else
folder = "/";
return folder;
refreshURL: ->
server = @serverEditor.getModel().getText().trim();
port = @portEditor.getModel().getText().trim();
url = "ftp://" + server;
if (server.length > 0)
port = @getPort();
if (port != null) and (port != 21)
url += ":" + port;
url += @getFolder();
@url.text(url);
refreshError: ->
message = @getErrorMessage();
if message != null
@showMessage(message, 2);
return;
message = @getWarningMessage();
if message != null
@showMessage(message, 1);
return;
@showMessage("", 0);
getErrorMessage: ->
server = @getServer();
if server.length == 0
return "Host must be specified."
port = @getPort();
if port == null
return "Invalid port number.";
if @serverExists(server, port, @getUsername())
return "This server has already been added.";
return null;
getWarningMessage: ->
if !@isAnonymousSelected()
if @passwordEditor.getModel().getText().trim().length == 0
return "Password not specified."
return null;
showMessage: (text, type) ->
@messageType = type;
@message.removeClass("text-error");
@message.removeClass("text-warning");
@message.removeClass("text-success");
if @messageType == 0
@message.addClass("text-success");
else if @messageType == 1
@message.addClass("text-warning");
else
@message.addClass("text-error");
@message.text(text);
serverExists: (server, port, username) ->
id = "ftp_"+server+"_"+port+"_"+username;
return @parentDialog.serverExists(id);
getName: ->
return @nameEditor.getModel().getText().trim();
getServer: ->
return @serverEditor.getModel().getText().trim();
getUsername: ->
return @usernameEditor.getModel().getText().trim();
getFTPConfig: ->
config = {};
config.protocol = "ftp";
config.name = @getName();
config.host = @getServer();
config.port = @getPort();
config.folder = @getFolder();
config.passwordDecrypted = true;
if @isAnonymousSelected()
config.anonymous = true;
config.user = @getUsername();
config.password = "<PASSWORD>@";
config.storePassword = true;
else
config.anonymous = false;
config.user = @getUsername();
config.password = @passwordEditor.getModel().getText().trim();
config.storePassword = @isStoreCheckBoxSelected();
return config;
selected: ->
@nameEditor.focus();
# attach: ->
# @panel = atom.workspace.addModalPanel(item: this.element);
# @serverEditor.focus();
# @serverEditor.getModel().scrollToCursorPosition();
close: ->
@parentDialog.close();
# panelToDestroy = @panel;
# @panel = null;
# panelToDestroy?.destroy();
# @containerView.requestFocus();
confirm: ->
if @hasError()
return;
config = @getFTPConfig();
if !config.storePassword and (config.password.length == 0)
delete config.password;
@parentDialog.addServer(config);
cancel: ->
@parentDialog.close();
hasError: ->
return @messageType == 2;
test: ->
if @hasError() or (@client != null)
return;
@client = new Client();
@client.on "ready", =>
@spinner.hide();
@showMessage("Connection successful", 0);
if @client != null
@client.end();
@client = null;
@client.on "error", (err) =>
@spinner.hide();
@showMessage("Connection failed", 1);
if @client != null
@client.end();
@client = null;
@spinner.show();
@client.connect(@getFTPConfig());
| true | Client = require 'ftp'
FTPFileSystem = require '../fs/ftp/ftp-filesystem'
{View, TextEditorView} = require 'atom-space-pen-views'
module.exports =
class FTPDialog extends View
constructor: ->
super();
@username = "";
@client = null;
setParentDialog: (@parentDialog) ->
@content: ->
@div class: "atom-commander-ftp-dialog", =>
# @div "New FTP Connection", {class: "heading"}
@table =>
@tbody =>
@tr =>
@td "Name", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "nameEditor", new TextEditorView(mini: true)
@tr =>
@td "URL", {class: "text-highlight", style: "width:40%"}
@td "ftp://", {outlet: "url", style: "padding-bottom: 0.5em"}
@tr =>
@td "Host", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "serverEditor", new TextEditorView(mini: true)
@tr =>
@td "Port", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "portEditor", new TextEditorView(mini: true)
@tr =>
@td "Folder", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "folderEditor", new TextEditorView(mini: true)
@tr =>
@td =>
@input {type: "checkbox", outlet: "anonymous"}
@span "Anonymous", {class: "text-highlight", style: "margin-left:5px"}
@tr =>
@td "Username", {class: "text-highlight", style: "width:40%"}
@td =>
@subview "usernameEditor", new TextEditorView(mini: true)
@tr =>
@td "Password", {class: "text-highlight", style: "width:40%"}
@td =>
@div {class: "password"}, =>
@subview "passwordEditor", new TextEditorView(mini: true)
@tr =>
@td ""
@td "Leave empty to prompt for password", {class:"encrypted"}
@tr =>
@td =>
@input {type: "checkbox", outlet: "storeCheckBox"}
@span "Store password", {class: "text-highlight", style: "margin-left:5px"}
@td =>
@span "Passwords are encrypted", {class: "encrypted"}
@div {class: "test-button-panel"}, =>
@button "Test", {class: "btn", click: "test", outlet: "testButton"}
@div {class: "bottom-button-panel"}, =>
@button "Cancel", {class: "btn", click: "cancel", outlet: "cancelButton"}
@button "OK", {class: "btn", click: "confirm", outlet: "okButton"}
@div =>
@span {class: "loading loading-spinner-tiny inline-block", outlet: "spinner"}
@span {class: "message", outlet: "message"}
initialize: ->
@nameEditor.attr("tabindex", 1);
@serverEditor.attr("tabindex", 2);
@portEditor.attr("tabindex", 3);
@folderEditor.attr("tabindex", 4);
@anonymous.attr("tabindex", 5);
@usernameEditor.attr("tabindex", 6);
@passwordEditor.attr("tabindex", 7);
@storeCheckBox.attr("tabindex", 8);
@testButton.attr("tabindex", 9);
@okButton.attr("tabindex", 10);
@cancelButton.attr("tabindex", 11);
@passwordEditor.addClass("password-editor");
@spinner.hide();
@portEditor.getModel().setText("21");
@storeCheckBox.prop("checked", true);
@serverEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@portEditor.getModel().onDidChange =>
@refreshURL();
@refreshError();
@folderEditor.getModel().onDidChange =>
@refreshURL();
@usernameEditor.getModel().onDidChange =>
if !@isAnonymousSelected()
@username = @usernameEditor.getModel().getText().trim();
@refreshError();
@passwordEditor.getModel().onDidChange =>
@refreshError();
@anonymous.change =>
@anonymousChanged();
atom.commands.add @element,
"core:confirm": => @confirm()
"core:cancel": => @cancel()
@refreshError();
# Populates the fields with an existing server's config. This is used
# when editing a server.
populateFields: (config) ->
password = PI:PASSWORD:<PASSWORD>END_PI;
if !password?
password = "";
@nameEditor.getModel().setText(config.name);
@serverEditor.getModel().setText(config.host);
@portEditor.getModel().setText(config.port + "");
@usernameEditor.getModel().setText(config.user);
@passwordEditor.getModel().setText(password);
@folderEditor.getModel().setText(config.folder);
@anonymous.prop("checked", config.anonymous);
@storeCheckBox.prop("checked", config.storePassword);
getPort: ->
port = @portEditor.getModel().getText().trim();
if port.length == 0
return 21;
port = parseInt(port);
if isNaN(port)
return null;
return port;
anonymousChanged: ->
selected = @isAnonymousSelected();
if selected
@usernameEditor.getModel().setText("anonymous");
else
@usernameEditor.getModel().setText(@username);
@refreshError();
isAnonymousSelected: ->
return @anonymous.is(":checked");
isStoreCheckBoxSelected: ->
return @storeCheckBox.is(":checked");
getFolder: ->
folder = @folderEditor.getModel().getText().trim();
if (folder.length > 0)
if folder[0] != "/"
folder = "/"+folder;
else
folder = "/";
return folder;
refreshURL: ->
server = @serverEditor.getModel().getText().trim();
port = @portEditor.getModel().getText().trim();
url = "ftp://" + server;
if (server.length > 0)
port = @getPort();
if (port != null) and (port != 21)
url += ":" + port;
url += @getFolder();
@url.text(url);
refreshError: ->
message = @getErrorMessage();
if message != null
@showMessage(message, 2);
return;
message = @getWarningMessage();
if message != null
@showMessage(message, 1);
return;
@showMessage("", 0);
getErrorMessage: ->
server = @getServer();
if server.length == 0
return "Host must be specified."
port = @getPort();
if port == null
return "Invalid port number.";
if @serverExists(server, port, @getUsername())
return "This server has already been added.";
return null;
getWarningMessage: ->
if !@isAnonymousSelected()
if @passwordEditor.getModel().getText().trim().length == 0
return "Password not specified."
return null;
showMessage: (text, type) ->
@messageType = type;
@message.removeClass("text-error");
@message.removeClass("text-warning");
@message.removeClass("text-success");
if @messageType == 0
@message.addClass("text-success");
else if @messageType == 1
@message.addClass("text-warning");
else
@message.addClass("text-error");
@message.text(text);
serverExists: (server, port, username) ->
id = "ftp_"+server+"_"+port+"_"+username;
return @parentDialog.serverExists(id);
getName: ->
return @nameEditor.getModel().getText().trim();
getServer: ->
return @serverEditor.getModel().getText().trim();
getUsername: ->
return @usernameEditor.getModel().getText().trim();
getFTPConfig: ->
config = {};
config.protocol = "ftp";
config.name = @getName();
config.host = @getServer();
config.port = @getPort();
config.folder = @getFolder();
config.passwordDecrypted = true;
if @isAnonymousSelected()
config.anonymous = true;
config.user = @getUsername();
config.password = "PI:PASSWORD:<PASSWORD>END_PI@";
config.storePassword = true;
else
config.anonymous = false;
config.user = @getUsername();
config.password = @passwordEditor.getModel().getText().trim();
config.storePassword = @isStoreCheckBoxSelected();
return config;
selected: ->
@nameEditor.focus();
# attach: ->
# @panel = atom.workspace.addModalPanel(item: this.element);
# @serverEditor.focus();
# @serverEditor.getModel().scrollToCursorPosition();
close: ->
@parentDialog.close();
# panelToDestroy = @panel;
# @panel = null;
# panelToDestroy?.destroy();
# @containerView.requestFocus();
confirm: ->
if @hasError()
return;
config = @getFTPConfig();
if !config.storePassword and (config.password.length == 0)
delete config.password;
@parentDialog.addServer(config);
cancel: ->
@parentDialog.close();
hasError: ->
return @messageType == 2;
test: ->
if @hasError() or (@client != null)
return;
@client = new Client();
@client.on "ready", =>
@spinner.hide();
@showMessage("Connection successful", 0);
if @client != null
@client.end();
@client = null;
@client.on "error", (err) =>
@spinner.hide();
@showMessage("Connection failed", 1);
if @client != null
@client.end();
@client = null;
@spinner.show();
@client.connect(@getFTPConfig());
|
[
{
"context": "###\n* @author Andrew D.Laptev <a.d.laptev@gmail.com>\n###\n\n###global describe, b",
"end": 29,
"score": 0.9998868107795715,
"start": 14,
"tag": "NAME",
"value": "Andrew D.Laptev"
},
{
"context": "###\n* @author Andrew D.Laptev <a.d.laptev@gmail.com>\n###\n\n###global ... | test/test.xecute.coffee | agsh/boobst | 16 | ###
* @author Andrew D.Laptev <a.d.laptev@gmail.com>
###
###global describe, beforeEach, afterEach, it###
assert = require 'assert'
boobst = require '../boobst'
BoobstSocket = boobst.BoobstSocket
describe 'xecute', () ->
this.timeout 15000
bs = new BoobstSocket(require './test.config')
#bs.on('debug', console.log); # uncomment for debug messages
beforeEach (done) ->
bs.connect (err) ->
throw err if err
done()
afterEach (done) ->
bs.disconnect () ->
done()
describe '#run hello world', () ->
it 'should properly gave us hello or disallowed', (done) ->
bs.xecute 'write "hello"', (err, data) ->
assert.equal err, null
assert.ok (data == 'hello' || data == 'disallowed')
done() | 14371 | ###
* @author <NAME> <<EMAIL>>
###
###global describe, beforeEach, afterEach, it###
assert = require 'assert'
boobst = require '../boobst'
BoobstSocket = boobst.BoobstSocket
describe 'xecute', () ->
this.timeout 15000
bs = new BoobstSocket(require './test.config')
#bs.on('debug', console.log); # uncomment for debug messages
beforeEach (done) ->
bs.connect (err) ->
throw err if err
done()
afterEach (done) ->
bs.disconnect () ->
done()
describe '#run hello world', () ->
it 'should properly gave us hello or disallowed', (done) ->
bs.xecute 'write "hello"', (err, data) ->
assert.equal err, null
assert.ok (data == 'hello' || data == 'disallowed')
done() | true | ###
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
###global describe, beforeEach, afterEach, it###
assert = require 'assert'
boobst = require '../boobst'
BoobstSocket = boobst.BoobstSocket
describe 'xecute', () ->
this.timeout 15000
bs = new BoobstSocket(require './test.config')
#bs.on('debug', console.log); # uncomment for debug messages
beforeEach (done) ->
bs.connect (err) ->
throw err if err
done()
afterEach (done) ->
bs.disconnect () ->
done()
describe '#run hello world', () ->
it 'should properly gave us hello or disallowed', (done) ->
bs.xecute 'write "hello"', (err, data) ->
assert.equal err, null
assert.ok (data == 'hello' || data == 'disallowed')
done() |
[
{
"context": "###\n\tCopyright 2013 David Pearson.\n\tBSD License.\n###\n\ngelim=require(\"./gelim\").geli",
"end": 33,
"score": 0.9998504519462585,
"start": 20,
"tag": "NAME",
"value": "David Pearson"
}
] | src/solve.coffee | dpearson/linalgebra | 1 | ###
Copyright 2013 David Pearson.
BSD License.
###
gelim=require("./gelim").gelim
# Performs back substitution on an augmented matrix to solve a system
# of linear equations
#
# a - The augmented matrix
#
# Example:
# backsub [[1, 0, 0, 2], [0, 1, 0, 3.0000000000000004],
# [0, 0, 1, -0.9999999999999999]]
# => [2, 3.0000000000000004, -0.9999999999999999]
#
# Returns an array of solution values in the format [x0...xn]
backsub=(a) ->
vals=[]
width=a[0].length-1
i=a.length-1
while i>=0
j=width-1
val=a[i][width]
while j>i
val-=a[i][j]*vals[j]
j--
val/=a[i][i]
vals[i]=val
i--
vals
# Solves a system of linear equations
#
# a - The augmented matrix representing the system to solve
#
# Example:
# solve [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]]
# => [2, 3.0000000000000004, -0.9999999999999999]
#
# Returns an array of solution values in the format [x0...xn]
solve=(a) ->
red=gelim a
vals=backsub red
exports.backsub=backsub
exports.solve=solve | 177758 | ###
Copyright 2013 <NAME>.
BSD License.
###
gelim=require("./gelim").gelim
# Performs back substitution on an augmented matrix to solve a system
# of linear equations
#
# a - The augmented matrix
#
# Example:
# backsub [[1, 0, 0, 2], [0, 1, 0, 3.0000000000000004],
# [0, 0, 1, -0.9999999999999999]]
# => [2, 3.0000000000000004, -0.9999999999999999]
#
# Returns an array of solution values in the format [x0...xn]
backsub=(a) ->
vals=[]
width=a[0].length-1
i=a.length-1
while i>=0
j=width-1
val=a[i][width]
while j>i
val-=a[i][j]*vals[j]
j--
val/=a[i][i]
vals[i]=val
i--
vals
# Solves a system of linear equations
#
# a - The augmented matrix representing the system to solve
#
# Example:
# solve [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]]
# => [2, 3.0000000000000004, -0.9999999999999999]
#
# Returns an array of solution values in the format [x0...xn]
solve=(a) ->
red=gelim a
vals=backsub red
exports.backsub=backsub
exports.solve=solve | true | ###
Copyright 2013 PI:NAME:<NAME>END_PI.
BSD License.
###
gelim=require("./gelim").gelim
# Performs back substitution on an augmented matrix to solve a system
# of linear equations
#
# a - The augmented matrix
#
# Example:
# backsub [[1, 0, 0, 2], [0, 1, 0, 3.0000000000000004],
# [0, 0, 1, -0.9999999999999999]]
# => [2, 3.0000000000000004, -0.9999999999999999]
#
# Returns an array of solution values in the format [x0...xn]
backsub=(a) ->
vals=[]
width=a[0].length-1
i=a.length-1
while i>=0
j=width-1
val=a[i][width]
while j>i
val-=a[i][j]*vals[j]
j--
val/=a[i][i]
vals[i]=val
i--
vals
# Solves a system of linear equations
#
# a - The augmented matrix representing the system to solve
#
# Example:
# solve [[2, 1, -1, 8], [-3, -1, 2, -11], [-2, 1, 2, -3]]
# => [2, 3.0000000000000004, -0.9999999999999999]
#
# Returns an array of solution values in the format [x0...xn]
solve=(a) ->
red=gelim a
vals=backsub red
exports.backsub=backsub
exports.solve=solve |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.