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": "application/x-www-form-urlencoded'\n username: client.id\n password: client.secret\n data = {}\n i",
"end": 729,
"score": 0.9988269805908203,
"start": 720,
"tag": "USERNAME",
"value": "client.id"
},
{
"context": "encoded'\n username: client.id\n ... | index.coffee | twhtanghk/oauth2_client | 0 | _ = require 'lodash'
Promise = require 'bluebird'
needle = Promise.promisifyAll require 'needle'
module.exports =
# 1. get token for Resource Owner Password Credentials Grant
# url: authorization server url to get token
# client:
# id: registered client id
# secret: client secret
# user:
# id: registered user id
# secret: user password
# scope: [ "User", "Mobile"]
# 2. get token for Client Credentials Grant
# url: authroization server url to get token
# client:
# id: registered client id
# secret: client secret
token: (url, client, user = null, scope = null) ->
opts =
'Content-Type': 'application/x-www-form-urlencoded'
username: client.id
password: client.secret
data = {}
if user?
data =
grant_type: 'password'
username: user.id
password: user.secret
scope: scope.join(' ')
else
data =
grant_type: 'client_credentials'
needle
.postAsync url, data, opts
.then (res) ->
res.body.access_token
# verify specified token
# url: authorization server url to verify token
# scope: required scope
# token: token to be verified
# return: promise to resolve token details
verify: (url, scope, token) ->
opts =
headers:
Authorization: "Bearer #{token}"
needle
.getAsync url, opts
.then (res) ->
if res.statusCode != 200
return Promise.reject res.body
authScope = res.body.scope.split ' '
result = _.intersection scope, authScope
if result.length != scope.length
Promise.reject "Unathorizated access to #{scope}"
res.body
| 21280 | _ = require 'lodash'
Promise = require 'bluebird'
needle = Promise.promisifyAll require 'needle'
module.exports =
# 1. get token for Resource Owner Password Credentials Grant
# url: authorization server url to get token
# client:
# id: registered client id
# secret: client secret
# user:
# id: registered user id
# secret: user password
# scope: [ "User", "Mobile"]
# 2. get token for Client Credentials Grant
# url: authroization server url to get token
# client:
# id: registered client id
# secret: client secret
token: (url, client, user = null, scope = null) ->
opts =
'Content-Type': 'application/x-www-form-urlencoded'
username: client.id
password: <PASSWORD>
data = {}
if user?
data =
grant_type: 'password'
username: user.id
password: <PASSWORD>
scope: scope.join(' ')
else
data =
grant_type: 'client_credentials'
needle
.postAsync url, data, opts
.then (res) ->
res.body.access_token
# verify specified token
# url: authorization server url to verify token
# scope: required scope
# token: token to be verified
# return: promise to resolve token details
verify: (url, scope, token) ->
opts =
headers:
Authorization: "Bearer #{token}"
needle
.getAsync url, opts
.then (res) ->
if res.statusCode != 200
return Promise.reject res.body
authScope = res.body.scope.split ' '
result = _.intersection scope, authScope
if result.length != scope.length
Promise.reject "Unathorizated access to #{scope}"
res.body
| true | _ = require 'lodash'
Promise = require 'bluebird'
needle = Promise.promisifyAll require 'needle'
module.exports =
# 1. get token for Resource Owner Password Credentials Grant
# url: authorization server url to get token
# client:
# id: registered client id
# secret: client secret
# user:
# id: registered user id
# secret: user password
# scope: [ "User", "Mobile"]
# 2. get token for Client Credentials Grant
# url: authroization server url to get token
# client:
# id: registered client id
# secret: client secret
token: (url, client, user = null, scope = null) ->
opts =
'Content-Type': 'application/x-www-form-urlencoded'
username: client.id
password: PI:PASSWORD:<PASSWORD>END_PI
data = {}
if user?
data =
grant_type: 'password'
username: user.id
password: PI:PASSWORD:<PASSWORD>END_PI
scope: scope.join(' ')
else
data =
grant_type: 'client_credentials'
needle
.postAsync url, data, opts
.then (res) ->
res.body.access_token
# verify specified token
# url: authorization server url to verify token
# scope: required scope
# token: token to be verified
# return: promise to resolve token details
verify: (url, scope, token) ->
opts =
headers:
Authorization: "Bearer #{token}"
needle
.getAsync url, opts
.then (res) ->
if res.statusCode != 200
return Promise.reject res.body
authScope = res.body.scope.split ' '
result = _.intersection scope, authScope
if result.length != scope.length
Promise.reject "Unathorizated access to #{scope}"
res.body
|
[
{
"context": "config.user || \"default\"\n CargoOptions.password = config.password if typeof(config.password) is \"string\"\n ",
"end": 1104,
"score": 0.5977954864501953,
"start": 1098,
"tag": "PASSWORD",
"value": "config"
}
] | src/index.coffee | yi/node-clickhouse-cargo | 6 |
assert = require "assert"
path = require "path"
os = require "os"
fs = require "fs"
http = require ('http')
https = require('https')
cluster = require('cluster')
{ cargoOptionToHttpOption } = require "./utils"
#{eachSeries} = require "async"
CLUSTER_WORKER_ID = if cluster.isMaster then "nocluster" else cluster.worker.id
debuglog = require("debug")("chcargo:index@#{CLUSTER_WORKER_ID}")
Cargo = require "./cargo"
REG_INVALID_SQL_TABLE_NAME_CHAR = /[^\w\d\.\-_]/i
TABLE_NAME_TO_CARGO = {}
CargoOptions = {}
# @param Object config:
# .pathToCargoFolder
# .maxTime
# .maxRows
# .commitInterval
init = (config)->
# config could be simply a string of clickhouse server host
config = host:config if typeof(config) is "string"
assert config and config.host, "missing host in config"
#config = Object.assign({}, config) # leave input obj unmodified
CargoOptions.host = config.host
CargoOptions.port = parseInt(config.port) || 8123
CargoOptions.user = config.user || "default"
CargoOptions.password = config.password if typeof(config.password) is "string"
CargoOptions.vehicle = if String(config.protocol || '').toLowerCase() is 'https:' then https else http
CargoOptions.timeout = config.timeout if config.timeout > 0 and Number.isInteger(config.timeout)
# prepare disk path
CargoOptions.pathToCargoFolder = path.resolve(process.cwd(), config.cargoPath || "cargo_files")
delete config.cargoPath
# verify cargo can write to the destination folder
fs.accessSync(CargoOptions.pathToCargoFolder, fs.constants.W_OK) #, "Cargo not able to write to folder #{CargoOptions.pathToCargoFolder}"
fs.stat CargoOptions.pathToCargoFolder, (err, stats)->
assert not err?, "Fail to read directory stats. Due to #{err}"
assert stats.isDirectory(), "Not a directory: #{CargoOptions.pathToCargoFolder}"
return
maxTime = parseInt(config.maxTime)
CargoOptions.maxTime = maxTime if maxTime > 0
delete config.maxTime
maxRows = parseInt(config.maxRows)
CargoOptions.maxRows = maxRows if maxRows > 0
delete config.maxRows
commitInterval = parseInt(config.commitInterval)
CargoOptions.commitInterval = commitInterval if commitInterval > 0
delete config.commitInterval
maxInsetParts = parseInt(config.maxInsetParts)
CargoOptions.maxInsetParts = maxInsetParts if maxInsetParts > 0
delete config.maxInsetParts
#debuglog "[init] CargoOptions:", CargoOptions
isToFlushBeforeCrash = if config.saveWhenCrash is false then false else true
#debuglog "[init] config.saveWhenCrash:#{config.saveWhenCrash}, isToFlushBeforeCrash:", isToFlushBeforeCrash
delete config.saveWhenCrash
# pin the given ClickHouse server
CargoOptions.vehicle.get(cargoOptionToHttpOption(CargoOptions), ((res)->
#debuglog "[index] res:", res and res.headers and res.headers['x-clickhouse-summary']
assert res and (res.statusCode is 200), "FAILED to pin ClickHouse server. Server response unexpected status code:#{res and res.statusCode}"
)).on 'error', (err)->
debuglog "FAILED to pin ClickHouse server, error:", err
throw(err)
return
if isToFlushBeforeCrash
# flush in-memroy data when process crash
process.on 'uncaughtException', (err)->
debuglog "⚠️⚠️⚠️ [flushSyncInMemoryCargo] ⚠️⚠️⚠️ "
for tableName, cargo of TABLE_NAME_TO_CARGO
cargo.flushSync()
throw err
return
# https://pm2.keymetrics.io/docs/usage/signals-clean-restart/
process.on 'SIGINT', ->
console.log "⚠️⚠️⚠️ [PM2 STOP SIGNAL] ⚠️⚠️⚠️ "
for tableName, cargo of TABLE_NAME_TO_CARGO
cargo.flushSync()
setImmediate((-> process.exit() ))
return
return
# Create a cargo instance.
# Cargos are bind to table. Call create multiple times with the same table name, will result in one shared cargo.
# @param tableName String, the name of ClickHouse table which data is inserted
createCargo = (tableName)->
debuglog "[createCargo] tableName:#{tableName}"
assert CargoOptions.host and CargoOptions.vehicle, "ClickHouse-Cargo needs to be inited first"
tableName = String(tableName || "").trim()
assert tableName and not REG_INVALID_SQL_TABLE_NAME_CHAR.test(tableName), "invalid tableName:#{tableName}"
cargo = TABLE_NAME_TO_CARGO[tableName]
if cargo
debuglog "[createCargo] reuse cargo@#{tableName}:", cargo.toString()
return cargo
cargo = new Cargo(tableName, CargoOptions)
TABLE_NAME_TO_CARGO[tableName] = cargo
debuglog "[createCargo] cargo@#{tableName}:", cargo.toString()
return cargo
examOneCargo = (cargo)->
try
examStartAt = Date.now()
await cargo.exam() # one-by-one
#debuglog "[examCargos] #{cargo.tableName} takes: #{diff}ms" if (diff = Date.now() - examStartAt) > 5
msSpent = Date.now() - examStartAt
debuglog "[examOneCargo] #{cargo.tableName} takes: #{msSpent}ms" if msSpent > 100
catch err
debuglog "[examOneCargo] #{cargo.tableName} FAILED error:", err
return
examCargos = ->
#debuglog "[examCargos]"
routineStartAt = Date.now()
#await eachSeries(TABLE_NAME_TO_CARGO, examOneCargo)
for tableName, cargo of TABLE_NAME_TO_CARGO
await examOneCargo(cargo)
msSpent = Date.now() - routineStartAt
debuglog "[examCargos] rountine takes #{msSpent}ms" if msSpent > 100
# sleep till next seconds
await new Promise((resolve)=> setTimeout(resolve, 1000 - msSpent)) if msSpent < 1000
setImmediate((-> await examCargos()))
return
## static init
# NOTE: with env:CLICKHOUSE_CARGO_PROFILE, try init automatically
if process.env.CLICKHOUSE_CARGO_PROFILE
profileName = process.env.CLICKHOUSE_CARGO_PROFILE
profileName += ".json" unless path.extname(profileName) is ".json"
pathToConfig = path.join(os.homedir(), ".clickhouse-cargo", process.env.CLICKHOUSE_CARGO_PROFILE + ".json")
debuglog "[static init] try auto init from CLICKHOUSE_CARGO_PROFILE"
try
profileConfig = JSON.parse(fs.readFileSync(pathToConfig))
catch err
debuglog "[static init] FAILED error:", err
init(profileConfig)
# self examination routine
setTimeout((-> await examCargos()), 100)
# examCargos()
module.exports =
init : init
createCargo : createCargo
isInited : -> return not not (CargoOptions and CargoOptions.host)
| 190940 |
assert = require "assert"
path = require "path"
os = require "os"
fs = require "fs"
http = require ('http')
https = require('https')
cluster = require('cluster')
{ cargoOptionToHttpOption } = require "./utils"
#{eachSeries} = require "async"
CLUSTER_WORKER_ID = if cluster.isMaster then "nocluster" else cluster.worker.id
debuglog = require("debug")("chcargo:index@#{CLUSTER_WORKER_ID}")
Cargo = require "./cargo"
REG_INVALID_SQL_TABLE_NAME_CHAR = /[^\w\d\.\-_]/i
TABLE_NAME_TO_CARGO = {}
CargoOptions = {}
# @param Object config:
# .pathToCargoFolder
# .maxTime
# .maxRows
# .commitInterval
init = (config)->
# config could be simply a string of clickhouse server host
config = host:config if typeof(config) is "string"
assert config and config.host, "missing host in config"
#config = Object.assign({}, config) # leave input obj unmodified
CargoOptions.host = config.host
CargoOptions.port = parseInt(config.port) || 8123
CargoOptions.user = config.user || "default"
CargoOptions.password = <PASSWORD>.password if typeof(config.password) is "string"
CargoOptions.vehicle = if String(config.protocol || '').toLowerCase() is 'https:' then https else http
CargoOptions.timeout = config.timeout if config.timeout > 0 and Number.isInteger(config.timeout)
# prepare disk path
CargoOptions.pathToCargoFolder = path.resolve(process.cwd(), config.cargoPath || "cargo_files")
delete config.cargoPath
# verify cargo can write to the destination folder
fs.accessSync(CargoOptions.pathToCargoFolder, fs.constants.W_OK) #, "Cargo not able to write to folder #{CargoOptions.pathToCargoFolder}"
fs.stat CargoOptions.pathToCargoFolder, (err, stats)->
assert not err?, "Fail to read directory stats. Due to #{err}"
assert stats.isDirectory(), "Not a directory: #{CargoOptions.pathToCargoFolder}"
return
maxTime = parseInt(config.maxTime)
CargoOptions.maxTime = maxTime if maxTime > 0
delete config.maxTime
maxRows = parseInt(config.maxRows)
CargoOptions.maxRows = maxRows if maxRows > 0
delete config.maxRows
commitInterval = parseInt(config.commitInterval)
CargoOptions.commitInterval = commitInterval if commitInterval > 0
delete config.commitInterval
maxInsetParts = parseInt(config.maxInsetParts)
CargoOptions.maxInsetParts = maxInsetParts if maxInsetParts > 0
delete config.maxInsetParts
#debuglog "[init] CargoOptions:", CargoOptions
isToFlushBeforeCrash = if config.saveWhenCrash is false then false else true
#debuglog "[init] config.saveWhenCrash:#{config.saveWhenCrash}, isToFlushBeforeCrash:", isToFlushBeforeCrash
delete config.saveWhenCrash
# pin the given ClickHouse server
CargoOptions.vehicle.get(cargoOptionToHttpOption(CargoOptions), ((res)->
#debuglog "[index] res:", res and res.headers and res.headers['x-clickhouse-summary']
assert res and (res.statusCode is 200), "FAILED to pin ClickHouse server. Server response unexpected status code:#{res and res.statusCode}"
)).on 'error', (err)->
debuglog "FAILED to pin ClickHouse server, error:", err
throw(err)
return
if isToFlushBeforeCrash
# flush in-memroy data when process crash
process.on 'uncaughtException', (err)->
debuglog "⚠️⚠️⚠️ [flushSyncInMemoryCargo] ⚠️⚠️⚠️ "
for tableName, cargo of TABLE_NAME_TO_CARGO
cargo.flushSync()
throw err
return
# https://pm2.keymetrics.io/docs/usage/signals-clean-restart/
process.on 'SIGINT', ->
console.log "⚠️⚠️⚠️ [PM2 STOP SIGNAL] ⚠️⚠️⚠️ "
for tableName, cargo of TABLE_NAME_TO_CARGO
cargo.flushSync()
setImmediate((-> process.exit() ))
return
return
# Create a cargo instance.
# Cargos are bind to table. Call create multiple times with the same table name, will result in one shared cargo.
# @param tableName String, the name of ClickHouse table which data is inserted
createCargo = (tableName)->
debuglog "[createCargo] tableName:#{tableName}"
assert CargoOptions.host and CargoOptions.vehicle, "ClickHouse-Cargo needs to be inited first"
tableName = String(tableName || "").trim()
assert tableName and not REG_INVALID_SQL_TABLE_NAME_CHAR.test(tableName), "invalid tableName:#{tableName}"
cargo = TABLE_NAME_TO_CARGO[tableName]
if cargo
debuglog "[createCargo] reuse cargo@#{tableName}:", cargo.toString()
return cargo
cargo = new Cargo(tableName, CargoOptions)
TABLE_NAME_TO_CARGO[tableName] = cargo
debuglog "[createCargo] cargo@#{tableName}:", cargo.toString()
return cargo
examOneCargo = (cargo)->
try
examStartAt = Date.now()
await cargo.exam() # one-by-one
#debuglog "[examCargos] #{cargo.tableName} takes: #{diff}ms" if (diff = Date.now() - examStartAt) > 5
msSpent = Date.now() - examStartAt
debuglog "[examOneCargo] #{cargo.tableName} takes: #{msSpent}ms" if msSpent > 100
catch err
debuglog "[examOneCargo] #{cargo.tableName} FAILED error:", err
return
examCargos = ->
#debuglog "[examCargos]"
routineStartAt = Date.now()
#await eachSeries(TABLE_NAME_TO_CARGO, examOneCargo)
for tableName, cargo of TABLE_NAME_TO_CARGO
await examOneCargo(cargo)
msSpent = Date.now() - routineStartAt
debuglog "[examCargos] rountine takes #{msSpent}ms" if msSpent > 100
# sleep till next seconds
await new Promise((resolve)=> setTimeout(resolve, 1000 - msSpent)) if msSpent < 1000
setImmediate((-> await examCargos()))
return
## static init
# NOTE: with env:CLICKHOUSE_CARGO_PROFILE, try init automatically
if process.env.CLICKHOUSE_CARGO_PROFILE
profileName = process.env.CLICKHOUSE_CARGO_PROFILE
profileName += ".json" unless path.extname(profileName) is ".json"
pathToConfig = path.join(os.homedir(), ".clickhouse-cargo", process.env.CLICKHOUSE_CARGO_PROFILE + ".json")
debuglog "[static init] try auto init from CLICKHOUSE_CARGO_PROFILE"
try
profileConfig = JSON.parse(fs.readFileSync(pathToConfig))
catch err
debuglog "[static init] FAILED error:", err
init(profileConfig)
# self examination routine
setTimeout((-> await examCargos()), 100)
# examCargos()
module.exports =
init : init
createCargo : createCargo
isInited : -> return not not (CargoOptions and CargoOptions.host)
| true |
assert = require "assert"
path = require "path"
os = require "os"
fs = require "fs"
http = require ('http')
https = require('https')
cluster = require('cluster')
{ cargoOptionToHttpOption } = require "./utils"
#{eachSeries} = require "async"
CLUSTER_WORKER_ID = if cluster.isMaster then "nocluster" else cluster.worker.id
debuglog = require("debug")("chcargo:index@#{CLUSTER_WORKER_ID}")
Cargo = require "./cargo"
REG_INVALID_SQL_TABLE_NAME_CHAR = /[^\w\d\.\-_]/i
TABLE_NAME_TO_CARGO = {}
CargoOptions = {}
# @param Object config:
# .pathToCargoFolder
# .maxTime
# .maxRows
# .commitInterval
init = (config)->
# config could be simply a string of clickhouse server host
config = host:config if typeof(config) is "string"
assert config and config.host, "missing host in config"
#config = Object.assign({}, config) # leave input obj unmodified
CargoOptions.host = config.host
CargoOptions.port = parseInt(config.port) || 8123
CargoOptions.user = config.user || "default"
CargoOptions.password = PI:PASSWORD:<PASSWORD>END_PI.password if typeof(config.password) is "string"
CargoOptions.vehicle = if String(config.protocol || '').toLowerCase() is 'https:' then https else http
CargoOptions.timeout = config.timeout if config.timeout > 0 and Number.isInteger(config.timeout)
# prepare disk path
CargoOptions.pathToCargoFolder = path.resolve(process.cwd(), config.cargoPath || "cargo_files")
delete config.cargoPath
# verify cargo can write to the destination folder
fs.accessSync(CargoOptions.pathToCargoFolder, fs.constants.W_OK) #, "Cargo not able to write to folder #{CargoOptions.pathToCargoFolder}"
fs.stat CargoOptions.pathToCargoFolder, (err, stats)->
assert not err?, "Fail to read directory stats. Due to #{err}"
assert stats.isDirectory(), "Not a directory: #{CargoOptions.pathToCargoFolder}"
return
maxTime = parseInt(config.maxTime)
CargoOptions.maxTime = maxTime if maxTime > 0
delete config.maxTime
maxRows = parseInt(config.maxRows)
CargoOptions.maxRows = maxRows if maxRows > 0
delete config.maxRows
commitInterval = parseInt(config.commitInterval)
CargoOptions.commitInterval = commitInterval if commitInterval > 0
delete config.commitInterval
maxInsetParts = parseInt(config.maxInsetParts)
CargoOptions.maxInsetParts = maxInsetParts if maxInsetParts > 0
delete config.maxInsetParts
#debuglog "[init] CargoOptions:", CargoOptions
isToFlushBeforeCrash = if config.saveWhenCrash is false then false else true
#debuglog "[init] config.saveWhenCrash:#{config.saveWhenCrash}, isToFlushBeforeCrash:", isToFlushBeforeCrash
delete config.saveWhenCrash
# pin the given ClickHouse server
CargoOptions.vehicle.get(cargoOptionToHttpOption(CargoOptions), ((res)->
#debuglog "[index] res:", res and res.headers and res.headers['x-clickhouse-summary']
assert res and (res.statusCode is 200), "FAILED to pin ClickHouse server. Server response unexpected status code:#{res and res.statusCode}"
)).on 'error', (err)->
debuglog "FAILED to pin ClickHouse server, error:", err
throw(err)
return
if isToFlushBeforeCrash
# flush in-memroy data when process crash
process.on 'uncaughtException', (err)->
debuglog "⚠️⚠️⚠️ [flushSyncInMemoryCargo] ⚠️⚠️⚠️ "
for tableName, cargo of TABLE_NAME_TO_CARGO
cargo.flushSync()
throw err
return
# https://pm2.keymetrics.io/docs/usage/signals-clean-restart/
process.on 'SIGINT', ->
console.log "⚠️⚠️⚠️ [PM2 STOP SIGNAL] ⚠️⚠️⚠️ "
for tableName, cargo of TABLE_NAME_TO_CARGO
cargo.flushSync()
setImmediate((-> process.exit() ))
return
return
# Create a cargo instance.
# Cargos are bind to table. Call create multiple times with the same table name, will result in one shared cargo.
# @param tableName String, the name of ClickHouse table which data is inserted
createCargo = (tableName)->
debuglog "[createCargo] tableName:#{tableName}"
assert CargoOptions.host and CargoOptions.vehicle, "ClickHouse-Cargo needs to be inited first"
tableName = String(tableName || "").trim()
assert tableName and not REG_INVALID_SQL_TABLE_NAME_CHAR.test(tableName), "invalid tableName:#{tableName}"
cargo = TABLE_NAME_TO_CARGO[tableName]
if cargo
debuglog "[createCargo] reuse cargo@#{tableName}:", cargo.toString()
return cargo
cargo = new Cargo(tableName, CargoOptions)
TABLE_NAME_TO_CARGO[tableName] = cargo
debuglog "[createCargo] cargo@#{tableName}:", cargo.toString()
return cargo
examOneCargo = (cargo)->
try
examStartAt = Date.now()
await cargo.exam() # one-by-one
#debuglog "[examCargos] #{cargo.tableName} takes: #{diff}ms" if (diff = Date.now() - examStartAt) > 5
msSpent = Date.now() - examStartAt
debuglog "[examOneCargo] #{cargo.tableName} takes: #{msSpent}ms" if msSpent > 100
catch err
debuglog "[examOneCargo] #{cargo.tableName} FAILED error:", err
return
examCargos = ->
#debuglog "[examCargos]"
routineStartAt = Date.now()
#await eachSeries(TABLE_NAME_TO_CARGO, examOneCargo)
for tableName, cargo of TABLE_NAME_TO_CARGO
await examOneCargo(cargo)
msSpent = Date.now() - routineStartAt
debuglog "[examCargos] rountine takes #{msSpent}ms" if msSpent > 100
# sleep till next seconds
await new Promise((resolve)=> setTimeout(resolve, 1000 - msSpent)) if msSpent < 1000
setImmediate((-> await examCargos()))
return
## static init
# NOTE: with env:CLICKHOUSE_CARGO_PROFILE, try init automatically
if process.env.CLICKHOUSE_CARGO_PROFILE
profileName = process.env.CLICKHOUSE_CARGO_PROFILE
profileName += ".json" unless path.extname(profileName) is ".json"
pathToConfig = path.join(os.homedir(), ".clickhouse-cargo", process.env.CLICKHOUSE_CARGO_PROFILE + ".json")
debuglog "[static init] try auto init from CLICKHOUSE_CARGO_PROFILE"
try
profileConfig = JSON.parse(fs.readFileSync(pathToConfig))
catch err
debuglog "[static init] FAILED error:", err
init(profileConfig)
# self examination routine
setTimeout((-> await examCargos()), 100)
# examCargos()
module.exports =
init : init
createCargo : createCargo
isInited : -> return not not (CargoOptions and CargoOptions.host)
|
[
{
"context": "<command> <text> - Trigger webhook\n#\n# Author:\n# Tatsuhiko Miyagawa <miyagawa@bulknews.net>\n#\nQs = require 'qs'\ncrypt",
"end": 264,
"score": 0.999862790107727,
"start": 246,
"tag": "NAME",
"value": "Tatsuhiko Miyagawa"
},
{
"context": "igger webhook\n#\n# Author... | node_modules/hubot-webhook/src/scripts/webhook.coffee | Viper702/riley-reid | 0 | # Descriptipn
# Generic Webhook plugin for Hubot
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_WEBHOOK_COMMANDS
# HUBOT_WEBHOOK_URL
# HUBOT_WEBHOOK_PARAMS
#
# Commands:
# Hubot <command> <text> - Trigger webhook
#
# Author:
# Tatsuhiko Miyagawa <miyagawa@bulknews.net>
#
Qs = require 'qs'
crypto = require 'crypto'
module.exports = (robot) ->
unless process.env.HUBOT_WEBHOOK_URL
robot.logger.warning "webhook plugin is disabled since HUBOT_WEBHOOK_URL is not set."
return
webhook = new Webhook process.env
if process.env.HUBOT_WEBHOOK_COMMANDS
cmds = process.env.HUBOT_WEBHOOK_COMMANDS.split(',').join("|")
pattern = new RegExp "(#{cmds}) (.*)"
robot.respond pattern, (msg) ->
new Command(msg, robot).reply(webhook, command: msg.match[1], text: msg.match[2])
else
robot.respond /(.*)/, (msg) ->
new Command(msg, robot).reply(webhook, text: msg.match[1])
class Webhook
constructor: (env) ->
@url = env.HUBOT_WEBHOOK_URL
@params = Qs.parse env.HUBOT_WEBHOOK_PARAMS
@method = env.HUBOT_WEBHOOK_METHOD || 'POST'
@secret = env.HUBOT_WEBHOOK_HMAC_SECRET
prepareParams: (message, params) ->
params[k] = v for k, v of @params
params['user_id'] = message.user.id
params['user_name'] = message.user.name
params['room_id'] = message.user.room
params['room_name'] = message.user.room
params['reply_to'] = message.user.reply_to
makeHttp: (msg, params) ->
http = msg.http(@url)
if @secret
http.header 'X-Webhook-Signature', @signatureFor(params)
switch @method
when 'GET'
http.query(params).get()
else
http.post(Qs.stringify params)
signatureFor: (params) ->
sig = crypto.createHmac('sha1', @secret).update(Qs.stringify params).digest('hex')
"sha1=#{sig}"
class Command
constructor: (@msg, @robot) ->
reply: (webhook, params) ->
webhook.prepareParams(@msg.message, params)
webhook.makeHttp(@msg, params) @callback
callback: (err, _, body) =>
if err?
@robot.logger.error err
else if body
@msg.send body
| 195625 | # Descriptipn
# Generic Webhook plugin for Hubot
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_WEBHOOK_COMMANDS
# HUBOT_WEBHOOK_URL
# HUBOT_WEBHOOK_PARAMS
#
# Commands:
# Hubot <command> <text> - Trigger webhook
#
# Author:
# <NAME> <<EMAIL>>
#
Qs = require 'qs'
crypto = require 'crypto'
module.exports = (robot) ->
unless process.env.HUBOT_WEBHOOK_URL
robot.logger.warning "webhook plugin is disabled since HUBOT_WEBHOOK_URL is not set."
return
webhook = new Webhook process.env
if process.env.HUBOT_WEBHOOK_COMMANDS
cmds = process.env.HUBOT_WEBHOOK_COMMANDS.split(',').join("|")
pattern = new RegExp "(#{cmds}) (.*)"
robot.respond pattern, (msg) ->
new Command(msg, robot).reply(webhook, command: msg.match[1], text: msg.match[2])
else
robot.respond /(.*)/, (msg) ->
new Command(msg, robot).reply(webhook, text: msg.match[1])
class Webhook
constructor: (env) ->
@url = env.HUBOT_WEBHOOK_URL
@params = Qs.parse env.HUBOT_WEBHOOK_PARAMS
@method = env.HUBOT_WEBHOOK_METHOD || 'POST'
@secret = env.HUBOT_WEBHOOK_HMAC_SECRET
prepareParams: (message, params) ->
params[k] = v for k, v of @params
params['user_id'] = message.user.id
params['user_name'] = message.user.name
params['room_id'] = message.user.room
params['room_name'] = message.user.room
params['reply_to'] = message.user.reply_to
makeHttp: (msg, params) ->
http = msg.http(@url)
if @secret
http.header 'X-Webhook-Signature', @signatureFor(params)
switch @method
when 'GET'
http.query(params).get()
else
http.post(Qs.stringify params)
signatureFor: (params) ->
sig = crypto.createHmac('sha1', @secret).update(Qs.stringify params).digest('hex')
"sha1=#{sig}"
class Command
constructor: (@msg, @robot) ->
reply: (webhook, params) ->
webhook.prepareParams(@msg.message, params)
webhook.makeHttp(@msg, params) @callback
callback: (err, _, body) =>
if err?
@robot.logger.error err
else if body
@msg.send body
| true | # Descriptipn
# Generic Webhook plugin for Hubot
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_WEBHOOK_COMMANDS
# HUBOT_WEBHOOK_URL
# HUBOT_WEBHOOK_PARAMS
#
# Commands:
# Hubot <command> <text> - Trigger webhook
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
Qs = require 'qs'
crypto = require 'crypto'
module.exports = (robot) ->
unless process.env.HUBOT_WEBHOOK_URL
robot.logger.warning "webhook plugin is disabled since HUBOT_WEBHOOK_URL is not set."
return
webhook = new Webhook process.env
if process.env.HUBOT_WEBHOOK_COMMANDS
cmds = process.env.HUBOT_WEBHOOK_COMMANDS.split(',').join("|")
pattern = new RegExp "(#{cmds}) (.*)"
robot.respond pattern, (msg) ->
new Command(msg, robot).reply(webhook, command: msg.match[1], text: msg.match[2])
else
robot.respond /(.*)/, (msg) ->
new Command(msg, robot).reply(webhook, text: msg.match[1])
class Webhook
constructor: (env) ->
@url = env.HUBOT_WEBHOOK_URL
@params = Qs.parse env.HUBOT_WEBHOOK_PARAMS
@method = env.HUBOT_WEBHOOK_METHOD || 'POST'
@secret = env.HUBOT_WEBHOOK_HMAC_SECRET
prepareParams: (message, params) ->
params[k] = v for k, v of @params
params['user_id'] = message.user.id
params['user_name'] = message.user.name
params['room_id'] = message.user.room
params['room_name'] = message.user.room
params['reply_to'] = message.user.reply_to
makeHttp: (msg, params) ->
http = msg.http(@url)
if @secret
http.header 'X-Webhook-Signature', @signatureFor(params)
switch @method
when 'GET'
http.query(params).get()
else
http.post(Qs.stringify params)
signatureFor: (params) ->
sig = crypto.createHmac('sha1', @secret).update(Qs.stringify params).digest('hex')
"sha1=#{sig}"
class Command
constructor: (@msg, @robot) ->
reply: (webhook, params) ->
webhook.prepareParams(@msg.message, params)
webhook.makeHttp(@msg, params) @callback
callback: (err, _, body) =>
if err?
@robot.logger.error err
else if body
@msg.send body
|
[
{
"context": "time\n#\n# Notes:\n# These quotes are attributed to David Carradine, Bruce Lee\n# and Abraham Lincoln\n# Author:\n# ",
"end": 278,
"score": 0.9998971819877625,
"start": 263,
"tag": "NAME",
"value": "David Carradine"
},
{
"context": " These quotes are attributed ... | scripts/kung-fu-quotes.coffee | brucellino/fitsmbot | 0 | # Description:
# This script provides the basis for some deep sayings
#
# Dependencies:
# hubot-cron
#
# Configuration:
# none
#
# Commands:
# hubot just says these things of it's own accord from time to time
#
# Notes:
# These quotes are attributed to David Carradine, Bruce Lee
# and Abraham Lincoln
# Author:
# @brucellino
{ WebClient } = require "@slack/client"
quotes = [
"If you trust yourself, any choice you make will be correct.
If you do not trust yourself, anything you do will be wrong.",
"To know oneself is to study oneself in action with another person.",
"When one eye is fixed on the destination,
you have only one eye to search for the way.",
"When your enemy is weak, you must make him strong. To destroy that enemy,
you must first glorify his power",
"There are two strengths...
the strength of the body and the strength of the spirit.
The body is the arrow. The spirit is the bow.
You must learn to use the strength of the spirit",
"A worker is known by his tools",
" If a man dwells on the past, then he robs the present.
But if a man ignores the past, he may rob the future.",
"Do not pray for an easy life,
pray for the strength to endure a difficult one.",
"If you don’t want to slip up tomorrow, speak the truth today.",
"A goal is not always meant to be reached.
It often serves simply as something to aim at"
"Moving… be like water. Still… be like a mirror. Respond like an echo.",
"I fear not the man who has practiced 10,000 kicks once,
but I fear the man who has practiced one kick 10,000 times.",
"A quick temper will make a fool of you soon enough.",
"Notice that the stiffest tree is most easily cracked,
while the bamboo or willow survives by bending with the wind.",
"Obey the principles without being bound by them.",
"Showing off is the fool’s idea of glory.",
"Absorb what is useful, discard what is not, add what is uniquely your own.",
"Knowledge will give you power, but character respect.",
"Those who are unaware they are walking
in darkness will never seek the light.",
"A wise man can learn more from a foolish question
than a fool can learn from a wise answer.",
"Choose the positive.
You have choice, you are master of your attitude,
choose the positive, the constructive.",
"I can show you the path but I can not walk it for you.",
"A Black Belt should be a reflection of what is inside not the proof of it!",
"He who is taught only by himself has a fool for a master.",
"The weakest of all weak things is a virtue that has not been tested in the
fire.",
"Seek not to follow in the footsteps of men of old; seek what they sought.",
"We are what we repeatedly do. Excellence then, is not an act, but a habit.",
"Should you desire the great tranquility, prepare to sweat.",
"First master your instrument, than just play.",
" There is no secret ingredient, to make something special
you just have to believe its special.",
"If you spend too much time thinking about a thing,
you'll never get it done.",
"Knowing is not enough, you must apply; willing is not enough, you must do.",
"I am not teaching you anything. I just help you to explore yourself",
"As you think, so shall you become."
]
module.exports = (robot) ->
web = new WebClient robot.adapter.options.token
# choose a random quote
n = Math.floor(Math.random() * (quotes.length))
# get the fitsm channel
#default_channel_name = "fitsm"
default_channel_name = process.env.FITSM_SLACK_CHANNEL
web.channels.list()
.then (api_response) ->
# The channel list is searched for the channel with the right name,
# and the notification_room is updated
room = api_response.channels.find (channel) ->
channel.name is default_channel_name
notification_room = room.id if room?
robot.messageRoom room.id, quotes[n]
# NOTE: for workspaces with a large number of channels,
# this can result in a timeout error. Use pagination.
.catch (error) ->
robot.logger.error error.message | 2235 | # Description:
# This script provides the basis for some deep sayings
#
# Dependencies:
# hubot-cron
#
# Configuration:
# none
#
# Commands:
# hubot just says these things of it's own accord from time to time
#
# Notes:
# These quotes are attributed to <NAME>, <NAME>
# and <NAME>
# Author:
# @brucellino
{ WebClient } = require "@slack/client"
quotes = [
"If you trust yourself, any choice you make will be correct.
If you do not trust yourself, anything you do will be wrong.",
"To know oneself is to study oneself in action with another person.",
"When one eye is fixed on the destination,
you have only one eye to search for the way.",
"When your enemy is weak, you must make him strong. To destroy that enemy,
you must first glorify his power",
"There are two strengths...
the strength of the body and the strength of the spirit.
The body is the arrow. The spirit is the bow.
You must learn to use the strength of the spirit",
"A worker is known by his tools",
" If a man dwells on the past, then he robs the present.
But if a man ignores the past, he may rob the future.",
"Do not pray for an easy life,
pray for the strength to endure a difficult one.",
"If you don’t want to slip up tomorrow, speak the truth today.",
"A goal is not always meant to be reached.
It often serves simply as something to aim at"
"Moving… be like water. Still… be like a mirror. Respond like an echo.",
"I fear not the man who has practiced 10,000 kicks once,
but I fear the man who has practiced one kick 10,000 times.",
"A quick temper will make a fool of you soon enough.",
"Notice that the stiffest tree is most easily cracked,
while the bamboo or willow survives by bending with the wind.",
"Obey the principles without being bound by them.",
"Showing off is the fool’s idea of glory.",
"Absorb what is useful, discard what is not, add what is uniquely your own.",
"Knowledge will give you power, but character respect.",
"Those who are unaware they are walking
in darkness will never seek the light.",
"A wise man can learn more from a foolish question
than a fool can learn from a wise answer.",
"Choose the positive.
You have choice, you are master of your attitude,
choose the positive, the constructive.",
"I can show you the path but I can not walk it for you.",
"A Black Belt should be a reflection of what is inside not the proof of it!",
"He who is taught only by himself has a fool for a master.",
"The weakest of all weak things is a virtue that has not been tested in the
fire.",
"Seek not to follow in the footsteps of men of old; seek what they sought.",
"We are what we repeatedly do. Excellence then, is not an act, but a habit.",
"Should you desire the great tranquility, prepare to sweat.",
"First master your instrument, than just play.",
" There is no secret ingredient, to make something special
you just have to believe its special.",
"If you spend too much time thinking about a thing,
you'll never get it done.",
"Knowing is not enough, you must apply; willing is not enough, you must do.",
"I am not teaching you anything. I just help you to explore yourself",
"As you think, so shall you become."
]
module.exports = (robot) ->
web = new WebClient robot.adapter.options.token
# choose a random quote
n = Math.floor(Math.random() * (quotes.length))
# get the fitsm channel
#default_channel_name = "fitsm"
default_channel_name = process.env.FITSM_SLACK_CHANNEL
web.channels.list()
.then (api_response) ->
# The channel list is searched for the channel with the right name,
# and the notification_room is updated
room = api_response.channels.find (channel) ->
channel.name is default_channel_name
notification_room = room.id if room?
robot.messageRoom room.id, quotes[n]
# NOTE: for workspaces with a large number of channels,
# this can result in a timeout error. Use pagination.
.catch (error) ->
robot.logger.error error.message | true | # Description:
# This script provides the basis for some deep sayings
#
# Dependencies:
# hubot-cron
#
# Configuration:
# none
#
# Commands:
# hubot just says these things of it's own accord from time to time
#
# Notes:
# These quotes are attributed to PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
# and PI:NAME:<NAME>END_PI
# Author:
# @brucellino
{ WebClient } = require "@slack/client"
quotes = [
"If you trust yourself, any choice you make will be correct.
If you do not trust yourself, anything you do will be wrong.",
"To know oneself is to study oneself in action with another person.",
"When one eye is fixed on the destination,
you have only one eye to search for the way.",
"When your enemy is weak, you must make him strong. To destroy that enemy,
you must first glorify his power",
"There are two strengths...
the strength of the body and the strength of the spirit.
The body is the arrow. The spirit is the bow.
You must learn to use the strength of the spirit",
"A worker is known by his tools",
" If a man dwells on the past, then he robs the present.
But if a man ignores the past, he may rob the future.",
"Do not pray for an easy life,
pray for the strength to endure a difficult one.",
"If you don’t want to slip up tomorrow, speak the truth today.",
"A goal is not always meant to be reached.
It often serves simply as something to aim at"
"Moving… be like water. Still… be like a mirror. Respond like an echo.",
"I fear not the man who has practiced 10,000 kicks once,
but I fear the man who has practiced one kick 10,000 times.",
"A quick temper will make a fool of you soon enough.",
"Notice that the stiffest tree is most easily cracked,
while the bamboo or willow survives by bending with the wind.",
"Obey the principles without being bound by them.",
"Showing off is the fool’s idea of glory.",
"Absorb what is useful, discard what is not, add what is uniquely your own.",
"Knowledge will give you power, but character respect.",
"Those who are unaware they are walking
in darkness will never seek the light.",
"A wise man can learn more from a foolish question
than a fool can learn from a wise answer.",
"Choose the positive.
You have choice, you are master of your attitude,
choose the positive, the constructive.",
"I can show you the path but I can not walk it for you.",
"A Black Belt should be a reflection of what is inside not the proof of it!",
"He who is taught only by himself has a fool for a master.",
"The weakest of all weak things is a virtue that has not been tested in the
fire.",
"Seek not to follow in the footsteps of men of old; seek what they sought.",
"We are what we repeatedly do. Excellence then, is not an act, but a habit.",
"Should you desire the great tranquility, prepare to sweat.",
"First master your instrument, than just play.",
" There is no secret ingredient, to make something special
you just have to believe its special.",
"If you spend too much time thinking about a thing,
you'll never get it done.",
"Knowing is not enough, you must apply; willing is not enough, you must do.",
"I am not teaching you anything. I just help you to explore yourself",
"As you think, so shall you become."
]
module.exports = (robot) ->
web = new WebClient robot.adapter.options.token
# choose a random quote
n = Math.floor(Math.random() * (quotes.length))
# get the fitsm channel
#default_channel_name = "fitsm"
default_channel_name = process.env.FITSM_SLACK_CHANNEL
web.channels.list()
.then (api_response) ->
# The channel list is searched for the channel with the right name,
# and the notification_room is updated
room = api_response.channels.find (channel) ->
channel.name is default_channel_name
notification_room = room.id if room?
robot.messageRoom room.id, quotes[n]
# NOTE: for workspaces with a large number of channels,
# this can result in a timeout error. Use pagination.
.catch (error) ->
robot.logger.error error.message |
[
{
"context": "5\n\nseveral = count to five\n\nme = be me Gentleman 'Pavel'\n\nmethod = me.speak\n\n# being polite will save you",
"end": 164,
"score": 0.9996739625930786,
"start": 159,
"tag": "NAME",
"value": "Pavel"
}
] | index.coffee | PavelVanecek/cup_o_tea | 0 | {
please
iterate
me
my
times
using
Gentleman
count
to
be
} = require './english'
five = 5
several = count to five
me = be me Gentleman 'Pavel'
method = me.speak
# being polite will save you a lot of time
# iterate my method several times using 'foo'
please iterate my method several times using 'well hello there'
| 32824 | {
please
iterate
me
my
times
using
Gentleman
count
to
be
} = require './english'
five = 5
several = count to five
me = be me Gentleman '<NAME>'
method = me.speak
# being polite will save you a lot of time
# iterate my method several times using 'foo'
please iterate my method several times using 'well hello there'
| true | {
please
iterate
me
my
times
using
Gentleman
count
to
be
} = require './english'
five = 5
several = count to five
me = be me Gentleman 'PI:NAME:<NAME>END_PI'
method = me.speak
# being polite will save you a lot of time
# iterate my method several times using 'foo'
please iterate my method several times using 'well hello there'
|
[
{
"context": "=========================================\n# Autor: Esteve Lladó (Fundació Bit), 2016\n# ==========================",
"end": 65,
"score": 0.9998742341995239,
"start": 53,
"tag": "NAME",
"value": "Esteve Lladó"
}
] | source/coffee/dictionary_terms.coffee | Fundacio-Bit/twitter-intranet | 0 | # =========================================
# Autor: Esteve Lladó (Fundació Bit), 2016
# =========================================
(($) ->
g_entries = [] # var global con la lista de entradas que servirá para refrescar después de borrar una entrada
# Función para extraer las marcas de la REST y renderizar resultados
# ------------------------------------------------------------------
getBrands = () ->
brand_list = []
request = "/rest_utils/brands"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
data.results.forEach (brand) ->
brand_list.push({'value': brand, 'name': brand.charAt(0).toUpperCase() + brand.slice(1)})
html_content = MyApp.templates.selectBrands {entries: brand_list, all_brands: true, label: true }
$('#form-group-brands').html html_content
html_content = MyApp.templates.selectBrandsModal {entries: brand_list, all_brands: true, label: true }
$('#form-group-brands-modal').html html_content
# Extraer las marcas de la REST y renderizar resultados
# -----------------------------------------------------
getBrands()
# =======================================================================================
# EVENTOS SOBRE COLUMNAS DE LA TABLA DE ENTRADAS
# =======================================================================================
setEventsOnEntriesTable = ->
# --------------------------------------
# Fijamos evento sobre columna de alias
# --------------------------------------
$('td.updateAlias').click ->
myid = $(this).attr('id')
myCanonicalName = $(this).attr('name')
mytext = $(this).text()
alias = (al.trim() for al in mytext.split(','))
$('#updateAliasList').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant...</p>'
$('#updateAliasModal').modal 'show' # mostramos el modal
setTimeout ( ->
# Eliminamos posibles duplicados
# -------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
# Descartamos alias que tienen caracteres extraños a una sublista en rojo
# ------------------------------------------------------------------------
discardedAlias = []
purgedAlias = []
uniqueAlias.forEach (al) ->
if al[0] is '#' # hashtag
if /^#[a-z0-9_]+$/.test(al) then purgedAlias.push(al) else discardedAlias.push(al)
else
if /^[a-z0-9\s&]+$/.test(al) then purgedAlias.push(al) else discardedAlias.push(al)
# Sacamos otros alias candidatos a partir del nombre canónico con la REST
# ------------------------------------------------------------------------
request = "/rest_dictionary_terms/alias/canonical_name/#{myCanonicalName}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#updateAliasList').html ''
alert "ERROR: #{JSON.stringify data.error}"
else
# =================
# Petición REST OK
# =================
restAlias = data.results
# Eliminamos posibles duplicados
# -------------------------------
otherCandidateAlias = []
restAlias.forEach (x) -> if x not in otherCandidateAlias then otherCandidateAlias.push x
# Formateamos para pintar el template
# ------------------------------------
discardedAlias = discardedAlias.map (alias) -> {alias: alias}
purgedAlias = purgedAlias.map (alias) -> {alias: alias}
otherCandidateAlias = otherCandidateAlias.map (alias) -> {alias: alias}
html_content = MyApp.templates.listDictionaryCandidateAlias {candidate_alias: purgedAlias, discarded_alias: discardedAlias, other_alias: otherCandidateAlias}
$('#updateAliasList').html html_content
# ---------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Añadir alias a la lista'
# ---------------------------------------------------------------
$('#updateAliasModal #addNewAliasButton').click (event) ->
event.preventDefault()
new_alias = $('#updateAliasModal #addNewAliasForm input[name="newAlias"]').val()
new_alias = new_alias.trim()
if new_alias isnt '' and not /^\s+$/.test(new_alias)
# Chequeamos el nuevo alias
# --------------------------
is_correct = false
if new_alias[0] is '#' # si es hashtag
if /^#[a-z0-9_]+$/.test(new_alias)
is_correct = true
else
alert 'ERROR: HASHTAG INCORRECTE! Revisi que no contengui caràcters prohibits (espais, majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), i underscore (_).'
else
if /^[a-z0-9\s&]+$/.test(new_alias)
is_correct = true
new_alias = new_alias.trim().replace /\s+/g, ' '
else
alert 'ERROR: ALIAS INCORRECTE! Revisi que no contengui caràcters prohibits (majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), espais entre paraules, i umpersand (&).'
if is_correct
# Comprobamos si hay alias repetidos en la lista antes de seleccionar
# --------------------------------------------------------------------
current_alias = []
$('#updateAliasModal #checkboxAliasListForm input[name="aliasCheckBox"]').each (e) ->
current_alias.push $(this).val()
if new_alias not in current_alias
$('#updateAliasModal #saveButton').before "<div class=\"checkbox\"><label><input type=\"checkbox\" class=\"check\" name=\"aliasCheckBox\" value=\"#{new_alias}\"> <i>#{new_alias}</i></label></div>"
else
alert "ERROR: L'àlies '#{new_alias}' està repetit a la llista."
return false
# -----------------------------------------------
# Modal: Fijamos evento sobre botón de 'Guardar'
# -----------------------------------------------
$('#updateAliasModal #saveButton').click (event) ->
event.preventDefault()
# Recogemos los alias seleccionados
# ----------------------------------
alias = []
$('#updateAliasModal #checkboxAliasListForm input[name="aliasCheckBox"]:checked').each (e) ->
alias.push $(this).val()
# Eliminamos posibles duplicados de la selección
# -----------------------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
if uniqueAlias.length is 0
alert "ERROR: No ha escollit cap àlies de la llista!"
else
# Comprobamos que no hay alias solapados entre ellos
# ---------------------------------------------------
hay_solapados = false
ngrams = uniqueAlias.filter (x) -> x[0] isnt '#'
for x in ngrams
for y in ngrams
if x isnt y
if x in y.split /\s+/
alert "ERROR: L'àlies '#{x}' està contingut dins '#{y}'. Descarti algun dels dos."
hay_solapados = true
break
if not hay_solapados
updateConfirmed = confirm "Validació de regles OK!\n\n" + "Nous àlies = #{uniqueAlias.join(', ')}\n\nVol MODIFICAR l'entrada?"
if updateConfirmed
# ==============
# Validación OK
# ==============
request = "/rest_dictionary_terms/entries/id/#{myid}"
$.ajax({
url: request,
type: "PUT",
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify({updatedAlias: uniqueAlias}),
error: (jqXHR) -> console.log "Ajax error: " + jqXHR.status
}).done (data) ->
# -------------------------------------------
# Procesamos el resultado de la petición PUT
# -------------------------------------------
if data.error?
alert "ERROR: #{JSON.stringify data.error}"
else
# alert "#{data.results}"
# Cerramos modal
# ---------------
$('#updateAliasModal').modal 'hide'
# Actualizamos columna
# ---------------------
$("td.updateAlias[id=\"#{myid}\"]").css "background-color", "#ddffdd"
$("td.updateAlias[id=\"#{myid}\"]").html "<i>#{uniqueAlias.join ', '}</i>"
return false
), 600 # cierra el timeout
# ---------------------------------------
# Fijamos evento sobre columna de status
# ---------------------------------------
$('td.updateStatus').click ->
myid = $(this).attr('id')
mystatus = $(this).text()
# cambiamos el estado como un interruptor on/off (PENDENT o vacío)
# -----------------------------------------------------------------
change_status = false
if mystatus is 'PENDENT'
changeConfirmed = confirm "Vol llevar l'estat 'PENDENT' d'aquesta entrada?"
if changeConfirmed
change_status = true
newstatus = 'none' # cualquier cosa distinta de 'PENDENT' sirve para borrar el estado
else
changeConfirmed = confirm "Vol posar l'estat a 'PENDENT' per aquesta entrada?"
if changeConfirmed
change_status = true
newstatus = 'PENDENT'
if change_status
request = "/rest_dictionary_terms/entries/id/#{myid}/status/#{newstatus}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
alert data.error
else
# =================
# Petición REST OK
# =================
# Modificamos el valor de la columna de la tabla
# -----------------------------------------------
if newstatus is 'none' then newstatus = ''
$("td.updateStatus[id=\"#{myid}\"]").html "<span class=\"label label-danger\">#{newstatus}</span>"
return false
# ------------------------------------------------
# Fijamos evento sobre columna de borrar entradas
# ------------------------------------------------
$('td.remove a').click ->
entryIdToDelete = $(this).attr('href')
acceptClicked = confirm "Segur que vol esborrar l'entrada?"
if acceptClicked then deleteDictionaryEntry entryIdToDelete
return false
# =====================================================================================
# DELETE DE ENTRADAS
# =====================================================================================
# ------------------------------------------------
# Función para borrar una entrada del diccionario
# ------------------------------------------------
deleteDictionaryEntry = (id) ->
request = "/rest_dictionary_terms/entries/delete/id/#{id}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
alert data.error
else
# =================
# Petición REST OK
# =================
# refrescamos la tabla de entradas
# ---------------------------------
$('#statusPanel').html ''
g_entries = g_entries.filter (x) -> x._id isnt id
if g_entries.length > 0
html_content = MyApp.templates.dictionaryTable {total_entries: g_entries.length, entries: g_entries}
$('#dictionaryTable').html html_content
setEventsOnEntriesTable()
else
$('#dictionaryTable').html ''
# =====================================================================================
# BÚSQUEDA (SEARCH) DE ENTRADAS
# =====================================================================================
# ---------------------------------------------------------------------------------
# Función para extraer entradas del diccionario de la REST y renderizar resultados
# ---------------------------------------------------------------------------------
getDictionaryEntriesAndRenderTable = (request) ->
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
# =================
# Petición REST OK
# =================
entries = data.results
entries.forEach (x) ->
x.brand = x.brand.toUpperCase()
x.category = x.category.toUpperCase()
x.alias = (al.trim() for al in x.alias.split(',')).join ', '
if not x.status? then x.status = ''
g_entries = entries # servirá para refrescar después de borrar una entrada
setTimeout ( ->
# -------------------
# Renderizamos tabla
# -------------------
html_content = MyApp.templates.dictionaryTable {total_entries: entries.length, entries: entries}
$('#dictionaryTable').html html_content
$('#statusPanel').html ''
setEventsOnEntriesTable()
), 600
$('#statusPanel').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant...</p>'
# -------------------------------------
# Fijamos evento sobre botón de Buscar
# -------------------------------------
$('#searchButton').click ->
categoria = $('#searchForm select[name="category"]').val()
marca = $('#searchForm select[name="brand"]').val()
# controlamos visibilidad de elementos
# -------------------------------------
$('#dictionaryTable').html ''
$('#statusPanel').html ''
# Petición REST
# --------------
request = "/rest_dictionary_terms/entries/category/#{categoria}/brand/#{marca}"
getDictionaryEntriesAndRenderTable request
return false
# =====================================================================================
# MODAL DE NUEVAS ENTRADAS
# =====================================================================================
# ----------------------------------------------
# Fijamos evento sobre botón de 'Crear entrada'
# ----------------------------------------------
$('#createButton').click ->
$('#resetBasicDataButton').click() # clickamos 'netejar' para limpiar formulario
$('#createNewEntryModal').modal 'show' # mostramos el modal
return false
# -----------------------------------------------------------
# Fijamos evento sobre el primer botón de borrar formularios
# -----------------------------------------------------------
$('#resetBasicDataButton').click ->
$('#candidateAliasList').html ''
$('#statusPanelModal').html ''
# ----------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Generar alias candidatos'
# ----------------------------------------------------------------
$('#generateCandidateAliasButton').click (event) ->
event.preventDefault()
$('#statusPanelModal').html ''
# Recogemos los campos del formulario
# ------------------------------------
brands = []
$('#form-group-brands-modal input[name="brand"]:checked').each (e) ->
brands.push $(this).val()
newEntry =
brands: brands
category: $('#basicDataNewEntryForm select[name="category"]').val()
_canonical_name: $('#basicDataNewEntryForm input[name="canonicalName"]').val()
# Validamos los campos
# ---------------------
if newEntry.brands.length == 0
setTimeout ( -> $('#brandError').html '' ), 1500
$('#brandError').html MyApp.templates.commonsModalFormValidation {message: 'Falta triar una <b>marca</b>'}
else if newEntry.category is null
setTimeout ( -> $('#categoryError').html '' ), 1500
$('#categoryError').html MyApp.templates.commonsModalFormValidation {message: 'Falta triar una <b>categoria</b>'}
else if newEntry._canonical_name is ''
setTimeout ( -> $('#canonicalNameError').html '' ), 1500
$('#canonicalNameError').html MyApp.templates.commonsModalFormValidation {message: 'Falta omplir el <b>nom canònic</b>'}
else
# ==============
# Validación OK
# ==============
$('#candidateAliasList').html '<img src="/img/rendering.gif">'
request = "/rest_dictionary_terms/alias/canonical_name/#{newEntry._canonical_name}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#candidateAliasList').html ''
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "Error: #{JSON.stringify data.error}"}
else
# =================
# Petición REST OK
# =================
candidate_alias = data.results
candidate_alias = candidate_alias.map (alias) -> {alias: alias}
html_content = MyApp.templates.listDictionaryCandidateAlias {candidate_alias: candidate_alias}
$('#candidateAliasList').html html_content
# ---------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Añadir alias a la lista'
# ---------------------------------------------------------------
$('#createNewEntryModal #addNewAliasButton').click (event) ->
event.preventDefault()
new_alias = $('#createNewEntryModal #addNewAliasForm input[name="newAlias"]').val()
new_alias = new_alias.trim()
if new_alias isnt '' and not /^\s+$/.test(new_alias)
# Chequeamos el nuevo alias
# --------------------------
is_correct = false
if new_alias[0] is '#' # si es hashtag
if /^#[a-z0-9_]+$/.test(new_alias)
is_correct = true
else
alert 'ERROR: HASHTAG INCORRECTE! Revisi que no contengui caràcters prohibits (espais, majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), i underscore (_).'
else
if /^[a-z0-9\s&]+$/.test(new_alias)
is_correct = true
new_alias = new_alias.trim().replace /\s+/g, ' '
else
alert 'ERROR: ALIAS INCORRECTE! Revisi que no contengui caràcters prohibits (majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), espais entre paraules, i umpersand (&).'
if is_correct
# Comprobamos si hay alias repetidos en la lista antes de seleccionar
# --------------------------------------------------------------------
current_alias = []
$('#createNewEntryModal #checkboxAliasListForm input[name="aliasCheckBox"]').each (e) ->
current_alias.push $(this).val()
if new_alias not in current_alias
$('#createNewEntryModal #saveButton').before "<div class=\"checkbox\"><label><input type=\"checkbox\" class=\"check\" name=\"aliasCheckBox\" value=\"#{new_alias}\"> <i>#{new_alias}</i></label></div>"
else
alert "ERROR: L'àlies '#{new_alias}' està repetit a la llista."
return false
# -------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Guardar nueva entrada'
# -------------------------------------------------------------
$('#createNewEntryModal #saveButton').click (event) ->
event.preventDefault()
# # Recogemos los datos de la nueva entrada (para el nombre canónico se debe coger el que se usó para generar los alias)
# # ----------------------------------------
# newEntry.brand = $('#basicDataNewEntryForm select[name="brand"]').val()
# Recogemos los brands seleccionados
# ----------------------------------
brands = []
$('#form-group-brands-modal input[name="brand"]:checked').each (e) ->
brands.push $(this).val()
# newEntry.brands = brands
newEntry.category = $('#basicDataNewEntryForm select[name="category"]').val()
# Comprobamos que no haya comas y semicolons en el nombre canónico
# -----------------------------------------------------------------
if /(,|;)/.test newEntry._canonical_name
alert "ERROR: El nom canònic no pot contenir comes (,) o semicolons (;).\nEsborri'ls i tornar a clickar 'Generar àlies candidats' i a seleccionar els àlies."
else
# Recogemos los alias seleccionados
# ----------------------------------
alias = []
$('#createNewEntryModal #checkboxAliasListForm input[name="aliasCheckBox"]:checked').each (e) ->
alias.push $(this).val()
# Comprobamos que no hay alias solapados entre ellos
# ---------------------------------------------------
hay_solapados = false
ngrams = alias.filter (x) -> x[0] isnt '#'
for x in ngrams
for y in ngrams
if x isnt y
if x in y.split /\s+/
alert "ERROR: L'àlies '#{x}' està contingut dins '#{y}'. Descarti algun dels dos."
hay_solapados = true
break
if not hay_solapados
# Eliminamos posibles duplicados
# -------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
newEntry.alias = uniqueAlias
newEntryConfirmed = confirm "Validació de regles OK!\n\n" + "Marca = #{newEntry.brands}\nCategoria = #{newEntry.category}\nNom canònic = #{newEntry._canonical_name}\nAlias = #{newEntry.alias.join(', ')}\n\nVol GUARDAR la nova entrada?"
if newEntryConfirmed
# ==============
# Validación OK
# ==============
# Guardamos nuevas entradas en MongoDB
# ------------------------------------
for brand in brands
newEntry.brand = brand
$.ajax({
url: '/rest_dictionary_terms/entries',
type: "POST",
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(newEntry),
error: (jqXHR) -> console.log "Ajax error: " + jqXHR.status
}).done (result) ->
# --------------------------------------------
# Procesamos el resultado de la petición POST
# --------------------------------------------
if result.ok?
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'success', glyphicon: 'ok', message: "Entrada creada correctament."}
# Mostramos la entrada insertada
# -------------------------------
$('#resetSearchButton').click() # limpiamos formulario de búsqueda del documento general
$('#dictionaryTable').html ''
$('#statusPanel').html ''
request = "/rest_dictionary_terms/entries/id/#{result.id}"
# getDictionaryEntriesAndRenderTable request
setTimeout ( ->
$('#createNewEntryModal').modal 'hide'
), 1000
else if result.error?
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "Error: #{result.error}"}
else
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "No s'ha pogut guardar la nova entrada."}
# # ------------------------------------------
# # Fijamos evento al hacer chek en Select All
# # ------------------------------------------
# $('#checkAll').click (event) ->
# event.preventDefault()
# $('.check').prop 'checked', $(this).prop('checked')
# Ocultaciones al inicio
# -----------------------
$('#statusPanel').html ''
$('#dictionaryTable').html ''
) jQuery | 156221 | # =========================================
# Autor: <NAME> (Fundació Bit), 2016
# =========================================
(($) ->
g_entries = [] # var global con la lista de entradas que servirá para refrescar después de borrar una entrada
# Función para extraer las marcas de la REST y renderizar resultados
# ------------------------------------------------------------------
getBrands = () ->
brand_list = []
request = "/rest_utils/brands"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
data.results.forEach (brand) ->
brand_list.push({'value': brand, 'name': brand.charAt(0).toUpperCase() + brand.slice(1)})
html_content = MyApp.templates.selectBrands {entries: brand_list, all_brands: true, label: true }
$('#form-group-brands').html html_content
html_content = MyApp.templates.selectBrandsModal {entries: brand_list, all_brands: true, label: true }
$('#form-group-brands-modal').html html_content
# Extraer las marcas de la REST y renderizar resultados
# -----------------------------------------------------
getBrands()
# =======================================================================================
# EVENTOS SOBRE COLUMNAS DE LA TABLA DE ENTRADAS
# =======================================================================================
setEventsOnEntriesTable = ->
# --------------------------------------
# Fijamos evento sobre columna de alias
# --------------------------------------
$('td.updateAlias').click ->
myid = $(this).attr('id')
myCanonicalName = $(this).attr('name')
mytext = $(this).text()
alias = (al.trim() for al in mytext.split(','))
$('#updateAliasList').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant...</p>'
$('#updateAliasModal').modal 'show' # mostramos el modal
setTimeout ( ->
# Eliminamos posibles duplicados
# -------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
# Descartamos alias que tienen caracteres extraños a una sublista en rojo
# ------------------------------------------------------------------------
discardedAlias = []
purgedAlias = []
uniqueAlias.forEach (al) ->
if al[0] is '#' # hashtag
if /^#[a-z0-9_]+$/.test(al) then purgedAlias.push(al) else discardedAlias.push(al)
else
if /^[a-z0-9\s&]+$/.test(al) then purgedAlias.push(al) else discardedAlias.push(al)
# Sacamos otros alias candidatos a partir del nombre canónico con la REST
# ------------------------------------------------------------------------
request = "/rest_dictionary_terms/alias/canonical_name/#{myCanonicalName}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#updateAliasList').html ''
alert "ERROR: #{JSON.stringify data.error}"
else
# =================
# Petición REST OK
# =================
restAlias = data.results
# Eliminamos posibles duplicados
# -------------------------------
otherCandidateAlias = []
restAlias.forEach (x) -> if x not in otherCandidateAlias then otherCandidateAlias.push x
# Formateamos para pintar el template
# ------------------------------------
discardedAlias = discardedAlias.map (alias) -> {alias: alias}
purgedAlias = purgedAlias.map (alias) -> {alias: alias}
otherCandidateAlias = otherCandidateAlias.map (alias) -> {alias: alias}
html_content = MyApp.templates.listDictionaryCandidateAlias {candidate_alias: purgedAlias, discarded_alias: discardedAlias, other_alias: otherCandidateAlias}
$('#updateAliasList').html html_content
# ---------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Añadir alias a la lista'
# ---------------------------------------------------------------
$('#updateAliasModal #addNewAliasButton').click (event) ->
event.preventDefault()
new_alias = $('#updateAliasModal #addNewAliasForm input[name="newAlias"]').val()
new_alias = new_alias.trim()
if new_alias isnt '' and not /^\s+$/.test(new_alias)
# Chequeamos el nuevo alias
# --------------------------
is_correct = false
if new_alias[0] is '#' # si es hashtag
if /^#[a-z0-9_]+$/.test(new_alias)
is_correct = true
else
alert 'ERROR: HASHTAG INCORRECTE! Revisi que no contengui caràcters prohibits (espais, majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), i underscore (_).'
else
if /^[a-z0-9\s&]+$/.test(new_alias)
is_correct = true
new_alias = new_alias.trim().replace /\s+/g, ' '
else
alert 'ERROR: ALIAS INCORRECTE! Revisi que no contengui caràcters prohibits (majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), espais entre paraules, i umpersand (&).'
if is_correct
# Comprobamos si hay alias repetidos en la lista antes de seleccionar
# --------------------------------------------------------------------
current_alias = []
$('#updateAliasModal #checkboxAliasListForm input[name="aliasCheckBox"]').each (e) ->
current_alias.push $(this).val()
if new_alias not in current_alias
$('#updateAliasModal #saveButton').before "<div class=\"checkbox\"><label><input type=\"checkbox\" class=\"check\" name=\"aliasCheckBox\" value=\"#{new_alias}\"> <i>#{new_alias}</i></label></div>"
else
alert "ERROR: L'àlies '#{new_alias}' està repetit a la llista."
return false
# -----------------------------------------------
# Modal: Fijamos evento sobre botón de 'Guardar'
# -----------------------------------------------
$('#updateAliasModal #saveButton').click (event) ->
event.preventDefault()
# Recogemos los alias seleccionados
# ----------------------------------
alias = []
$('#updateAliasModal #checkboxAliasListForm input[name="aliasCheckBox"]:checked').each (e) ->
alias.push $(this).val()
# Eliminamos posibles duplicados de la selección
# -----------------------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
if uniqueAlias.length is 0
alert "ERROR: No ha escollit cap àlies de la llista!"
else
# Comprobamos que no hay alias solapados entre ellos
# ---------------------------------------------------
hay_solapados = false
ngrams = uniqueAlias.filter (x) -> x[0] isnt '#'
for x in ngrams
for y in ngrams
if x isnt y
if x in y.split /\s+/
alert "ERROR: L'àlies '#{x}' està contingut dins '#{y}'. Descarti algun dels dos."
hay_solapados = true
break
if not hay_solapados
updateConfirmed = confirm "Validació de regles OK!\n\n" + "Nous àlies = #{uniqueAlias.join(', ')}\n\nVol MODIFICAR l'entrada?"
if updateConfirmed
# ==============
# Validación OK
# ==============
request = "/rest_dictionary_terms/entries/id/#{myid}"
$.ajax({
url: request,
type: "PUT",
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify({updatedAlias: uniqueAlias}),
error: (jqXHR) -> console.log "Ajax error: " + jqXHR.status
}).done (data) ->
# -------------------------------------------
# Procesamos el resultado de la petición PUT
# -------------------------------------------
if data.error?
alert "ERROR: #{JSON.stringify data.error}"
else
# alert "#{data.results}"
# Cerramos modal
# ---------------
$('#updateAliasModal').modal 'hide'
# Actualizamos columna
# ---------------------
$("td.updateAlias[id=\"#{myid}\"]").css "background-color", "#ddffdd"
$("td.updateAlias[id=\"#{myid}\"]").html "<i>#{uniqueAlias.join ', '}</i>"
return false
), 600 # cierra el timeout
# ---------------------------------------
# Fijamos evento sobre columna de status
# ---------------------------------------
$('td.updateStatus').click ->
myid = $(this).attr('id')
mystatus = $(this).text()
# cambiamos el estado como un interruptor on/off (PENDENT o vacío)
# -----------------------------------------------------------------
change_status = false
if mystatus is 'PENDENT'
changeConfirmed = confirm "Vol llevar l'estat 'PENDENT' d'aquesta entrada?"
if changeConfirmed
change_status = true
newstatus = 'none' # cualquier cosa distinta de 'PENDENT' sirve para borrar el estado
else
changeConfirmed = confirm "Vol posar l'estat a 'PENDENT' per aquesta entrada?"
if changeConfirmed
change_status = true
newstatus = 'PENDENT'
if change_status
request = "/rest_dictionary_terms/entries/id/#{myid}/status/#{newstatus}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
alert data.error
else
# =================
# Petición REST OK
# =================
# Modificamos el valor de la columna de la tabla
# -----------------------------------------------
if newstatus is 'none' then newstatus = ''
$("td.updateStatus[id=\"#{myid}\"]").html "<span class=\"label label-danger\">#{newstatus}</span>"
return false
# ------------------------------------------------
# Fijamos evento sobre columna de borrar entradas
# ------------------------------------------------
$('td.remove a').click ->
entryIdToDelete = $(this).attr('href')
acceptClicked = confirm "Segur que vol esborrar l'entrada?"
if acceptClicked then deleteDictionaryEntry entryIdToDelete
return false
# =====================================================================================
# DELETE DE ENTRADAS
# =====================================================================================
# ------------------------------------------------
# Función para borrar una entrada del diccionario
# ------------------------------------------------
deleteDictionaryEntry = (id) ->
request = "/rest_dictionary_terms/entries/delete/id/#{id}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
alert data.error
else
# =================
# Petición REST OK
# =================
# refrescamos la tabla de entradas
# ---------------------------------
$('#statusPanel').html ''
g_entries = g_entries.filter (x) -> x._id isnt id
if g_entries.length > 0
html_content = MyApp.templates.dictionaryTable {total_entries: g_entries.length, entries: g_entries}
$('#dictionaryTable').html html_content
setEventsOnEntriesTable()
else
$('#dictionaryTable').html ''
# =====================================================================================
# BÚSQUEDA (SEARCH) DE ENTRADAS
# =====================================================================================
# ---------------------------------------------------------------------------------
# Función para extraer entradas del diccionario de la REST y renderizar resultados
# ---------------------------------------------------------------------------------
getDictionaryEntriesAndRenderTable = (request) ->
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
# =================
# Petición REST OK
# =================
entries = data.results
entries.forEach (x) ->
x.brand = x.brand.toUpperCase()
x.category = x.category.toUpperCase()
x.alias = (al.trim() for al in x.alias.split(',')).join ', '
if not x.status? then x.status = ''
g_entries = entries # servirá para refrescar después de borrar una entrada
setTimeout ( ->
# -------------------
# Renderizamos tabla
# -------------------
html_content = MyApp.templates.dictionaryTable {total_entries: entries.length, entries: entries}
$('#dictionaryTable').html html_content
$('#statusPanel').html ''
setEventsOnEntriesTable()
), 600
$('#statusPanel').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant...</p>'
# -------------------------------------
# Fijamos evento sobre botón de Buscar
# -------------------------------------
$('#searchButton').click ->
categoria = $('#searchForm select[name="category"]').val()
marca = $('#searchForm select[name="brand"]').val()
# controlamos visibilidad de elementos
# -------------------------------------
$('#dictionaryTable').html ''
$('#statusPanel').html ''
# Petición REST
# --------------
request = "/rest_dictionary_terms/entries/category/#{categoria}/brand/#{marca}"
getDictionaryEntriesAndRenderTable request
return false
# =====================================================================================
# MODAL DE NUEVAS ENTRADAS
# =====================================================================================
# ----------------------------------------------
# Fijamos evento sobre botón de 'Crear entrada'
# ----------------------------------------------
$('#createButton').click ->
$('#resetBasicDataButton').click() # clickamos 'netejar' para limpiar formulario
$('#createNewEntryModal').modal 'show' # mostramos el modal
return false
# -----------------------------------------------------------
# Fijamos evento sobre el primer botón de borrar formularios
# -----------------------------------------------------------
$('#resetBasicDataButton').click ->
$('#candidateAliasList').html ''
$('#statusPanelModal').html ''
# ----------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Generar alias candidatos'
# ----------------------------------------------------------------
$('#generateCandidateAliasButton').click (event) ->
event.preventDefault()
$('#statusPanelModal').html ''
# Recogemos los campos del formulario
# ------------------------------------
brands = []
$('#form-group-brands-modal input[name="brand"]:checked').each (e) ->
brands.push $(this).val()
newEntry =
brands: brands
category: $('#basicDataNewEntryForm select[name="category"]').val()
_canonical_name: $('#basicDataNewEntryForm input[name="canonicalName"]').val()
# Validamos los campos
# ---------------------
if newEntry.brands.length == 0
setTimeout ( -> $('#brandError').html '' ), 1500
$('#brandError').html MyApp.templates.commonsModalFormValidation {message: 'Falta triar una <b>marca</b>'}
else if newEntry.category is null
setTimeout ( -> $('#categoryError').html '' ), 1500
$('#categoryError').html MyApp.templates.commonsModalFormValidation {message: 'Falta triar una <b>categoria</b>'}
else if newEntry._canonical_name is ''
setTimeout ( -> $('#canonicalNameError').html '' ), 1500
$('#canonicalNameError').html MyApp.templates.commonsModalFormValidation {message: 'Falta omplir el <b>nom canònic</b>'}
else
# ==============
# Validación OK
# ==============
$('#candidateAliasList').html '<img src="/img/rendering.gif">'
request = "/rest_dictionary_terms/alias/canonical_name/#{newEntry._canonical_name}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#candidateAliasList').html ''
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "Error: #{JSON.stringify data.error}"}
else
# =================
# Petición REST OK
# =================
candidate_alias = data.results
candidate_alias = candidate_alias.map (alias) -> {alias: alias}
html_content = MyApp.templates.listDictionaryCandidateAlias {candidate_alias: candidate_alias}
$('#candidateAliasList').html html_content
# ---------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Añadir alias a la lista'
# ---------------------------------------------------------------
$('#createNewEntryModal #addNewAliasButton').click (event) ->
event.preventDefault()
new_alias = $('#createNewEntryModal #addNewAliasForm input[name="newAlias"]').val()
new_alias = new_alias.trim()
if new_alias isnt '' and not /^\s+$/.test(new_alias)
# Chequeamos el nuevo alias
# --------------------------
is_correct = false
if new_alias[0] is '#' # si es hashtag
if /^#[a-z0-9_]+$/.test(new_alias)
is_correct = true
else
alert 'ERROR: HASHTAG INCORRECTE! Revisi que no contengui caràcters prohibits (espais, majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), i underscore (_).'
else
if /^[a-z0-9\s&]+$/.test(new_alias)
is_correct = true
new_alias = new_alias.trim().replace /\s+/g, ' '
else
alert 'ERROR: ALIAS INCORRECTE! Revisi que no contengui caràcters prohibits (majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), espais entre paraules, i umpersand (&).'
if is_correct
# Comprobamos si hay alias repetidos en la lista antes de seleccionar
# --------------------------------------------------------------------
current_alias = []
$('#createNewEntryModal #checkboxAliasListForm input[name="aliasCheckBox"]').each (e) ->
current_alias.push $(this).val()
if new_alias not in current_alias
$('#createNewEntryModal #saveButton').before "<div class=\"checkbox\"><label><input type=\"checkbox\" class=\"check\" name=\"aliasCheckBox\" value=\"#{new_alias}\"> <i>#{new_alias}</i></label></div>"
else
alert "ERROR: L'àlies '#{new_alias}' està repetit a la llista."
return false
# -------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Guardar nueva entrada'
# -------------------------------------------------------------
$('#createNewEntryModal #saveButton').click (event) ->
event.preventDefault()
# # Recogemos los datos de la nueva entrada (para el nombre canónico se debe coger el que se usó para generar los alias)
# # ----------------------------------------
# newEntry.brand = $('#basicDataNewEntryForm select[name="brand"]').val()
# Recogemos los brands seleccionados
# ----------------------------------
brands = []
$('#form-group-brands-modal input[name="brand"]:checked').each (e) ->
brands.push $(this).val()
# newEntry.brands = brands
newEntry.category = $('#basicDataNewEntryForm select[name="category"]').val()
# Comprobamos que no haya comas y semicolons en el nombre canónico
# -----------------------------------------------------------------
if /(,|;)/.test newEntry._canonical_name
alert "ERROR: El nom canònic no pot contenir comes (,) o semicolons (;).\nEsborri'ls i tornar a clickar 'Generar àlies candidats' i a seleccionar els àlies."
else
# Recogemos los alias seleccionados
# ----------------------------------
alias = []
$('#createNewEntryModal #checkboxAliasListForm input[name="aliasCheckBox"]:checked').each (e) ->
alias.push $(this).val()
# Comprobamos que no hay alias solapados entre ellos
# ---------------------------------------------------
hay_solapados = false
ngrams = alias.filter (x) -> x[0] isnt '#'
for x in ngrams
for y in ngrams
if x isnt y
if x in y.split /\s+/
alert "ERROR: L'àlies '#{x}' està contingut dins '#{y}'. Descarti algun dels dos."
hay_solapados = true
break
if not hay_solapados
# Eliminamos posibles duplicados
# -------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
newEntry.alias = uniqueAlias
newEntryConfirmed = confirm "Validació de regles OK!\n\n" + "Marca = #{newEntry.brands}\nCategoria = #{newEntry.category}\nNom canònic = #{newEntry._canonical_name}\nAlias = #{newEntry.alias.join(', ')}\n\nVol GUARDAR la nova entrada?"
if newEntryConfirmed
# ==============
# Validación OK
# ==============
# Guardamos nuevas entradas en MongoDB
# ------------------------------------
for brand in brands
newEntry.brand = brand
$.ajax({
url: '/rest_dictionary_terms/entries',
type: "POST",
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(newEntry),
error: (jqXHR) -> console.log "Ajax error: " + jqXHR.status
}).done (result) ->
# --------------------------------------------
# Procesamos el resultado de la petición POST
# --------------------------------------------
if result.ok?
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'success', glyphicon: 'ok', message: "Entrada creada correctament."}
# Mostramos la entrada insertada
# -------------------------------
$('#resetSearchButton').click() # limpiamos formulario de búsqueda del documento general
$('#dictionaryTable').html ''
$('#statusPanel').html ''
request = "/rest_dictionary_terms/entries/id/#{result.id}"
# getDictionaryEntriesAndRenderTable request
setTimeout ( ->
$('#createNewEntryModal').modal 'hide'
), 1000
else if result.error?
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "Error: #{result.error}"}
else
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "No s'ha pogut guardar la nova entrada."}
# # ------------------------------------------
# # Fijamos evento al hacer chek en Select All
# # ------------------------------------------
# $('#checkAll').click (event) ->
# event.preventDefault()
# $('.check').prop 'checked', $(this).prop('checked')
# Ocultaciones al inicio
# -----------------------
$('#statusPanel').html ''
$('#dictionaryTable').html ''
) jQuery | true | # =========================================
# Autor: PI:NAME:<NAME>END_PI (Fundació Bit), 2016
# =========================================
(($) ->
g_entries = [] # var global con la lista de entradas que servirá para refrescar después de borrar una entrada
# Función para extraer las marcas de la REST y renderizar resultados
# ------------------------------------------------------------------
getBrands = () ->
brand_list = []
request = "/rest_utils/brands"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
data.results.forEach (brand) ->
brand_list.push({'value': brand, 'name': brand.charAt(0).toUpperCase() + brand.slice(1)})
html_content = MyApp.templates.selectBrands {entries: brand_list, all_brands: true, label: true }
$('#form-group-brands').html html_content
html_content = MyApp.templates.selectBrandsModal {entries: brand_list, all_brands: true, label: true }
$('#form-group-brands-modal').html html_content
# Extraer las marcas de la REST y renderizar resultados
# -----------------------------------------------------
getBrands()
# =======================================================================================
# EVENTOS SOBRE COLUMNAS DE LA TABLA DE ENTRADAS
# =======================================================================================
setEventsOnEntriesTable = ->
# --------------------------------------
# Fijamos evento sobre columna de alias
# --------------------------------------
$('td.updateAlias').click ->
myid = $(this).attr('id')
myCanonicalName = $(this).attr('name')
mytext = $(this).text()
alias = (al.trim() for al in mytext.split(','))
$('#updateAliasList').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant...</p>'
$('#updateAliasModal').modal 'show' # mostramos el modal
setTimeout ( ->
# Eliminamos posibles duplicados
# -------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
# Descartamos alias que tienen caracteres extraños a una sublista en rojo
# ------------------------------------------------------------------------
discardedAlias = []
purgedAlias = []
uniqueAlias.forEach (al) ->
if al[0] is '#' # hashtag
if /^#[a-z0-9_]+$/.test(al) then purgedAlias.push(al) else discardedAlias.push(al)
else
if /^[a-z0-9\s&]+$/.test(al) then purgedAlias.push(al) else discardedAlias.push(al)
# Sacamos otros alias candidatos a partir del nombre canónico con la REST
# ------------------------------------------------------------------------
request = "/rest_dictionary_terms/alias/canonical_name/#{myCanonicalName}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#updateAliasList').html ''
alert "ERROR: #{JSON.stringify data.error}"
else
# =================
# Petición REST OK
# =================
restAlias = data.results
# Eliminamos posibles duplicados
# -------------------------------
otherCandidateAlias = []
restAlias.forEach (x) -> if x not in otherCandidateAlias then otherCandidateAlias.push x
# Formateamos para pintar el template
# ------------------------------------
discardedAlias = discardedAlias.map (alias) -> {alias: alias}
purgedAlias = purgedAlias.map (alias) -> {alias: alias}
otherCandidateAlias = otherCandidateAlias.map (alias) -> {alias: alias}
html_content = MyApp.templates.listDictionaryCandidateAlias {candidate_alias: purgedAlias, discarded_alias: discardedAlias, other_alias: otherCandidateAlias}
$('#updateAliasList').html html_content
# ---------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Añadir alias a la lista'
# ---------------------------------------------------------------
$('#updateAliasModal #addNewAliasButton').click (event) ->
event.preventDefault()
new_alias = $('#updateAliasModal #addNewAliasForm input[name="newAlias"]').val()
new_alias = new_alias.trim()
if new_alias isnt '' and not /^\s+$/.test(new_alias)
# Chequeamos el nuevo alias
# --------------------------
is_correct = false
if new_alias[0] is '#' # si es hashtag
if /^#[a-z0-9_]+$/.test(new_alias)
is_correct = true
else
alert 'ERROR: HASHTAG INCORRECTE! Revisi que no contengui caràcters prohibits (espais, majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), i underscore (_).'
else
if /^[a-z0-9\s&]+$/.test(new_alias)
is_correct = true
new_alias = new_alias.trim().replace /\s+/g, ' '
else
alert 'ERROR: ALIAS INCORRECTE! Revisi que no contengui caràcters prohibits (majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), espais entre paraules, i umpersand (&).'
if is_correct
# Comprobamos si hay alias repetidos en la lista antes de seleccionar
# --------------------------------------------------------------------
current_alias = []
$('#updateAliasModal #checkboxAliasListForm input[name="aliasCheckBox"]').each (e) ->
current_alias.push $(this).val()
if new_alias not in current_alias
$('#updateAliasModal #saveButton').before "<div class=\"checkbox\"><label><input type=\"checkbox\" class=\"check\" name=\"aliasCheckBox\" value=\"#{new_alias}\"> <i>#{new_alias}</i></label></div>"
else
alert "ERROR: L'àlies '#{new_alias}' està repetit a la llista."
return false
# -----------------------------------------------
# Modal: Fijamos evento sobre botón de 'Guardar'
# -----------------------------------------------
$('#updateAliasModal #saveButton').click (event) ->
event.preventDefault()
# Recogemos los alias seleccionados
# ----------------------------------
alias = []
$('#updateAliasModal #checkboxAliasListForm input[name="aliasCheckBox"]:checked').each (e) ->
alias.push $(this).val()
# Eliminamos posibles duplicados de la selección
# -----------------------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
if uniqueAlias.length is 0
alert "ERROR: No ha escollit cap àlies de la llista!"
else
# Comprobamos que no hay alias solapados entre ellos
# ---------------------------------------------------
hay_solapados = false
ngrams = uniqueAlias.filter (x) -> x[0] isnt '#'
for x in ngrams
for y in ngrams
if x isnt y
if x in y.split /\s+/
alert "ERROR: L'àlies '#{x}' està contingut dins '#{y}'. Descarti algun dels dos."
hay_solapados = true
break
if not hay_solapados
updateConfirmed = confirm "Validació de regles OK!\n\n" + "Nous àlies = #{uniqueAlias.join(', ')}\n\nVol MODIFICAR l'entrada?"
if updateConfirmed
# ==============
# Validación OK
# ==============
request = "/rest_dictionary_terms/entries/id/#{myid}"
$.ajax({
url: request,
type: "PUT",
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify({updatedAlias: uniqueAlias}),
error: (jqXHR) -> console.log "Ajax error: " + jqXHR.status
}).done (data) ->
# -------------------------------------------
# Procesamos el resultado de la petición PUT
# -------------------------------------------
if data.error?
alert "ERROR: #{JSON.stringify data.error}"
else
# alert "#{data.results}"
# Cerramos modal
# ---------------
$('#updateAliasModal').modal 'hide'
# Actualizamos columna
# ---------------------
$("td.updateAlias[id=\"#{myid}\"]").css "background-color", "#ddffdd"
$("td.updateAlias[id=\"#{myid}\"]").html "<i>#{uniqueAlias.join ', '}</i>"
return false
), 600 # cierra el timeout
# ---------------------------------------
# Fijamos evento sobre columna de status
# ---------------------------------------
$('td.updateStatus').click ->
myid = $(this).attr('id')
mystatus = $(this).text()
# cambiamos el estado como un interruptor on/off (PENDENT o vacío)
# -----------------------------------------------------------------
change_status = false
if mystatus is 'PENDENT'
changeConfirmed = confirm "Vol llevar l'estat 'PENDENT' d'aquesta entrada?"
if changeConfirmed
change_status = true
newstatus = 'none' # cualquier cosa distinta de 'PENDENT' sirve para borrar el estado
else
changeConfirmed = confirm "Vol posar l'estat a 'PENDENT' per aquesta entrada?"
if changeConfirmed
change_status = true
newstatus = 'PENDENT'
if change_status
request = "/rest_dictionary_terms/entries/id/#{myid}/status/#{newstatus}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
alert data.error
else
# =================
# Petición REST OK
# =================
# Modificamos el valor de la columna de la tabla
# -----------------------------------------------
if newstatus is 'none' then newstatus = ''
$("td.updateStatus[id=\"#{myid}\"]").html "<span class=\"label label-danger\">#{newstatus}</span>"
return false
# ------------------------------------------------
# Fijamos evento sobre columna de borrar entradas
# ------------------------------------------------
$('td.remove a').click ->
entryIdToDelete = $(this).attr('href')
acceptClicked = confirm "Segur que vol esborrar l'entrada?"
if acceptClicked then deleteDictionaryEntry entryIdToDelete
return false
# =====================================================================================
# DELETE DE ENTRADAS
# =====================================================================================
# ------------------------------------------------
# Función para borrar una entrada del diccionario
# ------------------------------------------------
deleteDictionaryEntry = (id) ->
request = "/rest_dictionary_terms/entries/delete/id/#{id}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
alert data.error
else
# =================
# Petición REST OK
# =================
# refrescamos la tabla de entradas
# ---------------------------------
$('#statusPanel').html ''
g_entries = g_entries.filter (x) -> x._id isnt id
if g_entries.length > 0
html_content = MyApp.templates.dictionaryTable {total_entries: g_entries.length, entries: g_entries}
$('#dictionaryTable').html html_content
setEventsOnEntriesTable()
else
$('#dictionaryTable').html ''
# =====================================================================================
# BÚSQUEDA (SEARCH) DE ENTRADAS
# =====================================================================================
# ---------------------------------------------------------------------------------
# Función para extraer entradas del diccionario de la REST y renderizar resultados
# ---------------------------------------------------------------------------------
getDictionaryEntriesAndRenderTable = (request) ->
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#statusPanel').html MyApp.templates.commonsRestApiError {message: data.error}
else
# =================
# Petición REST OK
# =================
entries = data.results
entries.forEach (x) ->
x.brand = x.brand.toUpperCase()
x.category = x.category.toUpperCase()
x.alias = (al.trim() for al in x.alias.split(',')).join ', '
if not x.status? then x.status = ''
g_entries = entries # servirá para refrescar después de borrar una entrada
setTimeout ( ->
# -------------------
# Renderizamos tabla
# -------------------
html_content = MyApp.templates.dictionaryTable {total_entries: entries.length, entries: entries}
$('#dictionaryTable').html html_content
$('#statusPanel').html ''
setEventsOnEntriesTable()
), 600
$('#statusPanel').html '<br><br><br><p align="center"><img src="/img/rendering.gif"> Carregant...</p>'
# -------------------------------------
# Fijamos evento sobre botón de Buscar
# -------------------------------------
$('#searchButton').click ->
categoria = $('#searchForm select[name="category"]').val()
marca = $('#searchForm select[name="brand"]').val()
# controlamos visibilidad de elementos
# -------------------------------------
$('#dictionaryTable').html ''
$('#statusPanel').html ''
# Petición REST
# --------------
request = "/rest_dictionary_terms/entries/category/#{categoria}/brand/#{marca}"
getDictionaryEntriesAndRenderTable request
return false
# =====================================================================================
# MODAL DE NUEVAS ENTRADAS
# =====================================================================================
# ----------------------------------------------
# Fijamos evento sobre botón de 'Crear entrada'
# ----------------------------------------------
$('#createButton').click ->
$('#resetBasicDataButton').click() # clickamos 'netejar' para limpiar formulario
$('#createNewEntryModal').modal 'show' # mostramos el modal
return false
# -----------------------------------------------------------
# Fijamos evento sobre el primer botón de borrar formularios
# -----------------------------------------------------------
$('#resetBasicDataButton').click ->
$('#candidateAliasList').html ''
$('#statusPanelModal').html ''
# ----------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Generar alias candidatos'
# ----------------------------------------------------------------
$('#generateCandidateAliasButton').click (event) ->
event.preventDefault()
$('#statusPanelModal').html ''
# Recogemos los campos del formulario
# ------------------------------------
brands = []
$('#form-group-brands-modal input[name="brand"]:checked').each (e) ->
brands.push $(this).val()
newEntry =
brands: brands
category: $('#basicDataNewEntryForm select[name="category"]').val()
_canonical_name: $('#basicDataNewEntryForm input[name="canonicalName"]').val()
# Validamos los campos
# ---------------------
if newEntry.brands.length == 0
setTimeout ( -> $('#brandError').html '' ), 1500
$('#brandError').html MyApp.templates.commonsModalFormValidation {message: 'Falta triar una <b>marca</b>'}
else if newEntry.category is null
setTimeout ( -> $('#categoryError').html '' ), 1500
$('#categoryError').html MyApp.templates.commonsModalFormValidation {message: 'Falta triar una <b>categoria</b>'}
else if newEntry._canonical_name is ''
setTimeout ( -> $('#canonicalNameError').html '' ), 1500
$('#canonicalNameError').html MyApp.templates.commonsModalFormValidation {message: 'Falta omplir el <b>nom canònic</b>'}
else
# ==============
# Validación OK
# ==============
$('#candidateAliasList').html '<img src="/img/rendering.gif">'
request = "/rest_dictionary_terms/alias/canonical_name/#{newEntry._canonical_name}"
$.ajax({url: request, type: "GET"})
.done (data) ->
# Chequeamos si la REST ha devuelto un error
# -------------------------------------------
if data.error?
$('#candidateAliasList').html ''
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "Error: #{JSON.stringify data.error}"}
else
# =================
# Petición REST OK
# =================
candidate_alias = data.results
candidate_alias = candidate_alias.map (alias) -> {alias: alias}
html_content = MyApp.templates.listDictionaryCandidateAlias {candidate_alias: candidate_alias}
$('#candidateAliasList').html html_content
# ---------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Añadir alias a la lista'
# ---------------------------------------------------------------
$('#createNewEntryModal #addNewAliasButton').click (event) ->
event.preventDefault()
new_alias = $('#createNewEntryModal #addNewAliasForm input[name="newAlias"]').val()
new_alias = new_alias.trim()
if new_alias isnt '' and not /^\s+$/.test(new_alias)
# Chequeamos el nuevo alias
# --------------------------
is_correct = false
if new_alias[0] is '#' # si es hashtag
if /^#[a-z0-9_]+$/.test(new_alias)
is_correct = true
else
alert 'ERROR: HASHTAG INCORRECTE! Revisi que no contengui caràcters prohibits (espais, majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), i underscore (_).'
else
if /^[a-z0-9\s&]+$/.test(new_alias)
is_correct = true
new_alias = new_alias.trim().replace /\s+/g, ' '
else
alert 'ERROR: ALIAS INCORRECTE! Revisi que no contengui caràcters prohibits (majúscules, accents, signes de puntuació). GUIA: Sols es permeten caràcters alfanumèrics [a-z] i [0-9] (sense ñ), espais entre paraules, i umpersand (&).'
if is_correct
# Comprobamos si hay alias repetidos en la lista antes de seleccionar
# --------------------------------------------------------------------
current_alias = []
$('#createNewEntryModal #checkboxAliasListForm input[name="aliasCheckBox"]').each (e) ->
current_alias.push $(this).val()
if new_alias not in current_alias
$('#createNewEntryModal #saveButton').before "<div class=\"checkbox\"><label><input type=\"checkbox\" class=\"check\" name=\"aliasCheckBox\" value=\"#{new_alias}\"> <i>#{new_alias}</i></label></div>"
else
alert "ERROR: L'àlies '#{new_alias}' està repetit a la llista."
return false
# -------------------------------------------------------------
# Modal: Fijamos evento sobre botón de 'Guardar nueva entrada'
# -------------------------------------------------------------
$('#createNewEntryModal #saveButton').click (event) ->
event.preventDefault()
# # Recogemos los datos de la nueva entrada (para el nombre canónico se debe coger el que se usó para generar los alias)
# # ----------------------------------------
# newEntry.brand = $('#basicDataNewEntryForm select[name="brand"]').val()
# Recogemos los brands seleccionados
# ----------------------------------
brands = []
$('#form-group-brands-modal input[name="brand"]:checked').each (e) ->
brands.push $(this).val()
# newEntry.brands = brands
newEntry.category = $('#basicDataNewEntryForm select[name="category"]').val()
# Comprobamos que no haya comas y semicolons en el nombre canónico
# -----------------------------------------------------------------
if /(,|;)/.test newEntry._canonical_name
alert "ERROR: El nom canònic no pot contenir comes (,) o semicolons (;).\nEsborri'ls i tornar a clickar 'Generar àlies candidats' i a seleccionar els àlies."
else
# Recogemos los alias seleccionados
# ----------------------------------
alias = []
$('#createNewEntryModal #checkboxAliasListForm input[name="aliasCheckBox"]:checked').each (e) ->
alias.push $(this).val()
# Comprobamos que no hay alias solapados entre ellos
# ---------------------------------------------------
hay_solapados = false
ngrams = alias.filter (x) -> x[0] isnt '#'
for x in ngrams
for y in ngrams
if x isnt y
if x in y.split /\s+/
alert "ERROR: L'àlies '#{x}' està contingut dins '#{y}'. Descarti algun dels dos."
hay_solapados = true
break
if not hay_solapados
# Eliminamos posibles duplicados
# -------------------------------
uniqueAlias = []
alias.forEach (x) -> if x not in uniqueAlias then uniqueAlias.push x
newEntry.alias = uniqueAlias
newEntryConfirmed = confirm "Validació de regles OK!\n\n" + "Marca = #{newEntry.brands}\nCategoria = #{newEntry.category}\nNom canònic = #{newEntry._canonical_name}\nAlias = #{newEntry.alias.join(', ')}\n\nVol GUARDAR la nova entrada?"
if newEntryConfirmed
# ==============
# Validación OK
# ==============
# Guardamos nuevas entradas en MongoDB
# ------------------------------------
for brand in brands
newEntry.brand = brand
$.ajax({
url: '/rest_dictionary_terms/entries',
type: "POST",
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(newEntry),
error: (jqXHR) -> console.log "Ajax error: " + jqXHR.status
}).done (result) ->
# --------------------------------------------
# Procesamos el resultado de la petición POST
# --------------------------------------------
if result.ok?
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'success', glyphicon: 'ok', message: "Entrada creada correctament."}
# Mostramos la entrada insertada
# -------------------------------
$('#resetSearchButton').click() # limpiamos formulario de búsqueda del documento general
$('#dictionaryTable').html ''
$('#statusPanel').html ''
request = "/rest_dictionary_terms/entries/id/#{result.id}"
# getDictionaryEntriesAndRenderTable request
setTimeout ( ->
$('#createNewEntryModal').modal 'hide'
), 1000
else if result.error?
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "Error: #{result.error}"}
else
$('#statusPanelModal').html MyApp.templates.commonsModalCreateNewEntry {state: 'danger', glyphicon: 'alert', message: "No s'ha pogut guardar la nova entrada."}
# # ------------------------------------------
# # Fijamos evento al hacer chek en Select All
# # ------------------------------------------
# $('#checkAll').click (event) ->
# event.preventDefault()
# $('.check').prop 'checked', $(this).prop('checked')
# Ocultaciones al inicio
# -----------------------
$('#statusPanel').html ''
$('#dictionaryTable').html ''
) jQuery |
[
{
"context": "l\n req.open method, url, true\n # FIXME <brian@wesabe.com>: 2008-03-11\n # <hack>\n # XULRunner 1.9",
"end": 2015,
"score": 0.9999262690544128,
"start": 1999,
"tag": "EMAIL",
"value": "brian@wesabe.com"
}
] | application/chrome/content/wesabe/io/xhr.coffee | wesabe/ssu | 28 | type = require 'lang/type'
func = require 'lang/func'
{sharedEventEmitter} = require 'events2'
{tryCatch, tryThrow} = require 'util/try'
xhr =
urlFor: (path, params) ->
return path unless params
url = path
qs = @encodeParams params
url += (if /\?/.test(url) then '&' else '?') + qs if qs.length
return url
encodeParams: (params) ->
("#{encodeURIComponent k}=#{encodeURIComponent v}" for own k, v of params when not type.isFunction v).join '&'
getUserAgent: ->
try
appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime)
runtime = appInfo.OS + " " + appInfo.XPCOMABI
catch ex
runtime = "unknown"
"Wesabe-ServerSideUploader/1.0 (#{runtime})"
request: (method, path, params, data, callback) ->
req = new XMLHttpRequest()
before = =>
# call `before' callback if it's given as a separate callback
func.executeCallback callback, 'before', [req] unless type.isFunction callback
sharedEventEmitter.emit 'before-xhr', req
after = =>
# call `after' callback if it's given as a separate callback
func.executeCallback callback, 'after', [req] unless type.isFunction callback
sharedEventEmitter.emit 'after-xhr', req
tryThrow "xhr(#{method} #{path})", (log) =>
if params and not (data or method.match(/get/i))
data = if type.isString params
params
else
@encodeParams params
params = null
contentType = "application/x-www-form-urlencoded"
url = @urlFor path, params
req.onreadystatechange = =>
log.debug 'readyState=', req.readyState
if req.readyState is 4
log.debug 'status=',req.status
wesabe.callback callback, req.status is 200, [req]
after()
req.onerror = (error) =>
log.error error
after()
log.debug 'url=', url
req.open method, url, true
# FIXME <brian@wesabe.com>: 2008-03-11
# <hack>
# XULRunner 1.9b3pre and 1.9b5pre insist on tacking on ";charset=utf-8" to whatever
# Content-type header you might set using setRequestHeader, which USAA balks at.
# To get around this you either have to pass in a DOMDocument or an nsIInputStream,
# so this part is only here to work around that limitation. See:
# https://bugzilla.mozilla.org/show_bug.cgi?id=382947
if type.isString data
stream = Cc['@mozilla.org/io/string-input-stream;1'].createInstance(Ci.nsIStringInputStream)
stream.setData data, data.length
data = stream
# </hack>
req.setRequestHeader "Content-Type", contentType if contentType
req.setRequestHeader "User-Agent", @getUserAgent()
req.setRequestHeader "Accept", "*/*, text/html"
before()
req.send data
return req
get: (path, params, block) ->
@request 'GET', path, params, null, block
post: (path, params, data, block) ->
@request 'POST', path, params, data, block
put: (path, params, data, block) ->
@request 'PUT', path, params, data, block
module.exports = xhr
| 77619 | type = require 'lang/type'
func = require 'lang/func'
{sharedEventEmitter} = require 'events2'
{tryCatch, tryThrow} = require 'util/try'
xhr =
urlFor: (path, params) ->
return path unless params
url = path
qs = @encodeParams params
url += (if /\?/.test(url) then '&' else '?') + qs if qs.length
return url
encodeParams: (params) ->
("#{encodeURIComponent k}=#{encodeURIComponent v}" for own k, v of params when not type.isFunction v).join '&'
getUserAgent: ->
try
appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime)
runtime = appInfo.OS + " " + appInfo.XPCOMABI
catch ex
runtime = "unknown"
"Wesabe-ServerSideUploader/1.0 (#{runtime})"
request: (method, path, params, data, callback) ->
req = new XMLHttpRequest()
before = =>
# call `before' callback if it's given as a separate callback
func.executeCallback callback, 'before', [req] unless type.isFunction callback
sharedEventEmitter.emit 'before-xhr', req
after = =>
# call `after' callback if it's given as a separate callback
func.executeCallback callback, 'after', [req] unless type.isFunction callback
sharedEventEmitter.emit 'after-xhr', req
tryThrow "xhr(#{method} #{path})", (log) =>
if params and not (data or method.match(/get/i))
data = if type.isString params
params
else
@encodeParams params
params = null
contentType = "application/x-www-form-urlencoded"
url = @urlFor path, params
req.onreadystatechange = =>
log.debug 'readyState=', req.readyState
if req.readyState is 4
log.debug 'status=',req.status
wesabe.callback callback, req.status is 200, [req]
after()
req.onerror = (error) =>
log.error error
after()
log.debug 'url=', url
req.open method, url, true
# FIXME <<EMAIL>>: 2008-03-11
# <hack>
# XULRunner 1.9b3pre and 1.9b5pre insist on tacking on ";charset=utf-8" to whatever
# Content-type header you might set using setRequestHeader, which USAA balks at.
# To get around this you either have to pass in a DOMDocument or an nsIInputStream,
# so this part is only here to work around that limitation. See:
# https://bugzilla.mozilla.org/show_bug.cgi?id=382947
if type.isString data
stream = Cc['@mozilla.org/io/string-input-stream;1'].createInstance(Ci.nsIStringInputStream)
stream.setData data, data.length
data = stream
# </hack>
req.setRequestHeader "Content-Type", contentType if contentType
req.setRequestHeader "User-Agent", @getUserAgent()
req.setRequestHeader "Accept", "*/*, text/html"
before()
req.send data
return req
get: (path, params, block) ->
@request 'GET', path, params, null, block
post: (path, params, data, block) ->
@request 'POST', path, params, data, block
put: (path, params, data, block) ->
@request 'PUT', path, params, data, block
module.exports = xhr
| true | type = require 'lang/type'
func = require 'lang/func'
{sharedEventEmitter} = require 'events2'
{tryCatch, tryThrow} = require 'util/try'
xhr =
urlFor: (path, params) ->
return path unless params
url = path
qs = @encodeParams params
url += (if /\?/.test(url) then '&' else '?') + qs if qs.length
return url
encodeParams: (params) ->
("#{encodeURIComponent k}=#{encodeURIComponent v}" for own k, v of params when not type.isFunction v).join '&'
getUserAgent: ->
try
appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime)
runtime = appInfo.OS + " " + appInfo.XPCOMABI
catch ex
runtime = "unknown"
"Wesabe-ServerSideUploader/1.0 (#{runtime})"
request: (method, path, params, data, callback) ->
req = new XMLHttpRequest()
before = =>
# call `before' callback if it's given as a separate callback
func.executeCallback callback, 'before', [req] unless type.isFunction callback
sharedEventEmitter.emit 'before-xhr', req
after = =>
# call `after' callback if it's given as a separate callback
func.executeCallback callback, 'after', [req] unless type.isFunction callback
sharedEventEmitter.emit 'after-xhr', req
tryThrow "xhr(#{method} #{path})", (log) =>
if params and not (data or method.match(/get/i))
data = if type.isString params
params
else
@encodeParams params
params = null
contentType = "application/x-www-form-urlencoded"
url = @urlFor path, params
req.onreadystatechange = =>
log.debug 'readyState=', req.readyState
if req.readyState is 4
log.debug 'status=',req.status
wesabe.callback callback, req.status is 200, [req]
after()
req.onerror = (error) =>
log.error error
after()
log.debug 'url=', url
req.open method, url, true
# FIXME <PI:EMAIL:<EMAIL>END_PI>: 2008-03-11
# <hack>
# XULRunner 1.9b3pre and 1.9b5pre insist on tacking on ";charset=utf-8" to whatever
# Content-type header you might set using setRequestHeader, which USAA balks at.
# To get around this you either have to pass in a DOMDocument or an nsIInputStream,
# so this part is only here to work around that limitation. See:
# https://bugzilla.mozilla.org/show_bug.cgi?id=382947
if type.isString data
stream = Cc['@mozilla.org/io/string-input-stream;1'].createInstance(Ci.nsIStringInputStream)
stream.setData data, data.length
data = stream
# </hack>
req.setRequestHeader "Content-Type", contentType if contentType
req.setRequestHeader "User-Agent", @getUserAgent()
req.setRequestHeader "Accept", "*/*, text/html"
before()
req.send data
return req
get: (path, params, block) ->
@request 'GET', path, params, null, block
post: (path, params, data, block) ->
@request 'POST', path, params, data, block
put: (path, params, data, block) ->
@request 'PUT', path, params, data, block
module.exports = xhr
|
[
{
"context": "ll\n created: ->\n this.users.push\n name: \"Takuya Tejima\"\n comment: \"次回の連載に乞うご期待。\"\n this.users.pus",
"end": 192,
"score": 0.9998050332069397,
"start": 179,
"tag": "NAME",
"value": "Takuya Tejima"
},
{
"context": ": \"次回の連載に乞うご期待。\"\n this.user... | src/coffee/main.coffee | Takushi-U/vue-practice | 0 | $ = require 'jQuery'
Vue = require 'vue'
vm = new Vue
el: "#app"
data:
searchText: ""
users: []
selectedUser: null
created: ->
this.users.push
name: "Takuya Tejima"
comment: "次回の連載に乞うご期待。"
this.users.push
name: "Daisuke Shimizu"
comment: "こんにちは。"
this.users.push
name: "Ryota Agata"
comment: "Vue.js嫌い。"
methods:
onClickUser: (user)->
this.selectedUser = user
# vm = new Vue
# el: "#app"
# data: {
# selected: false
# hasError: true
# isImportant: false
# users:[
# {
# name: "hoge"
# email: "hoge@email.com",
# }
# {
# name: "huga"
# email: "hoge@email.com"
# }
# ]}
# clickvm = new Vue
# el: "#app"
# data:
# [{
# user: "takushi"
# birthDay: "1989/09/30"
# id: 2
# }
# {
# user: "takushi"
# birthDay: "1989/09/30"
# id: 1
# }]
# methods:
# submit: ->
# this.addUser()
# console.log(this[0])
# addUser: ->
# this.$add('hobby', {value: "haiku"})
# computed:
# oDouble:->
# return this[0].id * 2
# oPlus:
# get: ->
# return this[1].id + 1
# $.ajax
# type: "GET"
# data: "josn"
# url: "/api/test_get.json"
# success: (data)->
# console.log(data[0])
# clickvm = new Vue
# el: "#app"
# data:
# [{
# user: "takushi"
# birthDay: "1989/09/30"
# id: 2
# }
# {
# user: "takushi"
# birthDay: "1989/09/30"
# id: 1
# }]
# methods:
# submit: ->
# this.addUser()
# console.log(this[0])
# addUser: ->
# this.$add('hobby', {value: "haiku"})
# computed:
# oDouble:->
# return this[0].id * 2
# oPlus:
# get: ->
# return this[1].id + 1
# created: ->
# console.log this.$el #-> null
# ready: ->
# console.log this.$el #-> DOMが帰って来る。
# **ディレクティブ**
# vm = new Vue
# el: "#app"
# data:
# msg: "hi!"
# chechked: true
# picked: "one"
# selected: "two"
# selected: "a"
# myOptions:
# [{
# text: "A"
# value: "a"
# }
# {
# text: "B"
# value: "b"
# }]
| 115692 | $ = require 'jQuery'
Vue = require 'vue'
vm = new Vue
el: "#app"
data:
searchText: ""
users: []
selectedUser: null
created: ->
this.users.push
name: "<NAME>"
comment: "次回の連載に乞うご期待。"
this.users.push
name: "<NAME>"
comment: "こんにちは。"
this.users.push
name: "<NAME>"
comment: "Vue.js嫌い。"
methods:
onClickUser: (user)->
this.selectedUser = user
# vm = new Vue
# el: "#app"
# data: {
# selected: false
# hasError: true
# isImportant: false
# users:[
# {
# name: "<NAME>"
# email: "<EMAIL>",
# }
# {
# name: "<NAME>"
# email: "<EMAIL>"
# }
# ]}
# clickvm = new Vue
# el: "#app"
# data:
# [{
# user: "takushi"
# birthDay: "1989/09/30"
# id: 2
# }
# {
# user: "takushi"
# birthDay: "1989/09/30"
# id: 1
# }]
# methods:
# submit: ->
# this.addUser()
# console.log(this[0])
# addUser: ->
# this.$add('hobby', {value: "haiku"})
# computed:
# oDouble:->
# return this[0].id * 2
# oPlus:
# get: ->
# return this[1].id + 1
# $.ajax
# type: "GET"
# data: "josn"
# url: "/api/test_get.json"
# success: (data)->
# console.log(data[0])
# clickvm = new Vue
# el: "#app"
# data:
# [{
# user: "takushi"
# birthDay: "1989/09/30"
# id: 2
# }
# {
# user: "takushi"
# birthDay: "1989/09/30"
# id: 1
# }]
# methods:
# submit: ->
# this.addUser()
# console.log(this[0])
# addUser: ->
# this.$add('hobby', {value: "haiku"})
# computed:
# oDouble:->
# return this[0].id * 2
# oPlus:
# get: ->
# return this[1].id + 1
# created: ->
# console.log this.$el #-> null
# ready: ->
# console.log this.$el #-> DOMが帰って来る。
# **ディレクティブ**
# vm = new Vue
# el: "#app"
# data:
# msg: "hi!"
# chechked: true
# picked: "one"
# selected: "two"
# selected: "a"
# myOptions:
# [{
# text: "A"
# value: "a"
# }
# {
# text: "B"
# value: "b"
# }]
| true | $ = require 'jQuery'
Vue = require 'vue'
vm = new Vue
el: "#app"
data:
searchText: ""
users: []
selectedUser: null
created: ->
this.users.push
name: "PI:NAME:<NAME>END_PI"
comment: "次回の連載に乞うご期待。"
this.users.push
name: "PI:NAME:<NAME>END_PI"
comment: "こんにちは。"
this.users.push
name: "PI:NAME:<NAME>END_PI"
comment: "Vue.js嫌い。"
methods:
onClickUser: (user)->
this.selectedUser = user
# vm = new Vue
# el: "#app"
# data: {
# selected: false
# hasError: true
# isImportant: false
# users:[
# {
# name: "PI:NAME:<NAME>END_PI"
# email: "PI:EMAIL:<EMAIL>END_PI",
# }
# {
# name: "PI:NAME:<NAME>END_PI"
# email: "PI:EMAIL:<EMAIL>END_PI"
# }
# ]}
# clickvm = new Vue
# el: "#app"
# data:
# [{
# user: "takushi"
# birthDay: "1989/09/30"
# id: 2
# }
# {
# user: "takushi"
# birthDay: "1989/09/30"
# id: 1
# }]
# methods:
# submit: ->
# this.addUser()
# console.log(this[0])
# addUser: ->
# this.$add('hobby', {value: "haiku"})
# computed:
# oDouble:->
# return this[0].id * 2
# oPlus:
# get: ->
# return this[1].id + 1
# $.ajax
# type: "GET"
# data: "josn"
# url: "/api/test_get.json"
# success: (data)->
# console.log(data[0])
# clickvm = new Vue
# el: "#app"
# data:
# [{
# user: "takushi"
# birthDay: "1989/09/30"
# id: 2
# }
# {
# user: "takushi"
# birthDay: "1989/09/30"
# id: 1
# }]
# methods:
# submit: ->
# this.addUser()
# console.log(this[0])
# addUser: ->
# this.$add('hobby', {value: "haiku"})
# computed:
# oDouble:->
# return this[0].id * 2
# oPlus:
# get: ->
# return this[1].id + 1
# created: ->
# console.log this.$el #-> null
# ready: ->
# console.log this.$el #-> DOMが帰って来る。
# **ディレクティブ**
# vm = new Vue
# el: "#app"
# data:
# msg: "hi!"
# chechked: true
# picked: "one"
# selected: "two"
# selected: "a"
# myOptions:
# [{
# text: "A"
# value: "a"
# }
# {
# text: "B"
# value: "b"
# }]
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9944522380828857,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/progNoteDetailView.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
# List component for historical entries (desc), concerning targets and data-revisions
Imm = require 'immutable'
_ = require 'underscore'
Term = require './term'
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
Mark = win.Mark
ProgEventWidget = require('./progEventWidget').load(win)
MetricWidget = require('./metricWidget').load(win)
RevisionHistory = require('./revisionHistory').load(win)
ColorKeyBubble = require('./colorKeyBubble').load(win)
{FaIcon, renderLineBreaks, showWhen, formatTimestamp} = require('./utils').load(win)
ProgNoteDetailView = React.createFactory React.createClass
displayName: 'ProgNoteDetailView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: -> {
descriptionVisibility: 'showingSome'
historyCount: 10
}
componentWillReceiveProps: (nextProps) ->
# Reset history count and scroll when targetId (or type) changes
oldTargetId = if @props.item then @props.item.get('targetId')
if nextProps.item and (nextProps.item.get('targetId') isnt oldTargetId)
@_resetHistoryCount()
if @refs.history? then @refs.history.resetScroll()
componentDidUpdate: (oldProps, oldState) ->
oldDescVis = oldState.descriptionVisibility
newDescVis = @state.descriptionVisibility
# Unfortunately necessary...
# Needed in order to determine if itemDescription's rendered height
# is big enough to warrant an "Expand" button
if oldDescVis isnt 'showingSome' and newDescVis is 'showingSome'
@forceUpdate()
unless Imm.is oldProps.item, @props.item
@forceUpdate()
_addHistoryCount: (count) ->
# Disregard if nothing left to load
return if @state.historyCount >= @props.progNoteHistories.size
historyCount = @state.historyCount + count
@setState {historyCount}
_resetHistoryCount: ->
@setState {historyCount: 10}
render: ->
{item, progNoteHistories, programsById, metricsById, progEvents, eventTypes} = @props
unless item
return R.div({className: 'progNoteDetailView'},
if progNoteHistories.size > 0
R.div({className: 'noSelection'},
"Select an entry on the left to see more information about it here."
)
)
switch item.get('type')
when 'progNote'
# First figure out which progNote history to diff through
progNoteHistory = progNoteHistories.find (progNoteHistory) ->
progNoteHistory.last().get('id') is item.get('progNoteId')
return R.div({className: 'progNoteDetailView'},
RevisionHistory({
revisions: progNoteHistory.reverse()
type: 'progNote'
disableSnapshot: true
metricsById
programsById
dataModelName: Term 'progress note'
terms: {
metric: Term 'metric'
metrics: Term 'metric'
}
})
)
when 'basicUnit'
unitId = item.get('unitId')
itemName = item.get('unitName')
entries = progNoteHistories.flatMap (progNoteHistory) ->
initialAuthor = progNoteHistory.first().get('authorDisplayName') or progNoteHistory.first().get('author')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
switch progNote.get('type')
when 'basic'
return Imm.List()
when 'full'
return progNote.get('units')
.filter (unit) => # find relevant units
return unit.get('id') is unitId
.map (unit) => # turn them into entries
matchingProgEvents = progEvents.filter (progEvent) =>
return progEvent.get('relatedProgNoteId') is progNote.get('id')
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
status: progNote.get('status')
progNoteId: progNote.get('id')
author: initialAuthor
timestamp: createdTimestamp
authorProgram
backdate: progNote.get('backdate')
notes: unit.get('notes')
progEvents: matchingProgEvents
}
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
when 'planSectionTarget'
unitId = item.get('unitId')
sectionId = item.get('sectionId')
targetId = item.get('targetId')
itemName = item.get('targetName')
itemDescription = item.get('targetDescription')
entries = progNoteHistories.flatMap (progNoteHistory) =>
initialAuthor = progNoteHistory.first().get('authorDisplayName') or progNoteHistory.first().get('author')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
switch progNote.get('type')
when 'basic'
return Imm.List()
when 'full'
return progNote.get('units')
.filter (unit) => # find relevant units
return unit.get('id') is unitId
.flatMap (unit) => # turn them into entries
return unit.get('sections').flatMap (section) =>
return section.get('targets')
.filter (target) => # find relevant targets
return target.get('id') is targetId
.map (target) =>
progNoteId = progNote.get('id')
matchingProgEvents = progEvents.filter (progEvent) ->
progEvent.get('relatedProgNoteId') is progNoteId
# Metric entry must have a value to display
metrics = target.get('metrics').filter (metric) -> metric.get('value')
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
progNoteId
status: progNote.get('status')
targetId: target.get('id')
author: initialAuthor
authorProgram
timestamp: createdTimestamp
backdate: progNote.get('backdate')
notes: target.get('notes')
progEvents: matchingProgEvents
metrics
}
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
when 'quickNote'
itemName = Term 'Quick Notes'
# Extract all quickNote entries
entries = progNoteHistories
.filter (progNoteHistory) -> progNoteHistory.last().get('type') is 'basic'
.map (progNoteHistory) =>
initialAuthor = progNoteHistory.first().get('authorDisplayName')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
progNoteId = progNote.get('id')
# TODO: progEvents = @props.progEvents.filter (progEvent) =>
# return progEvent.get('relatedProgNoteId') is progNoteId
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
progNoteId
status: progNote.get('status')
author: initialAuthor
authorProgram
timestamp: createdTimestamp
backdate: progNote.get('backdate')
notes: progNote.get('notes')
}
else
throw new Error "unknown item type: #{JSON.stringify item?.get('type')}"
# Filter out blank & cancelled notes, and sort by date/backdate
entries = entries
.filter (entry) ->
(entry.get('notes').trim().length > 0 or (entry.get('metrics')? and entry.get('metrics').size > 0)) and
entry.get('status') isnt 'cancelled'
.sortBy (entry) ->
entry.get('backdate') or entry.get('timestamp')
.reverse()
entriesCount = entries.size
entries = entries
.slice(0, @state.historyCount)
# Figure out next state in description visibility cycle
switch @state.descriptionVisibility
when 'hidden'
nextDescVis = 'showingSome'
when 'showingSome'
unless @refs.itemDescription
nextDescVis = 'hidden'
else if @refs.itemDescription.scrollHeight >= 130 # must match max-height used in CSS
nextDescVis = 'showingAll'
else
nextDescVis = 'hidden'
when 'showingAll'
nextDescVis = 'hidden'
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify @state.descriptionVisibility
)
return R.div({className: 'progNoteDetailView'},
R.div({className: 'itemDetails'},
R.div({
className: 'itemName'
onClick: => @setState {
descriptionVisibility: nextDescVis
}
},
R.h3({}, itemName)
(if itemDescription
R.div({className: 'toggleDescriptionButton'},
switch nextDescVis
when 'hidden'
"Hide"
when 'showingSome'
"Show"
when 'showingAll'
"Expand"
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify nextDescVis
)
" Description "
FaIcon('chevron-up', {
className: switch nextDescVis
when 'hidden'
'up'
when 'showingSome'
'down'
when 'showingAll'
'down'
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify nextDescVis
)
})
)
)
)
(if itemDescription
R.div({
className: 'itemDescription ' + @state.descriptionVisibility
ref: 'itemDescription'
},
renderLineBreaks itemDescription
)
)
)
History({
ref: 'history'
entries
entriesCount
eventTypes
historyCount: @state.historyCount
addHistoryCount: @_addHistoryCount
resetHistoryCount: @_resetHistoryCount
isFiltering: @props.isFiltering
searchQuery: @props.searchQuery
})
)
History = React.createFactory React.createClass
displayName: 'History'
mixins: [React.addons.PureRenderMixin]
componentDidMount: ->
historyPane = $('.history')
historyPane.on 'scroll', _.throttle((=>
if @props.historyCount < @props.entriesCount
if historyPane.scrollTop() + (historyPane.innerHeight() * 2) >= historyPane[0].scrollHeight
@props.addHistoryCount(10)
return
), 150)
# Draw highlighting first time if searchQuery exists
if @props.isFiltering and @props.searchQuery
$historyPane = new Mark findDOMNode @refs.history
$historyPane.unmark().mark @props.searchQuery
componentDidUpdate: (oldProps, oldState) ->
# Check to see if we need to redraw highlighting while in filter-mode
if @props.isFiltering
$historyPane = new Mark findDOMNode @refs.history
searchQueryChanged = @props.searchQuery isnt oldProps.searchQuery
if @props.searchQuery and (searchQueryChanged or @props.historyCount isnt oldProps.historyCount)
$historyPane.unmark().mark @props.searchQuery
else if not @props.searchQuery and searchQueryChanged
$historyPane.unmark()
resetScroll: ->
historyPane = $('.history')
historyPane.scrollTop(0)
render: ->
{entries, eventTypes} = @props
R.div({
ref: 'history'
className: 'history'
},
(entries.map (entry) =>
entryId = entry.get('progNoteId')
timestamp = entry.get('backdate') or entry.get('timestamp')
authorProgram = entry.get('authorProgram')
return R.div({
key: entryId
className: 'entry'
},
R.div({className: 'header'},
R.div({className: 'timestamp'},
formatTimestamp(timestamp)
(if authorProgram
ColorKeyBubble({
colorKeyHex: authorProgram.get('colorKeyHex')
popover: {
title: authorProgram.get('name')
content: authorProgram.get('description')
placement: 'left'
}
})
)
)
R.div({className: 'author'},
FaIcon('user')
entry.get('author')
)
)
unless entry.get('notes') is ''
R.div({className: 'notes'},
if entry.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks entry.get('notes').replace(/\*\*\*/g, '')
)
else
renderLineBreaks entry.get('notes')
)
if entry.get('metrics')
unless entry.get('metrics').size is 0
R.div({className: 'metrics'},
entry.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
)
if entry.get('progEvents')
unless entry.get('progEvents').isEmpty()
R.div({className: 'progEvents'},
entry.get('progEvents').map (progEvent) =>
ProgEventWidget({
key: progEvent.get('id')
format: 'small'
progEvent
eventTypes
})
)
)
).toJS()...
)
return ProgNoteDetailView
module.exports = {load}
| 214029 | # 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
# List component for historical entries (desc), concerning targets and data-revisions
Imm = require 'immutable'
_ = require 'underscore'
Term = require './term'
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
Mark = win.Mark
ProgEventWidget = require('./progEventWidget').load(win)
MetricWidget = require('./metricWidget').load(win)
RevisionHistory = require('./revisionHistory').load(win)
ColorKeyBubble = require('./colorKeyBubble').load(win)
{FaIcon, renderLineBreaks, showWhen, formatTimestamp} = require('./utils').load(win)
ProgNoteDetailView = React.createFactory React.createClass
displayName: 'ProgNoteDetailView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: -> {
descriptionVisibility: 'showingSome'
historyCount: 10
}
componentWillReceiveProps: (nextProps) ->
# Reset history count and scroll when targetId (or type) changes
oldTargetId = if @props.item then @props.item.get('targetId')
if nextProps.item and (nextProps.item.get('targetId') isnt oldTargetId)
@_resetHistoryCount()
if @refs.history? then @refs.history.resetScroll()
componentDidUpdate: (oldProps, oldState) ->
oldDescVis = oldState.descriptionVisibility
newDescVis = @state.descriptionVisibility
# Unfortunately necessary...
# Needed in order to determine if itemDescription's rendered height
# is big enough to warrant an "Expand" button
if oldDescVis isnt 'showingSome' and newDescVis is 'showingSome'
@forceUpdate()
unless Imm.is oldProps.item, @props.item
@forceUpdate()
_addHistoryCount: (count) ->
# Disregard if nothing left to load
return if @state.historyCount >= @props.progNoteHistories.size
historyCount = @state.historyCount + count
@setState {historyCount}
_resetHistoryCount: ->
@setState {historyCount: 10}
render: ->
{item, progNoteHistories, programsById, metricsById, progEvents, eventTypes} = @props
unless item
return R.div({className: 'progNoteDetailView'},
if progNoteHistories.size > 0
R.div({className: 'noSelection'},
"Select an entry on the left to see more information about it here."
)
)
switch item.get('type')
when 'progNote'
# First figure out which progNote history to diff through
progNoteHistory = progNoteHistories.find (progNoteHistory) ->
progNoteHistory.last().get('id') is item.get('progNoteId')
return R.div({className: 'progNoteDetailView'},
RevisionHistory({
revisions: progNoteHistory.reverse()
type: 'progNote'
disableSnapshot: true
metricsById
programsById
dataModelName: Term 'progress note'
terms: {
metric: Term 'metric'
metrics: Term 'metric'
}
})
)
when 'basicUnit'
unitId = item.get('unitId')
itemName = item.get('unitName')
entries = progNoteHistories.flatMap (progNoteHistory) ->
initialAuthor = progNoteHistory.first().get('authorDisplayName') or progNoteHistory.first().get('author')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
switch progNote.get('type')
when 'basic'
return Imm.List()
when 'full'
return progNote.get('units')
.filter (unit) => # find relevant units
return unit.get('id') is unitId
.map (unit) => # turn them into entries
matchingProgEvents = progEvents.filter (progEvent) =>
return progEvent.get('relatedProgNoteId') is progNote.get('id')
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
status: progNote.get('status')
progNoteId: progNote.get('id')
author: initialAuthor
timestamp: createdTimestamp
authorProgram
backdate: progNote.get('backdate')
notes: unit.get('notes')
progEvents: matchingProgEvents
}
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
when 'planSectionTarget'
unitId = item.get('unitId')
sectionId = item.get('sectionId')
targetId = item.get('targetId')
itemName = item.get('targetName')
itemDescription = item.get('targetDescription')
entries = progNoteHistories.flatMap (progNoteHistory) =>
initialAuthor = progNoteHistory.first().get('authorDisplayName') or progNoteHistory.first().get('author')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
switch progNote.get('type')
when 'basic'
return Imm.List()
when 'full'
return progNote.get('units')
.filter (unit) => # find relevant units
return unit.get('id') is unitId
.flatMap (unit) => # turn them into entries
return unit.get('sections').flatMap (section) =>
return section.get('targets')
.filter (target) => # find relevant targets
return target.get('id') is targetId
.map (target) =>
progNoteId = progNote.get('id')
matchingProgEvents = progEvents.filter (progEvent) ->
progEvent.get('relatedProgNoteId') is progNoteId
# Metric entry must have a value to display
metrics = target.get('metrics').filter (metric) -> metric.get('value')
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
progNoteId
status: progNote.get('status')
targetId: target.get('id')
author: initialAuthor
authorProgram
timestamp: createdTimestamp
backdate: progNote.get('backdate')
notes: target.get('notes')
progEvents: matchingProgEvents
metrics
}
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
when 'quickNote'
itemName = Term 'Quick Notes'
# Extract all quickNote entries
entries = progNoteHistories
.filter (progNoteHistory) -> progNoteHistory.last().get('type') is 'basic'
.map (progNoteHistory) =>
initialAuthor = progNoteHistory.first().get('authorDisplayName')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
progNoteId = progNote.get('id')
# TODO: progEvents = @props.progEvents.filter (progEvent) =>
# return progEvent.get('relatedProgNoteId') is progNoteId
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
progNoteId
status: progNote.get('status')
author: initialAuthor
authorProgram
timestamp: createdTimestamp
backdate: progNote.get('backdate')
notes: progNote.get('notes')
}
else
throw new Error "unknown item type: #{JSON.stringify item?.get('type')}"
# Filter out blank & cancelled notes, and sort by date/backdate
entries = entries
.filter (entry) ->
(entry.get('notes').trim().length > 0 or (entry.get('metrics')? and entry.get('metrics').size > 0)) and
entry.get('status') isnt 'cancelled'
.sortBy (entry) ->
entry.get('backdate') or entry.get('timestamp')
.reverse()
entriesCount = entries.size
entries = entries
.slice(0, @state.historyCount)
# Figure out next state in description visibility cycle
switch @state.descriptionVisibility
when 'hidden'
nextDescVis = 'showingSome'
when 'showingSome'
unless @refs.itemDescription
nextDescVis = 'hidden'
else if @refs.itemDescription.scrollHeight >= 130 # must match max-height used in CSS
nextDescVis = 'showingAll'
else
nextDescVis = 'hidden'
when 'showingAll'
nextDescVis = 'hidden'
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify @state.descriptionVisibility
)
return R.div({className: 'progNoteDetailView'},
R.div({className: 'itemDetails'},
R.div({
className: 'itemName'
onClick: => @setState {
descriptionVisibility: nextDescVis
}
},
R.h3({}, itemName)
(if itemDescription
R.div({className: 'toggleDescriptionButton'},
switch nextDescVis
when 'hidden'
"Hide"
when 'showingSome'
"Show"
when 'showingAll'
"Expand"
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify nextDescVis
)
" Description "
FaIcon('chevron-up', {
className: switch nextDescVis
when 'hidden'
'up'
when 'showingSome'
'down'
when 'showingAll'
'down'
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify nextDescVis
)
})
)
)
)
(if itemDescription
R.div({
className: 'itemDescription ' + @state.descriptionVisibility
ref: 'itemDescription'
},
renderLineBreaks itemDescription
)
)
)
History({
ref: 'history'
entries
entriesCount
eventTypes
historyCount: @state.historyCount
addHistoryCount: @_addHistoryCount
resetHistoryCount: @_resetHistoryCount
isFiltering: @props.isFiltering
searchQuery: @props.searchQuery
})
)
History = React.createFactory React.createClass
displayName: 'History'
mixins: [React.addons.PureRenderMixin]
componentDidMount: ->
historyPane = $('.history')
historyPane.on 'scroll', _.throttle((=>
if @props.historyCount < @props.entriesCount
if historyPane.scrollTop() + (historyPane.innerHeight() * 2) >= historyPane[0].scrollHeight
@props.addHistoryCount(10)
return
), 150)
# Draw highlighting first time if searchQuery exists
if @props.isFiltering and @props.searchQuery
$historyPane = new Mark findDOMNode @refs.history
$historyPane.unmark().mark @props.searchQuery
componentDidUpdate: (oldProps, oldState) ->
# Check to see if we need to redraw highlighting while in filter-mode
if @props.isFiltering
$historyPane = new Mark findDOMNode @refs.history
searchQueryChanged = @props.searchQuery isnt oldProps.searchQuery
if @props.searchQuery and (searchQueryChanged or @props.historyCount isnt oldProps.historyCount)
$historyPane.unmark().mark @props.searchQuery
else if not @props.searchQuery and searchQueryChanged
$historyPane.unmark()
resetScroll: ->
historyPane = $('.history')
historyPane.scrollTop(0)
render: ->
{entries, eventTypes} = @props
R.div({
ref: 'history'
className: 'history'
},
(entries.map (entry) =>
entryId = entry.get('progNoteId')
timestamp = entry.get('backdate') or entry.get('timestamp')
authorProgram = entry.get('authorProgram')
return R.div({
key: entryId
className: 'entry'
},
R.div({className: 'header'},
R.div({className: 'timestamp'},
formatTimestamp(timestamp)
(if authorProgram
ColorKeyBubble({
colorKeyHex: authorProgram.get('colorKeyHex')
popover: {
title: authorProgram.get('name')
content: authorProgram.get('description')
placement: 'left'
}
})
)
)
R.div({className: 'author'},
FaIcon('user')
entry.get('author')
)
)
unless entry.get('notes') is ''
R.div({className: 'notes'},
if entry.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks entry.get('notes').replace(/\*\*\*/g, '')
)
else
renderLineBreaks entry.get('notes')
)
if entry.get('metrics')
unless entry.get('metrics').size is 0
R.div({className: 'metrics'},
entry.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
)
if entry.get('progEvents')
unless entry.get('progEvents').isEmpty()
R.div({className: 'progEvents'},
entry.get('progEvents').map (progEvent) =>
ProgEventWidget({
key: progEvent.get('id')
format: 'small'
progEvent
eventTypes
})
)
)
).toJS()...
)
return ProgNoteDetailView
module.exports = {load}
| 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
# List component for historical entries (desc), concerning targets and data-revisions
Imm = require 'immutable'
_ = require 'underscore'
Term = require './term'
load = (win) ->
$ = win.jQuery
React = win.React
R = React.DOM
{findDOMNode} = win.ReactDOM
Mark = win.Mark
ProgEventWidget = require('./progEventWidget').load(win)
MetricWidget = require('./metricWidget').load(win)
RevisionHistory = require('./revisionHistory').load(win)
ColorKeyBubble = require('./colorKeyBubble').load(win)
{FaIcon, renderLineBreaks, showWhen, formatTimestamp} = require('./utils').load(win)
ProgNoteDetailView = React.createFactory React.createClass
displayName: 'ProgNoteDetailView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: -> {
descriptionVisibility: 'showingSome'
historyCount: 10
}
componentWillReceiveProps: (nextProps) ->
# Reset history count and scroll when targetId (or type) changes
oldTargetId = if @props.item then @props.item.get('targetId')
if nextProps.item and (nextProps.item.get('targetId') isnt oldTargetId)
@_resetHistoryCount()
if @refs.history? then @refs.history.resetScroll()
componentDidUpdate: (oldProps, oldState) ->
oldDescVis = oldState.descriptionVisibility
newDescVis = @state.descriptionVisibility
# Unfortunately necessary...
# Needed in order to determine if itemDescription's rendered height
# is big enough to warrant an "Expand" button
if oldDescVis isnt 'showingSome' and newDescVis is 'showingSome'
@forceUpdate()
unless Imm.is oldProps.item, @props.item
@forceUpdate()
_addHistoryCount: (count) ->
# Disregard if nothing left to load
return if @state.historyCount >= @props.progNoteHistories.size
historyCount = @state.historyCount + count
@setState {historyCount}
_resetHistoryCount: ->
@setState {historyCount: 10}
render: ->
{item, progNoteHistories, programsById, metricsById, progEvents, eventTypes} = @props
unless item
return R.div({className: 'progNoteDetailView'},
if progNoteHistories.size > 0
R.div({className: 'noSelection'},
"Select an entry on the left to see more information about it here."
)
)
switch item.get('type')
when 'progNote'
# First figure out which progNote history to diff through
progNoteHistory = progNoteHistories.find (progNoteHistory) ->
progNoteHistory.last().get('id') is item.get('progNoteId')
return R.div({className: 'progNoteDetailView'},
RevisionHistory({
revisions: progNoteHistory.reverse()
type: 'progNote'
disableSnapshot: true
metricsById
programsById
dataModelName: Term 'progress note'
terms: {
metric: Term 'metric'
metrics: Term 'metric'
}
})
)
when 'basicUnit'
unitId = item.get('unitId')
itemName = item.get('unitName')
entries = progNoteHistories.flatMap (progNoteHistory) ->
initialAuthor = progNoteHistory.first().get('authorDisplayName') or progNoteHistory.first().get('author')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
switch progNote.get('type')
when 'basic'
return Imm.List()
when 'full'
return progNote.get('units')
.filter (unit) => # find relevant units
return unit.get('id') is unitId
.map (unit) => # turn them into entries
matchingProgEvents = progEvents.filter (progEvent) =>
return progEvent.get('relatedProgNoteId') is progNote.get('id')
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
status: progNote.get('status')
progNoteId: progNote.get('id')
author: initialAuthor
timestamp: createdTimestamp
authorProgram
backdate: progNote.get('backdate')
notes: unit.get('notes')
progEvents: matchingProgEvents
}
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
when 'planSectionTarget'
unitId = item.get('unitId')
sectionId = item.get('sectionId')
targetId = item.get('targetId')
itemName = item.get('targetName')
itemDescription = item.get('targetDescription')
entries = progNoteHistories.flatMap (progNoteHistory) =>
initialAuthor = progNoteHistory.first().get('authorDisplayName') or progNoteHistory.first().get('author')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
switch progNote.get('type')
when 'basic'
return Imm.List()
when 'full'
return progNote.get('units')
.filter (unit) => # find relevant units
return unit.get('id') is unitId
.flatMap (unit) => # turn them into entries
return unit.get('sections').flatMap (section) =>
return section.get('targets')
.filter (target) => # find relevant targets
return target.get('id') is targetId
.map (target) =>
progNoteId = progNote.get('id')
matchingProgEvents = progEvents.filter (progEvent) ->
progEvent.get('relatedProgNoteId') is progNoteId
# Metric entry must have a value to display
metrics = target.get('metrics').filter (metric) -> metric.get('value')
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
progNoteId
status: progNote.get('status')
targetId: target.get('id')
author: initialAuthor
authorProgram
timestamp: createdTimestamp
backdate: progNote.get('backdate')
notes: target.get('notes')
progEvents: matchingProgEvents
metrics
}
else
throw new Error "unknown prognote type: #{progNote.get('type')}"
when 'quickNote'
itemName = Term 'Quick Notes'
# Extract all quickNote entries
entries = progNoteHistories
.filter (progNoteHistory) -> progNoteHistory.last().get('type') is 'basic'
.map (progNoteHistory) =>
initialAuthor = progNoteHistory.first().get('authorDisplayName')
createdTimestamp = progNoteHistory.first().get('timestamp')
progNote = progNoteHistory.last()
progNoteId = progNote.get('id')
# TODO: progEvents = @props.progEvents.filter (progEvent) =>
# return progEvent.get('relatedProgNoteId') is progNoteId
authorProgram = programsById.get progNote.get('authorProgramId')
return Imm.fromJS {
progNoteId
status: progNote.get('status')
author: initialAuthor
authorProgram
timestamp: createdTimestamp
backdate: progNote.get('backdate')
notes: progNote.get('notes')
}
else
throw new Error "unknown item type: #{JSON.stringify item?.get('type')}"
# Filter out blank & cancelled notes, and sort by date/backdate
entries = entries
.filter (entry) ->
(entry.get('notes').trim().length > 0 or (entry.get('metrics')? and entry.get('metrics').size > 0)) and
entry.get('status') isnt 'cancelled'
.sortBy (entry) ->
entry.get('backdate') or entry.get('timestamp')
.reverse()
entriesCount = entries.size
entries = entries
.slice(0, @state.historyCount)
# Figure out next state in description visibility cycle
switch @state.descriptionVisibility
when 'hidden'
nextDescVis = 'showingSome'
when 'showingSome'
unless @refs.itemDescription
nextDescVis = 'hidden'
else if @refs.itemDescription.scrollHeight >= 130 # must match max-height used in CSS
nextDescVis = 'showingAll'
else
nextDescVis = 'hidden'
when 'showingAll'
nextDescVis = 'hidden'
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify @state.descriptionVisibility
)
return R.div({className: 'progNoteDetailView'},
R.div({className: 'itemDetails'},
R.div({
className: 'itemName'
onClick: => @setState {
descriptionVisibility: nextDescVis
}
},
R.h3({}, itemName)
(if itemDescription
R.div({className: 'toggleDescriptionButton'},
switch nextDescVis
when 'hidden'
"Hide"
when 'showingSome'
"Show"
when 'showingAll'
"Expand"
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify nextDescVis
)
" Description "
FaIcon('chevron-up', {
className: switch nextDescVis
when 'hidden'
'up'
when 'showingSome'
'down'
when 'showingAll'
'down'
else
throw new Error(
'unknown descriptionVisibility ' +
JSON.stringify nextDescVis
)
})
)
)
)
(if itemDescription
R.div({
className: 'itemDescription ' + @state.descriptionVisibility
ref: 'itemDescription'
},
renderLineBreaks itemDescription
)
)
)
History({
ref: 'history'
entries
entriesCount
eventTypes
historyCount: @state.historyCount
addHistoryCount: @_addHistoryCount
resetHistoryCount: @_resetHistoryCount
isFiltering: @props.isFiltering
searchQuery: @props.searchQuery
})
)
History = React.createFactory React.createClass
displayName: 'History'
mixins: [React.addons.PureRenderMixin]
componentDidMount: ->
historyPane = $('.history')
historyPane.on 'scroll', _.throttle((=>
if @props.historyCount < @props.entriesCount
if historyPane.scrollTop() + (historyPane.innerHeight() * 2) >= historyPane[0].scrollHeight
@props.addHistoryCount(10)
return
), 150)
# Draw highlighting first time if searchQuery exists
if @props.isFiltering and @props.searchQuery
$historyPane = new Mark findDOMNode @refs.history
$historyPane.unmark().mark @props.searchQuery
componentDidUpdate: (oldProps, oldState) ->
# Check to see if we need to redraw highlighting while in filter-mode
if @props.isFiltering
$historyPane = new Mark findDOMNode @refs.history
searchQueryChanged = @props.searchQuery isnt oldProps.searchQuery
if @props.searchQuery and (searchQueryChanged or @props.historyCount isnt oldProps.historyCount)
$historyPane.unmark().mark @props.searchQuery
else if not @props.searchQuery and searchQueryChanged
$historyPane.unmark()
resetScroll: ->
historyPane = $('.history')
historyPane.scrollTop(0)
render: ->
{entries, eventTypes} = @props
R.div({
ref: 'history'
className: 'history'
},
(entries.map (entry) =>
entryId = entry.get('progNoteId')
timestamp = entry.get('backdate') or entry.get('timestamp')
authorProgram = entry.get('authorProgram')
return R.div({
key: entryId
className: 'entry'
},
R.div({className: 'header'},
R.div({className: 'timestamp'},
formatTimestamp(timestamp)
(if authorProgram
ColorKeyBubble({
colorKeyHex: authorProgram.get('colorKeyHex')
popover: {
title: authorProgram.get('name')
content: authorProgram.get('description')
placement: 'left'
}
})
)
)
R.div({className: 'author'},
FaIcon('user')
entry.get('author')
)
)
unless entry.get('notes') is ''
R.div({className: 'notes'},
if entry.get('notes').includes "***"
R.span({className: 'starred'},
renderLineBreaks entry.get('notes').replace(/\*\*\*/g, '')
)
else
renderLineBreaks entry.get('notes')
)
if entry.get('metrics')
unless entry.get('metrics').size is 0
R.div({className: 'metrics'},
entry.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
)
if entry.get('progEvents')
unless entry.get('progEvents').isEmpty()
R.div({className: 'progEvents'},
entry.get('progEvents').map (progEvent) =>
ProgEventWidget({
key: progEvent.get('id')
format: 'small'
progEvent
eventTypes
})
)
)
).toJS()...
)
return ProgNoteDetailView
module.exports = {load}
|
[
{
"context": "uest.get 'http://127.0.0.1:1337', callback).auth 'Sarah', 'testpass'\n",
"end": 988,
"score": 0.4318821132183075,
"start": 985,
"tag": "USERNAME",
"value": "Sar"
},
{
"context": "t.get 'http://127.0.0.1:1337', callback).auth 'Sarah', 'testpass'\n",
"end": 990,
"... | node_modules/http-auth/tests/test-skip-user.coffee | witalij777/WebBluetooth | 1 | # Request library.
request = require 'request'
# HTTP library.
http = require 'http'
# Authentication library.
auth = require '../gensrc/http-auth'
# htpasswd verification is reused.
htpasswd = require 'htpasswd'
module.exports =
# Before each test.
setUp: (callback) ->
basic = auth.basic { # Configure authentication.
realm: "Private Area.",
file: __dirname + "/../data/users.htpasswd",
skipUser: true
}
# Creating new HTTP server.
@server = http.createServer basic, (req, res) ->
res.end "req.user is #{req.user}!"
# Start server.
@server.listen 1337
callback()
# After each test.
tearDown: (callback) ->
@server.close() # Stop server.
callback()
# Correct plain details.
testSuccessPlain: (test) ->
callback = (error, response, body) -> # Callback.
test.equals body, "req.user is undefined!"
test.done()
# Test request.
(request.get 'http://127.0.0.1:1337', callback).auth 'Sarah', 'testpass'
| 117412 | # Request library.
request = require 'request'
# HTTP library.
http = require 'http'
# Authentication library.
auth = require '../gensrc/http-auth'
# htpasswd verification is reused.
htpasswd = require 'htpasswd'
module.exports =
# Before each test.
setUp: (callback) ->
basic = auth.basic { # Configure authentication.
realm: "Private Area.",
file: __dirname + "/../data/users.htpasswd",
skipUser: true
}
# Creating new HTTP server.
@server = http.createServer basic, (req, res) ->
res.end "req.user is #{req.user}!"
# Start server.
@server.listen 1337
callback()
# After each test.
tearDown: (callback) ->
@server.close() # Stop server.
callback()
# Correct plain details.
testSuccessPlain: (test) ->
callback = (error, response, body) -> # Callback.
test.equals body, "req.user is undefined!"
test.done()
# Test request.
(request.get 'http://127.0.0.1:1337', callback).auth 'Sar<NAME>', 'testpass'
| true | # Request library.
request = require 'request'
# HTTP library.
http = require 'http'
# Authentication library.
auth = require '../gensrc/http-auth'
# htpasswd verification is reused.
htpasswd = require 'htpasswd'
module.exports =
# Before each test.
setUp: (callback) ->
basic = auth.basic { # Configure authentication.
realm: "Private Area.",
file: __dirname + "/../data/users.htpasswd",
skipUser: true
}
# Creating new HTTP server.
@server = http.createServer basic, (req, res) ->
res.end "req.user is #{req.user}!"
# Start server.
@server.listen 1337
callback()
# After each test.
tearDown: (callback) ->
@server.close() # Stop server.
callback()
# Correct plain details.
testSuccessPlain: (test) ->
callback = (error, response, body) -> # Callback.
test.equals body, "req.user is undefined!"
test.done()
# Test request.
(request.get 'http://127.0.0.1:1337', callback).auth 'SarPI:NAME:<NAME>END_PI', 'testpass'
|
[
{
"context": "eys.sort((a, b) -> a.index - b.index)\n keys = (a.hash for a in keys)\n API.createAlbum(keys, (result)",
"end": 13485,
"score": 0.8767699599266052,
"start": 13479,
"tag": "KEY",
"value": "a.hash"
},
{
"context": "a, b) -> a.index - b.index)\n keys = (a.hash for... | scripts/home.coffee | Jaex/MediaCrush | 1 | worker = new Worker('/static/worker.js')
window.backgroundWorker = worker
albumAttached = false
maxConcurrentUploads = 3
window.addEventListener('DOMContentLoaded', ->
window.addEventListener('dragenter', dragNop, false)
window.addEventListener('dragleave', dragNop, false)
window.addEventListener('dragover', dragNop, false)
window.addEventListener('drop', handleDragDrop, false)
document.getElementById('browse-link').addEventListener('click', (e) ->
e.preventDefault()
document.getElementById('browse').click()
, false)
document.getElementById('browse').addEventListener('change', (e) ->
handleFiles(e.target.files)
, false)
albumUI = document.getElementById('albumUI')
albumUI.querySelector('.button').addEventListener('click', (e) ->
e.preventDefault()
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumAttached = true
createAlbum()
, false)
worker.addEventListener('message', handleWorkerMessage)
worker.postMessage({ action: 'load' })
window.statusChange = (file, status, oldStatus) ->
if oldStatus == 'uploading'
uploadPendingItems()
# We kick this manually every so often to make sure nothing gets abandoned in the 'Pending' state
setInterval(uploadPendingFiles, 10000)
pasteTarget = document.getElementById('paste-target')
pasteTarget.addEventListener('paste', handlePaste, false)
forceFocus()
historyEnabled = document.getElementById('historyEnabled')
if not UserHistory.getHistoryEnabled()
historyEnabled.textContent = 'Enable local history'
historyEnabled.addEventListener('click', (e) ->
e.preventDefault()
if UserHistory.toggleHistoryEnabled()
historyEnabled.textContent = 'Disable local history'
else
historyEnabled.textContent = 'Enable local history'
, false)
items = UserHistory.getHistory()[..].reverse()[..4]
historyContainer = document.getElementById('history')
historyList = historyContainer.querySelector('ul')
blurb = document.getElementById('blurb')
if items.length != 0
spinner = document.createElement('div')
spinner.className = 'progress'
blurb.appendChild(spinner)
UserHistory.loadDetailedHistory(items, (result) ->
blurb.classList.add('hidden')
historyContainer.classList.remove('hidden')
spinner.parentElement.removeChild(spinner)
for item in items
if result[item]
historyList.appendChild(createHistoryItem({ item: result[item], hash: item }))
)
, false)
forceFocus = ->
if document.activeElement.tagName in ['TEXTAREA', 'INPUT', 'IFRAME']
setTimeout(forceFocus, 250)
return
pasteTarget = document.getElementById('paste-target')
pasteTarget.focus()
setTimeout(forceFocus, 250)
createHistoryItem = (h, noLink = false) ->
item = h.item
container = null
if h.base?
container = document.createElement(data.base)
else
container = document.createElement('li')
if item.blob_type == 'video'
preview = document.createElement('video')
preview.setAttribute('loop', 'true')
preview.poster = '/' + item.hash + '.jpg'
for file in item.files
if file.type.indexOf('video/') == 0
source = document.createElement('source')
source.src = window.cdn + file.file
source.type = file.type
preview.appendChild(source)
preview.volume = 0
preview.className = 'item-view'
preview.onmouseenter = (e) ->
e.target.play()
preview.onmouseleave = (e) ->
e.target.pause()
else if item.blob_type == 'image'
preview = document.createElement('img')
for file in item.files
if not file.type.indexOf('image/') == 0
continue
preview.src = window.cdn + file.file
break
preview.className = 'item-view'
else if item.blob_type == 'audio'
preview = document.createElement('img')
preview.src = '/static/audio-player-narrow.png'
preview.className = 'item-view'
else if item.type == 'application/album'
preview = document.createElement('div')
preview.className = 'album-preview'
for file in item.files
preview.appendChild(createHistoryItem(file, true))
if preview
if not noLink
a = document.createElement('a')
a.href = '/' + h.hash
a.target = '_blank'
a.appendChild(preview)
container.appendChild(a)
return container
window.onbeforeunload = ->
for f of uploadedFiles
if uploadedFiles[f].status not in ['done', 'error', 'ready']
return 'If you leave this page, your uploads will be cancelled.'
handleWorkerMessage = (e) ->
if e.data.execute?
eval(e.data.execute)
if e.data.event?
switch e.data.event
when 'file-status-change' then fileStatusChanged(e.data)
dragNop = (e) ->
e.stopPropagation()
e.preventDefault()
handleDragDrop = (e) ->
dragNop(e)
droparea = document.getElementById('droparea')
droparea.classList.remove('hover') if droparea.classList.contains('hover')
files = e.dataTransfer.files
handleFiles(files) if files.length > 0
pendingFiles = []
updateQueue = ->
files = pendingFiles.splice(0, 5)
urls = pendingUrls.splice(0, 5)
fileList = document.getElementById('files')
scrollingContainer = document.getElementById('droparea')
for file in files
((file) ->
mediaFile = new MediaFile(file)
mediaFile.preview = createPreview(file.name)
_ = scrollingContainer.scrollTop
fileList.appendChild(mediaFile.preview)
scrollingContainer.scrollTop = _
mediaFile.preview = fileList.lastElementChild
mediaFile.loadPreview()
mediaFile.hash = new String(guid())
mediaFile.updateStatus('local-pending')
uploadedFiles[mediaFile.hash] = mediaFile
)(file)
for url in urls
((url) ->
mediaFile = new MediaFile(url)
mediaFile.preview = createPreview(mediaFile.name)
_ = scrollingContainer.scrollTop
fileList.appendChild(mediaFile.preview)
scrollingContainer.scrollTop = _
mediaFile.preview = fileList.lastElementChild
mediaFile.loadPreview()
mediaFile.hash = new String(guid())
mediaFile.updateStatus('local-pending')
uploadedFiles[mediaFile.hash] = mediaFile
)(url)
if pendingFiles.length + pendingUrls.length > 0
setTimeout(updateQueue, 500)
if files.length > 0
uploadPendingFiles()
handleFiles = (files) ->
if albumAttached
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumUI.querySelector('.result').classList.add('hidden')
if Object.keys(uploadedFiles).length == 0
document.getElementById('files').innerHTML = ''
dropArea = document.getElementById('droparea')
dropArea.style.overflowY = 'scroll'
dropArea.classList.add('files')
pendingFiles.push(file) for file in files
updateQueue()
window.handleFiles = handleFiles
uploadPendingFiles = ->
toUpload = []
uploading = 0
for hash, file of uploadedFiles
if file.status in ['preparing', 'uploading']
uploading++
return if uploading >= maxConcurrentUploads
else if file.status == 'local-pending' and toUpload.length < 5
toUpload.push(file)
for file in toUpload
((file) ->
if file.isUrl
uploadUrlFile(file)
else
reader = new FileReader()
reader.onloadend = (e) ->
try
data = e.target.result
file.updateStatus('preparing')
worker.postMessage({ action: 'compute-hash', data: data, callback: 'hashCompleted', id: file.hash })
catch e # Too large
uploadFile(file)
reader.readAsBinaryString(file.file)
)(file)
hashCompleted = (id, result) ->
file = uploadedFiles[id]
file.hash = result
delete uploadedFiles[id]
uploadedFiles[result] = file
file.isHashed = true
uploadFile(file)
handlePaste = (e) ->
target = document.getElementById('paste-target')
if e.clipboardData
text = e.clipboardData.getData('text/plain')
if text
if text.indexOf('http://') == 0 or text.indexOf('https://') == 0
urls = text.split('\n')
uploadUrls(url.trim() for url in urls when url.indexOf('http://') == 0 or url.indexOf('https://') == 0)
target.innerHTML = ''
else
# todo: plaintext
else
if e.clipboardData.items # webkit
for item in e.clipboardData.items
if item.type.indexOf('image/') == 0
file = item.getAsFile
file.name = 'Clipboard'
handleFiles([ file ])
else # not webkit
check = ->
if target.innerHTML != ''
img = target.firstChild.src
if img.indexOf('data:image/png;base64,') == 0
blob = dataURItoBlob(img)
blob.name = 'Clipboard'
handleFiles([ blob ])
target.innerHTML = ''
else
setTimeout(check, 100)
check()
pendingUrls = []
uploadUrls = (urls) ->
if albumAttached
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumUI.querySelector('.result').classList.add('hidden')
if Object.keys(uploadedFiles).length == 0
document.getElementById('files').innerHTML = ''
dropArea = document.getElementById('droparea')
dropArea.style.overflowY = 'scroll'
dropArea.classList.add('files')
pendingUrls.push(url) for url in urls
updateQueue()
uploadUrlFile = (file) ->
oldHash = file.hash
API.uploadUrl(file, (result) ->
uploadedFiles[file.hash] = file
if result.error?
file.setError(result.error)
return
file = result.file
delete uploadedFiles[oldHash]
uploadedFiles[file.hash] = file
if file.status == 'done'
finish(file)
else
file.isUserOwned = true
worker.postMessage({ action: 'monitor-status', hash: file.hash })
)
uploadFile = (file) ->
oldHash = file.hash
upload = ->
file.updateStatus('uploading')
API.uploadFile(file, (e) ->
if e.lengthComputable
file.updateProgress(e.loaded / e.total)
, (result) ->
file.file = null
if result.error?
file.setError(result.error)
return
if file.hash != oldHash # for larger files, the server does the hashing for us
delete uploadedFiles[oldHash]
uploadedFiles[file.hash] = file
if file.status == 'done'
finish(file)
else
file.isUserOwned = true
worker.postMessage({ action: 'monitor-status', hash: file.hash })
)
if file.isHashed
API.checkExists(file, (exists) ->
if exists
file.file = null
file.isUserOwned = false
file.updateStatus('done')
finish(file)
return
else
upload()
)
fileStatusChanged = (e) ->
uploadedFiles[e.hash].updateStatus(e.status)
if e.file? and e.file.flags?
uploadedFiles[e.hash].setFlags(e.file.flags)
if e.status in ['ready', 'done']
uploadedFiles[e.hash].blob = e.file
finish(uploadedFiles[e.hash])
finish = (file) ->
file.finish()
updateAlbumUI()
updateAlbumUI = ->
if albumAttached
createAlbum()
else
keys = []
for f, v of uploadedFiles
if v.status in ['processing', 'pending', 'ready', 'done', 'uploading']
keys.push(f)
albumUI = document.getElementById('albumUI')
if keys.length >= 2
albumUI.querySelector('.button').classList.remove('hidden')
else
albumUI.querySelector('.button').classList.add('hidden')
createAlbum = ->
keys = []
for f, v of uploadedFiles
if v.status in ['done', 'ready']
keys.push(v)
else
return
return unless keys.length >= 2
keys.sort((a, b) -> a.index - b.index)
keys = (a.hash for a in keys)
API.createAlbum(keys, (result) ->
albumUI = document.getElementById('albumUI')
if result.error?
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'An error occured creating this album.'
albumUI.querySelector('.button').classList.remove('hidden')
albumUI.querySelector('.button').textContent = 'Try again'
else
albumUI.querySelector('.status').classList.add('hidden')
albumUI.querySelector('.result a').textContent = window.location.origin + "/#{result.hash}"
albumUI.querySelector('.result a').href = window.location.origin + "/#{result.hash}"
albumUI.querySelector('.result').classList.remove('hidden')
)
window.statusHook = (file, status, oldStatus) ->
if oldStatus?
return if status == 'ready' and oldStatus == 'done'
updateAlbumUI()
createPreview = (name) ->
create = (element, className) ->
_ = document.createElement(element)
_.className = className if className?
return _
container = create('div', 'media-preview')
preview = create('div', 'preview')
fade = create('div', 'respondive-fade')
title = create('h2')
title.title = name
title.textContent = name
flags = create('div', 'flags hidden')
status = create('div', 'status')
error = create('div', 'error hidden')
link = create('a', 'link hidden')
deleteLink = create('a', 'delete hidden')
deleteLink.textContent = 'Delete'
fullSize = create('a', 'full-size hidden')
progress = create('div', 'progress')
progress.style.width = 0
container.appendChild(preview)
container.appendChild(fade)
container.appendChild(title)
container.appendChild(flags)
container.appendChild(status)
container.appendChild(error)
container.appendChild(link)
container.appendChild(deleteLink)
container.appendChild(fullSize)
container.appendChild(progress)
return container
| 171202 | worker = new Worker('/static/worker.js')
window.backgroundWorker = worker
albumAttached = false
maxConcurrentUploads = 3
window.addEventListener('DOMContentLoaded', ->
window.addEventListener('dragenter', dragNop, false)
window.addEventListener('dragleave', dragNop, false)
window.addEventListener('dragover', dragNop, false)
window.addEventListener('drop', handleDragDrop, false)
document.getElementById('browse-link').addEventListener('click', (e) ->
e.preventDefault()
document.getElementById('browse').click()
, false)
document.getElementById('browse').addEventListener('change', (e) ->
handleFiles(e.target.files)
, false)
albumUI = document.getElementById('albumUI')
albumUI.querySelector('.button').addEventListener('click', (e) ->
e.preventDefault()
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumAttached = true
createAlbum()
, false)
worker.addEventListener('message', handleWorkerMessage)
worker.postMessage({ action: 'load' })
window.statusChange = (file, status, oldStatus) ->
if oldStatus == 'uploading'
uploadPendingItems()
# We kick this manually every so often to make sure nothing gets abandoned in the 'Pending' state
setInterval(uploadPendingFiles, 10000)
pasteTarget = document.getElementById('paste-target')
pasteTarget.addEventListener('paste', handlePaste, false)
forceFocus()
historyEnabled = document.getElementById('historyEnabled')
if not UserHistory.getHistoryEnabled()
historyEnabled.textContent = 'Enable local history'
historyEnabled.addEventListener('click', (e) ->
e.preventDefault()
if UserHistory.toggleHistoryEnabled()
historyEnabled.textContent = 'Disable local history'
else
historyEnabled.textContent = 'Enable local history'
, false)
items = UserHistory.getHistory()[..].reverse()[..4]
historyContainer = document.getElementById('history')
historyList = historyContainer.querySelector('ul')
blurb = document.getElementById('blurb')
if items.length != 0
spinner = document.createElement('div')
spinner.className = 'progress'
blurb.appendChild(spinner)
UserHistory.loadDetailedHistory(items, (result) ->
blurb.classList.add('hidden')
historyContainer.classList.remove('hidden')
spinner.parentElement.removeChild(spinner)
for item in items
if result[item]
historyList.appendChild(createHistoryItem({ item: result[item], hash: item }))
)
, false)
forceFocus = ->
if document.activeElement.tagName in ['TEXTAREA', 'INPUT', 'IFRAME']
setTimeout(forceFocus, 250)
return
pasteTarget = document.getElementById('paste-target')
pasteTarget.focus()
setTimeout(forceFocus, 250)
createHistoryItem = (h, noLink = false) ->
item = h.item
container = null
if h.base?
container = document.createElement(data.base)
else
container = document.createElement('li')
if item.blob_type == 'video'
preview = document.createElement('video')
preview.setAttribute('loop', 'true')
preview.poster = '/' + item.hash + '.jpg'
for file in item.files
if file.type.indexOf('video/') == 0
source = document.createElement('source')
source.src = window.cdn + file.file
source.type = file.type
preview.appendChild(source)
preview.volume = 0
preview.className = 'item-view'
preview.onmouseenter = (e) ->
e.target.play()
preview.onmouseleave = (e) ->
e.target.pause()
else if item.blob_type == 'image'
preview = document.createElement('img')
for file in item.files
if not file.type.indexOf('image/') == 0
continue
preview.src = window.cdn + file.file
break
preview.className = 'item-view'
else if item.blob_type == 'audio'
preview = document.createElement('img')
preview.src = '/static/audio-player-narrow.png'
preview.className = 'item-view'
else if item.type == 'application/album'
preview = document.createElement('div')
preview.className = 'album-preview'
for file in item.files
preview.appendChild(createHistoryItem(file, true))
if preview
if not noLink
a = document.createElement('a')
a.href = '/' + h.hash
a.target = '_blank'
a.appendChild(preview)
container.appendChild(a)
return container
window.onbeforeunload = ->
for f of uploadedFiles
if uploadedFiles[f].status not in ['done', 'error', 'ready']
return 'If you leave this page, your uploads will be cancelled.'
handleWorkerMessage = (e) ->
if e.data.execute?
eval(e.data.execute)
if e.data.event?
switch e.data.event
when 'file-status-change' then fileStatusChanged(e.data)
dragNop = (e) ->
e.stopPropagation()
e.preventDefault()
handleDragDrop = (e) ->
dragNop(e)
droparea = document.getElementById('droparea')
droparea.classList.remove('hover') if droparea.classList.contains('hover')
files = e.dataTransfer.files
handleFiles(files) if files.length > 0
pendingFiles = []
updateQueue = ->
files = pendingFiles.splice(0, 5)
urls = pendingUrls.splice(0, 5)
fileList = document.getElementById('files')
scrollingContainer = document.getElementById('droparea')
for file in files
((file) ->
mediaFile = new MediaFile(file)
mediaFile.preview = createPreview(file.name)
_ = scrollingContainer.scrollTop
fileList.appendChild(mediaFile.preview)
scrollingContainer.scrollTop = _
mediaFile.preview = fileList.lastElementChild
mediaFile.loadPreview()
mediaFile.hash = new String(guid())
mediaFile.updateStatus('local-pending')
uploadedFiles[mediaFile.hash] = mediaFile
)(file)
for url in urls
((url) ->
mediaFile = new MediaFile(url)
mediaFile.preview = createPreview(mediaFile.name)
_ = scrollingContainer.scrollTop
fileList.appendChild(mediaFile.preview)
scrollingContainer.scrollTop = _
mediaFile.preview = fileList.lastElementChild
mediaFile.loadPreview()
mediaFile.hash = new String(guid())
mediaFile.updateStatus('local-pending')
uploadedFiles[mediaFile.hash] = mediaFile
)(url)
if pendingFiles.length + pendingUrls.length > 0
setTimeout(updateQueue, 500)
if files.length > 0
uploadPendingFiles()
handleFiles = (files) ->
if albumAttached
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumUI.querySelector('.result').classList.add('hidden')
if Object.keys(uploadedFiles).length == 0
document.getElementById('files').innerHTML = ''
dropArea = document.getElementById('droparea')
dropArea.style.overflowY = 'scroll'
dropArea.classList.add('files')
pendingFiles.push(file) for file in files
updateQueue()
window.handleFiles = handleFiles
uploadPendingFiles = ->
toUpload = []
uploading = 0
for hash, file of uploadedFiles
if file.status in ['preparing', 'uploading']
uploading++
return if uploading >= maxConcurrentUploads
else if file.status == 'local-pending' and toUpload.length < 5
toUpload.push(file)
for file in toUpload
((file) ->
if file.isUrl
uploadUrlFile(file)
else
reader = new FileReader()
reader.onloadend = (e) ->
try
data = e.target.result
file.updateStatus('preparing')
worker.postMessage({ action: 'compute-hash', data: data, callback: 'hashCompleted', id: file.hash })
catch e # Too large
uploadFile(file)
reader.readAsBinaryString(file.file)
)(file)
hashCompleted = (id, result) ->
file = uploadedFiles[id]
file.hash = result
delete uploadedFiles[id]
uploadedFiles[result] = file
file.isHashed = true
uploadFile(file)
handlePaste = (e) ->
target = document.getElementById('paste-target')
if e.clipboardData
text = e.clipboardData.getData('text/plain')
if text
if text.indexOf('http://') == 0 or text.indexOf('https://') == 0
urls = text.split('\n')
uploadUrls(url.trim() for url in urls when url.indexOf('http://') == 0 or url.indexOf('https://') == 0)
target.innerHTML = ''
else
# todo: plaintext
else
if e.clipboardData.items # webkit
for item in e.clipboardData.items
if item.type.indexOf('image/') == 0
file = item.getAsFile
file.name = 'Clipboard'
handleFiles([ file ])
else # not webkit
check = ->
if target.innerHTML != ''
img = target.firstChild.src
if img.indexOf('data:image/png;base64,') == 0
blob = dataURItoBlob(img)
blob.name = 'Clipboard'
handleFiles([ blob ])
target.innerHTML = ''
else
setTimeout(check, 100)
check()
pendingUrls = []
uploadUrls = (urls) ->
if albumAttached
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumUI.querySelector('.result').classList.add('hidden')
if Object.keys(uploadedFiles).length == 0
document.getElementById('files').innerHTML = ''
dropArea = document.getElementById('droparea')
dropArea.style.overflowY = 'scroll'
dropArea.classList.add('files')
pendingUrls.push(url) for url in urls
updateQueue()
uploadUrlFile = (file) ->
oldHash = file.hash
API.uploadUrl(file, (result) ->
uploadedFiles[file.hash] = file
if result.error?
file.setError(result.error)
return
file = result.file
delete uploadedFiles[oldHash]
uploadedFiles[file.hash] = file
if file.status == 'done'
finish(file)
else
file.isUserOwned = true
worker.postMessage({ action: 'monitor-status', hash: file.hash })
)
uploadFile = (file) ->
oldHash = file.hash
upload = ->
file.updateStatus('uploading')
API.uploadFile(file, (e) ->
if e.lengthComputable
file.updateProgress(e.loaded / e.total)
, (result) ->
file.file = null
if result.error?
file.setError(result.error)
return
if file.hash != oldHash # for larger files, the server does the hashing for us
delete uploadedFiles[oldHash]
uploadedFiles[file.hash] = file
if file.status == 'done'
finish(file)
else
file.isUserOwned = true
worker.postMessage({ action: 'monitor-status', hash: file.hash })
)
if file.isHashed
API.checkExists(file, (exists) ->
if exists
file.file = null
file.isUserOwned = false
file.updateStatus('done')
finish(file)
return
else
upload()
)
fileStatusChanged = (e) ->
uploadedFiles[e.hash].updateStatus(e.status)
if e.file? and e.file.flags?
uploadedFiles[e.hash].setFlags(e.file.flags)
if e.status in ['ready', 'done']
uploadedFiles[e.hash].blob = e.file
finish(uploadedFiles[e.hash])
finish = (file) ->
file.finish()
updateAlbumUI()
updateAlbumUI = ->
if albumAttached
createAlbum()
else
keys = []
for f, v of uploadedFiles
if v.status in ['processing', 'pending', 'ready', 'done', 'uploading']
keys.push(f)
albumUI = document.getElementById('albumUI')
if keys.length >= 2
albumUI.querySelector('.button').classList.remove('hidden')
else
albumUI.querySelector('.button').classList.add('hidden')
createAlbum = ->
keys = []
for f, v of uploadedFiles
if v.status in ['done', 'ready']
keys.push(v)
else
return
return unless keys.length >= 2
keys.sort((a, b) -> a.index - b.index)
keys = (<KEY> for <KEY> in keys)
API.createAlbum(keys, (result) ->
albumUI = document.getElementById('albumUI')
if result.error?
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'An error occured creating this album.'
albumUI.querySelector('.button').classList.remove('hidden')
albumUI.querySelector('.button').textContent = 'Try again'
else
albumUI.querySelector('.status').classList.add('hidden')
albumUI.querySelector('.result a').textContent = window.location.origin + "/#{result.hash}"
albumUI.querySelector('.result a').href = window.location.origin + "/#{result.hash}"
albumUI.querySelector('.result').classList.remove('hidden')
)
window.statusHook = (file, status, oldStatus) ->
if oldStatus?
return if status == 'ready' and oldStatus == 'done'
updateAlbumUI()
createPreview = (name) ->
create = (element, className) ->
_ = document.createElement(element)
_.className = className if className?
return _
container = create('div', 'media-preview')
preview = create('div', 'preview')
fade = create('div', 'respondive-fade')
title = create('h2')
title.title = name
title.textContent = name
flags = create('div', 'flags hidden')
status = create('div', 'status')
error = create('div', 'error hidden')
link = create('a', 'link hidden')
deleteLink = create('a', 'delete hidden')
deleteLink.textContent = 'Delete'
fullSize = create('a', 'full-size hidden')
progress = create('div', 'progress')
progress.style.width = 0
container.appendChild(preview)
container.appendChild(fade)
container.appendChild(title)
container.appendChild(flags)
container.appendChild(status)
container.appendChild(error)
container.appendChild(link)
container.appendChild(deleteLink)
container.appendChild(fullSize)
container.appendChild(progress)
return container
| true | worker = new Worker('/static/worker.js')
window.backgroundWorker = worker
albumAttached = false
maxConcurrentUploads = 3
window.addEventListener('DOMContentLoaded', ->
window.addEventListener('dragenter', dragNop, false)
window.addEventListener('dragleave', dragNop, false)
window.addEventListener('dragover', dragNop, false)
window.addEventListener('drop', handleDragDrop, false)
document.getElementById('browse-link').addEventListener('click', (e) ->
e.preventDefault()
document.getElementById('browse').click()
, false)
document.getElementById('browse').addEventListener('change', (e) ->
handleFiles(e.target.files)
, false)
albumUI = document.getElementById('albumUI')
albumUI.querySelector('.button').addEventListener('click', (e) ->
e.preventDefault()
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumAttached = true
createAlbum()
, false)
worker.addEventListener('message', handleWorkerMessage)
worker.postMessage({ action: 'load' })
window.statusChange = (file, status, oldStatus) ->
if oldStatus == 'uploading'
uploadPendingItems()
# We kick this manually every so often to make sure nothing gets abandoned in the 'Pending' state
setInterval(uploadPendingFiles, 10000)
pasteTarget = document.getElementById('paste-target')
pasteTarget.addEventListener('paste', handlePaste, false)
forceFocus()
historyEnabled = document.getElementById('historyEnabled')
if not UserHistory.getHistoryEnabled()
historyEnabled.textContent = 'Enable local history'
historyEnabled.addEventListener('click', (e) ->
e.preventDefault()
if UserHistory.toggleHistoryEnabled()
historyEnabled.textContent = 'Disable local history'
else
historyEnabled.textContent = 'Enable local history'
, false)
items = UserHistory.getHistory()[..].reverse()[..4]
historyContainer = document.getElementById('history')
historyList = historyContainer.querySelector('ul')
blurb = document.getElementById('blurb')
if items.length != 0
spinner = document.createElement('div')
spinner.className = 'progress'
blurb.appendChild(spinner)
UserHistory.loadDetailedHistory(items, (result) ->
blurb.classList.add('hidden')
historyContainer.classList.remove('hidden')
spinner.parentElement.removeChild(spinner)
for item in items
if result[item]
historyList.appendChild(createHistoryItem({ item: result[item], hash: item }))
)
, false)
forceFocus = ->
if document.activeElement.tagName in ['TEXTAREA', 'INPUT', 'IFRAME']
setTimeout(forceFocus, 250)
return
pasteTarget = document.getElementById('paste-target')
pasteTarget.focus()
setTimeout(forceFocus, 250)
createHistoryItem = (h, noLink = false) ->
item = h.item
container = null
if h.base?
container = document.createElement(data.base)
else
container = document.createElement('li')
if item.blob_type == 'video'
preview = document.createElement('video')
preview.setAttribute('loop', 'true')
preview.poster = '/' + item.hash + '.jpg'
for file in item.files
if file.type.indexOf('video/') == 0
source = document.createElement('source')
source.src = window.cdn + file.file
source.type = file.type
preview.appendChild(source)
preview.volume = 0
preview.className = 'item-view'
preview.onmouseenter = (e) ->
e.target.play()
preview.onmouseleave = (e) ->
e.target.pause()
else if item.blob_type == 'image'
preview = document.createElement('img')
for file in item.files
if not file.type.indexOf('image/') == 0
continue
preview.src = window.cdn + file.file
break
preview.className = 'item-view'
else if item.blob_type == 'audio'
preview = document.createElement('img')
preview.src = '/static/audio-player-narrow.png'
preview.className = 'item-view'
else if item.type == 'application/album'
preview = document.createElement('div')
preview.className = 'album-preview'
for file in item.files
preview.appendChild(createHistoryItem(file, true))
if preview
if not noLink
a = document.createElement('a')
a.href = '/' + h.hash
a.target = '_blank'
a.appendChild(preview)
container.appendChild(a)
return container
window.onbeforeunload = ->
for f of uploadedFiles
if uploadedFiles[f].status not in ['done', 'error', 'ready']
return 'If you leave this page, your uploads will be cancelled.'
handleWorkerMessage = (e) ->
if e.data.execute?
eval(e.data.execute)
if e.data.event?
switch e.data.event
when 'file-status-change' then fileStatusChanged(e.data)
dragNop = (e) ->
e.stopPropagation()
e.preventDefault()
handleDragDrop = (e) ->
dragNop(e)
droparea = document.getElementById('droparea')
droparea.classList.remove('hover') if droparea.classList.contains('hover')
files = e.dataTransfer.files
handleFiles(files) if files.length > 0
pendingFiles = []
updateQueue = ->
files = pendingFiles.splice(0, 5)
urls = pendingUrls.splice(0, 5)
fileList = document.getElementById('files')
scrollingContainer = document.getElementById('droparea')
for file in files
((file) ->
mediaFile = new MediaFile(file)
mediaFile.preview = createPreview(file.name)
_ = scrollingContainer.scrollTop
fileList.appendChild(mediaFile.preview)
scrollingContainer.scrollTop = _
mediaFile.preview = fileList.lastElementChild
mediaFile.loadPreview()
mediaFile.hash = new String(guid())
mediaFile.updateStatus('local-pending')
uploadedFiles[mediaFile.hash] = mediaFile
)(file)
for url in urls
((url) ->
mediaFile = new MediaFile(url)
mediaFile.preview = createPreview(mediaFile.name)
_ = scrollingContainer.scrollTop
fileList.appendChild(mediaFile.preview)
scrollingContainer.scrollTop = _
mediaFile.preview = fileList.lastElementChild
mediaFile.loadPreview()
mediaFile.hash = new String(guid())
mediaFile.updateStatus('local-pending')
uploadedFiles[mediaFile.hash] = mediaFile
)(url)
if pendingFiles.length + pendingUrls.length > 0
setTimeout(updateQueue, 500)
if files.length > 0
uploadPendingFiles()
handleFiles = (files) ->
if albumAttached
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumUI.querySelector('.result').classList.add('hidden')
if Object.keys(uploadedFiles).length == 0
document.getElementById('files').innerHTML = ''
dropArea = document.getElementById('droparea')
dropArea.style.overflowY = 'scroll'
dropArea.classList.add('files')
pendingFiles.push(file) for file in files
updateQueue()
window.handleFiles = handleFiles
uploadPendingFiles = ->
toUpload = []
uploading = 0
for hash, file of uploadedFiles
if file.status in ['preparing', 'uploading']
uploading++
return if uploading >= maxConcurrentUploads
else if file.status == 'local-pending' and toUpload.length < 5
toUpload.push(file)
for file in toUpload
((file) ->
if file.isUrl
uploadUrlFile(file)
else
reader = new FileReader()
reader.onloadend = (e) ->
try
data = e.target.result
file.updateStatus('preparing')
worker.postMessage({ action: 'compute-hash', data: data, callback: 'hashCompleted', id: file.hash })
catch e # Too large
uploadFile(file)
reader.readAsBinaryString(file.file)
)(file)
hashCompleted = (id, result) ->
file = uploadedFiles[id]
file.hash = result
delete uploadedFiles[id]
uploadedFiles[result] = file
file.isHashed = true
uploadFile(file)
handlePaste = (e) ->
target = document.getElementById('paste-target')
if e.clipboardData
text = e.clipboardData.getData('text/plain')
if text
if text.indexOf('http://') == 0 or text.indexOf('https://') == 0
urls = text.split('\n')
uploadUrls(url.trim() for url in urls when url.indexOf('http://') == 0 or url.indexOf('https://') == 0)
target.innerHTML = ''
else
# todo: plaintext
else
if e.clipboardData.items # webkit
for item in e.clipboardData.items
if item.type.indexOf('image/') == 0
file = item.getAsFile
file.name = 'Clipboard'
handleFiles([ file ])
else # not webkit
check = ->
if target.innerHTML != ''
img = target.firstChild.src
if img.indexOf('data:image/png;base64,') == 0
blob = dataURItoBlob(img)
blob.name = 'Clipboard'
handleFiles([ blob ])
target.innerHTML = ''
else
setTimeout(check, 100)
check()
pendingUrls = []
uploadUrls = (urls) ->
if albumAttached
albumUI.querySelector('.button').classList.add('hidden')
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'Processing, please wait...'
albumUI.querySelector('.result').classList.add('hidden')
if Object.keys(uploadedFiles).length == 0
document.getElementById('files').innerHTML = ''
dropArea = document.getElementById('droparea')
dropArea.style.overflowY = 'scroll'
dropArea.classList.add('files')
pendingUrls.push(url) for url in urls
updateQueue()
uploadUrlFile = (file) ->
oldHash = file.hash
API.uploadUrl(file, (result) ->
uploadedFiles[file.hash] = file
if result.error?
file.setError(result.error)
return
file = result.file
delete uploadedFiles[oldHash]
uploadedFiles[file.hash] = file
if file.status == 'done'
finish(file)
else
file.isUserOwned = true
worker.postMessage({ action: 'monitor-status', hash: file.hash })
)
uploadFile = (file) ->
oldHash = file.hash
upload = ->
file.updateStatus('uploading')
API.uploadFile(file, (e) ->
if e.lengthComputable
file.updateProgress(e.loaded / e.total)
, (result) ->
file.file = null
if result.error?
file.setError(result.error)
return
if file.hash != oldHash # for larger files, the server does the hashing for us
delete uploadedFiles[oldHash]
uploadedFiles[file.hash] = file
if file.status == 'done'
finish(file)
else
file.isUserOwned = true
worker.postMessage({ action: 'monitor-status', hash: file.hash })
)
if file.isHashed
API.checkExists(file, (exists) ->
if exists
file.file = null
file.isUserOwned = false
file.updateStatus('done')
finish(file)
return
else
upload()
)
fileStatusChanged = (e) ->
uploadedFiles[e.hash].updateStatus(e.status)
if e.file? and e.file.flags?
uploadedFiles[e.hash].setFlags(e.file.flags)
if e.status in ['ready', 'done']
uploadedFiles[e.hash].blob = e.file
finish(uploadedFiles[e.hash])
finish = (file) ->
file.finish()
updateAlbumUI()
updateAlbumUI = ->
if albumAttached
createAlbum()
else
keys = []
for f, v of uploadedFiles
if v.status in ['processing', 'pending', 'ready', 'done', 'uploading']
keys.push(f)
albumUI = document.getElementById('albumUI')
if keys.length >= 2
albumUI.querySelector('.button').classList.remove('hidden')
else
albumUI.querySelector('.button').classList.add('hidden')
createAlbum = ->
keys = []
for f, v of uploadedFiles
if v.status in ['done', 'ready']
keys.push(v)
else
return
return unless keys.length >= 2
keys.sort((a, b) -> a.index - b.index)
keys = (PI:KEY:<KEY>END_PI for PI:KEY:<KEY>END_PI in keys)
API.createAlbum(keys, (result) ->
albumUI = document.getElementById('albumUI')
if result.error?
albumUI.querySelector('.status').classList.remove('hidden')
albumUI.querySelector('.status').textContent = 'An error occured creating this album.'
albumUI.querySelector('.button').classList.remove('hidden')
albumUI.querySelector('.button').textContent = 'Try again'
else
albumUI.querySelector('.status').classList.add('hidden')
albumUI.querySelector('.result a').textContent = window.location.origin + "/#{result.hash}"
albumUI.querySelector('.result a').href = window.location.origin + "/#{result.hash}"
albumUI.querySelector('.result').classList.remove('hidden')
)
window.statusHook = (file, status, oldStatus) ->
if oldStatus?
return if status == 'ready' and oldStatus == 'done'
updateAlbumUI()
createPreview = (name) ->
create = (element, className) ->
_ = document.createElement(element)
_.className = className if className?
return _
container = create('div', 'media-preview')
preview = create('div', 'preview')
fade = create('div', 'respondive-fade')
title = create('h2')
title.title = name
title.textContent = name
flags = create('div', 'flags hidden')
status = create('div', 'status')
error = create('div', 'error hidden')
link = create('a', 'link hidden')
deleteLink = create('a', 'delete hidden')
deleteLink.textContent = 'Delete'
fullSize = create('a', 'full-size hidden')
progress = create('div', 'progress')
progress.style.width = 0
container.appendChild(preview)
container.appendChild(fade)
container.appendChild(title)
container.appendChild(flags)
container.appendChild(status)
container.appendChild(error)
container.appendChild(link)
container.appendChild(deleteLink)
container.appendChild(fullSize)
container.appendChild(progress)
return container
|
[
{
"context": "ments)\n @\n password = mnemonic.normalize('NFKD')\n salt = \"mnemonic\" + passphrase.normalize('N",
"end": 804,
"score": 0.7616033554077148,
"start": 800,
"tag": "PASSWORD",
"value": "NFKD"
},
{
"context": "password = mnemonic.normalize('NFKD')\n salt = \... | app/src/utils/bitcoin/bip39.coffee | doged/ledger-wallet-doged-chrome | 1 | ledger.bitcoin ?= {}
ledger.bitcoin.bip39 ?= {}
_.extend ledger.bitcoin.bip39,
ENTROPY_BIT_LENGTH: 256
BIT_IN_BYTES: 8
BYTES_IN_INTEGER: 4
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
isMnemonicPhraseValid: (mnemonicPhrase) ->
try
@utils.checkMnemonicPhraseValid(mnemonicPhrase) && true
catch e
false
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
mnemonicPhraseToSeed: (mnemonicPhrase, passphrase="") ->
@utils.checkMnemonicPhraseValid(mnemonicPhrase)
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = mnemonic.normalize('NFKD')
salt = "mnemonic" + passphrase.normalize('NFKD')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
mnemonicIsValid: (mnemonic) ->
numberOfWords = @numberOfWordsInMnemonic(mnemonic)
return no if (numberOfWords % 3 != 0) or (numberOfWords != @mnemonicWordsNumber())
return no if not @_allWordsInMnemonicAreValid(mnemonic)
# convert wordlist to words indexes
words = mnemonic.split(' ')
wordsIndexes = @_mnemonicArrayToWordsIndexes words
# generate binary array from words indexes
binaryArray = @_integersArrayToBinaryArray wordsIndexes, 11
# extract checksum
entropyBitLength = @_nearest32Multiple binaryArray.length
extractedBinaryChecksum = @_lastBitsOfBinaryArray binaryArray, entropyBitLength / 32
extractedChecksum = @_binaryArrayToInteger extractedBinaryChecksum
# compute checksum
binaryEntropy = @_firstBitsOfBinaryArray binaryArray, entropyBitLength
integersEntropy = @_binaryArrayToIntegersArray binaryEntropy
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = @_integersArrayToBinaryArray hashedIntegersEntropy
computedBinaryChecksum = @_firstBitsOfBinaryArray(hashedEntropyBinaryArray, entropyBitLength / 32)
computedChecksum = @_binaryArrayToInteger computedBinaryChecksum
# verify checksum
return computedChecksum == extractedChecksum
generateMnemonic: (entropyBitLength = @ENTROPY_BIT_LENGTH) ->
# generate entropy bytes array
entropyBytesArray = @_randomEntropyBytesArray(entropyBitLength / @BIT_IN_BYTES)
entropyIntegersArray = @_bytesArrayToIntegersArray(entropyBytesArray)
@entropyToMnemonic(entropyBytesArray, entropyBitLength)
entropyToMnemonic: (entropy, entropyBitLength = @ENTROPY_BIT_LENGTH) ->
# convert it to integers array
if typeof entropy == "string"
entropyIntegersArray = entropy.match(/\w{8}/g).map (h) -> parseInt(h,16)
else if entropy instanceof Uint8Array
entropyIntegersArray = @_bytesArrayToIntegersArray(entropy)
else
entropyIntegersArray = entropy
# apply sha256 to hash
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
# get first x bits of hash
hashedEntropyBinaryArray = @_integersArrayToBinaryArray hashedEntropyIntegersArray
checksum = @_firstBitsOfBinaryArray(hashedEntropyBinaryArray, entropyBitLength / 32)
# compute entropy binary array
entropyBinaryArray = @_integersArrayToBinaryArray entropyIntegersArray
# append checksum to entropy
finalEntropyBinaryArray = @_appendBitsToBinaryArray entropyBinaryArray, checksum
# extract words indexes
wordsIndexes = @_binaryArrayToIntegersArray finalEntropyBinaryArray, 11
# generate wordlist
wordlist = @_wordsIndexesToMnemonicArray wordsIndexes
wordlist.join(' ')
generateSeed: (mnemonic, passphrase = "") ->
return undefined if !@mnemonicIsValid mnemonic
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = mnemonic.normalize('NFKD')
salt = "mnemonic" + passphrase.normalize('NFKD')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
numberOfWordsInMnemonic: (mnemonic) ->
return 0 if not mnemonic? or mnemonic.length == 0
count = 0
words = mnemonic.split ' '
for word in words
count++ if word? and word.length > 0
count
mnemonicWordsNumber: ->
return (@ENTROPY_BIT_LENGTH + @ENTROPY_BIT_LENGTH / 32) / 11
_allWordsInMnemonicAreValid: (mnemonic) ->
return 0 if not mnemonic? or mnemonic.length == 0
words = mnemonic.split ' '
for word in words
return no if ledger.bitcoin.bip39.wordlist.indexOf(word) == -1
return yes
_integersArrayToBinaryArray: (integersArray, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
binaryArray = []
for integer in integersArray
partialBinaryArray = @_integerToBinaryArray integer, integerBitLength
@_appendBitsToBinaryArray binaryArray, partialBinaryArray
binaryArray
_integerToBinaryArray: (integer, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
binaryArray = []
for power in [integerBitLength - 1 .. 0]
val = Math.abs ((integer & (1 << power)) >> power)
binaryArray.push val
binaryArray
_binaryArrayToInteger: (binaryArray) ->
return 0 if binaryArray.length == 0
integer = 0
multiplier = 1
for i in [binaryArray.length - 1 .. 0]
if binaryArray[i] == 1
integer += multiplier
multiplier *= 2
integer
_binaryArrayToIntegersArray: (binaryArray, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
integersArray = []
workingArray = binaryArray.slice()
while workingArray.length > 0
integersArray.push @_binaryArrayToInteger(@_firstBitsOfBinaryArray(workingArray, integerBitLength))
workingArray.splice 0, integerBitLength
integersArray
_bytesArrayToIntegersArray: (bytesArray) ->
i = 0
integerArray = []
while i < bytesArray.length
integer = (bytesArray[i] << (@BIT_IN_BYTES * 3)) + (bytesArray[i + 1] << (@BIT_IN_BYTES * 2)) + (bytesArray[i + 2] << (@BIT_IN_BYTES * 1)) + bytesArray[i + 3]
integerArray.push integer
i += @BYTES_IN_INTEGER
integerArray
_firstBitsOfBinaryArray: (binaryArray, numberOfFirstBits) ->
binaryArray.slice 0, numberOfFirstBits
_lastBitsOfBinaryArray: (binaryArray, numberOfLastBits) ->
binaryArray.slice -numberOfLastBits
_appendBitsToBinaryArray: (binaryArray, bitsToAppend) ->
for bit in bitsToAppend
binaryArray.push bit
binaryArray
_wordsIndexesToMnemonicArray: (indexes) ->
mnemonicArray = []
for index in indexes
mnemonicArray.push ledger.bitcoin.bip39.wordlist[index]
mnemonicArray
_mnemonicArrayToWordsIndexes: (mnemonicArray) ->
indexes = []
for word in mnemonicArray
indexes.push ledger.bitcoin.bip39.wordlist.indexOf word
indexes
_nearest32Multiple: (length) ->
power = 0
while (power + 32) <= length
power += 32
power
_randomEntropyBytesArray: (bytesLength) ->
entropy = new Uint8Array(bytesLength)
crypto.getRandomValues entropy
entropy
utils:
BITS_IN_INTEGER: 8 * 4
wordlist: ledger.bitcoin.bip39.wordlist
# @param [string] entropy A hexadecimal string.
# @return [string] Mnemonic phrase. Phrase may contains 12 to 24 words depending of entropy length.
entropyToMnemonicPhrase: (entropy) ->
throw "Invalid entropy format. Wait a hexadecimal string" if ! entropy.match(/^[0-9a-fA-F]+$/)
throw "Invalid entropy length: #{entropy.length*4}" if entropy.length % 8 != 0
# Compute checksum
entropyIntegersArray = entropy.match(/[0-9a-fA-F]{8}/g).map (h) -> parseInt(h,16)
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
hashedEntropy = hashedEntropyIntegersArray.map((i) => @_intToBin(i,32)).join('')
# 1 checksum bit per 32 bits of entropy.
binChecksum = hashedEntropy.slice(0,entropyIntegersArray.length)
binEntropy = entropyIntegersArray.map((i) => @_intToBin(i,32)).join('')
binMnemonic = binEntropy + binChecksum
throw "Invalid binMnemonic length : #{binMnemonic.length}" if binMnemonic.length % 11 != 0
mnemonicIndexes = binMnemonic.match(/[01]{11}/g).map (b) -> parseInt(b,2)
mnemonicWords = mnemonicIndexes.map (idx) => @wordlist[idx]
mnemonicWords.join(' ')
checkMnemonicPhraseValid: (mnemonicPhrase) ->
mnemonicWords = @mnemonicWordsFromPhrase(mnemonicPhrase)
mnemonicIndexes = @mnemonicWordsToIndexes(mnemonicWords)
if mnemonicIndexes.length % 3 != 0
throw "Invalid mnemonic length : #{mnemonicIndexes.length}"
if mnemonicIndexes.indexOf(-1) != -1
word = mnemonicPhrase.trim().split(' ')[mnemonicIndexes.indexOf(-1)]
throw "Invalid mnemonic word : #{word}"
mnemonicBin = @mnemonicIndexesToBin(mnemonicIndexes)
[binEntropy, binChecksum] = @splitMnemonicBin(mnemonicBin)
if ! @checkEntropyChecksum(binEntropy, binChecksum)
throw "Checksum error."
return true
# Do not check if mnemonic words are valids.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Array] Mnemonic words in the phrase.
mnemonicWordsFromPhrase: (mnemonicPhrase) ->
mnemonicPhrase.trim().split(/\ /)
# @param [String] mnemonicWord
# @return [Integer] Index of mnemonicWord in wordlist
mnemonicWordToIndex: (mnemonicWord) ->
@wordlist.indexOf(mnemonicWord)
# @param [Array] mnemonicWords
# @return [Array] Indexes of each mnemonicWord in wordlist
mnemonicWordsToIndexes: (mnemonicWords) ->
@mnemonicWordToIndex(mnemonicWord) for mnemonicWord in mnemonicWords
# @return [Array] Return entropy bits and checksum bits.
splitMnemonicBin: (mnemonicBin) ->
# There is a checksum bit for each 33 bits (= 3 mnemonics word) slice.
[mnemonicBin.slice(0, -(mnemonicBin.length/33)), mnemonicBin.slice(-(mnemonicBin.length/33))]
checkEntropyChecksum: (entropyBin, checksumBin) ->
integersEntropy = entropyBin.match(/[01]{32}/g).map (s) -> parseInt(s,2)
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = hashedIntegersEntropy.map (s) => @_intToBin(s, @BITS_IN_INTEGER)
computedChecksumBin = hashedEntropyBinaryArray.join('').slice(0, checksumBin.length)
return computedChecksumBin == checksumBin
mnemonicIndexToBin: (mnemonicIndex) ->
@_intToBin(mnemonicIndex, 11)
mnemonicIndexesToBin: (mnemonicIndexes) ->
(@mnemonicIndexToBin(index) for index in mnemonicIndexes).join('')
# Do not check if mnemonic phrase is valid.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Integer] The number of mnemonic word in the phrase.
mnemonicPhraseLength: (mnemonicPhrase) ->
@mnemonicWordsFromPhrase().length
# @param [String] mnemonicWord A mnemonic word.
# @return [Boolean] Return true if mnemonic word is in wordlist
isMnemonicWordValid: (mnemonicWord) ->
@mnemonicWordToIndex(mnemonicWord) != -1
# Just check if each mnemonic word is valid.
# Do not check checksum, length, etc.
# @param [Array] mnemonicWords An array of mnemonic words.
# @return [Boolean] Return true if each mnemonic word is in wordlist
isMnemonicWordsValid: (mnemonicWords) ->
_.every(mnemonicWords, (word) => @isMnemonicWordValid(word))
_intToBin: (int, binLength) ->
int += 1 if int < 0
str = int.toString(2)
str = str.replace("-","0").replace(/0/g,'a').replace(/1/g,'0').replace(/a/g,'1') if int < 0
str = (if int < 0 then '1' else '0') + str while str.length < binLength
str
for key, value of ledger.bitcoin.bip39 when _(value).isFunction()
ledger.bitcoin.bip39[key] = ledger.bitcoin.bip39[key].bind ledger.bitcoin.bip39 | 47880 | ledger.bitcoin ?= {}
ledger.bitcoin.bip39 ?= {}
_.extend ledger.bitcoin.bip39,
ENTROPY_BIT_LENGTH: 256
BIT_IN_BYTES: 8
BYTES_IN_INTEGER: 4
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
isMnemonicPhraseValid: (mnemonicPhrase) ->
try
@utils.checkMnemonicPhraseValid(mnemonicPhrase) && true
catch e
false
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
mnemonicPhraseToSeed: (mnemonicPhrase, passphrase="") ->
@utils.checkMnemonicPhraseValid(mnemonicPhrase)
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = mnemonic.normalize('<PASSWORD>')
salt = "<PASSWORD>" + passphrase.normalize('<PASSWORD>')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
mnemonicIsValid: (mnemonic) ->
numberOfWords = @numberOfWordsInMnemonic(mnemonic)
return no if (numberOfWords % 3 != 0) or (numberOfWords != @mnemonicWordsNumber())
return no if not @_allWordsInMnemonicAreValid(mnemonic)
# convert wordlist to words indexes
words = mnemonic.split(' ')
wordsIndexes = @_mnemonicArrayToWordsIndexes words
# generate binary array from words indexes
binaryArray = @_integersArrayToBinaryArray wordsIndexes, 11
# extract checksum
entropyBitLength = @_nearest32Multiple binaryArray.length
extractedBinaryChecksum = @_lastBitsOfBinaryArray binaryArray, entropyBitLength / 32
extractedChecksum = @_binaryArrayToInteger extractedBinaryChecksum
# compute checksum
binaryEntropy = @_firstBitsOfBinaryArray binaryArray, entropyBitLength
integersEntropy = @_binaryArrayToIntegersArray binaryEntropy
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = @_integersArrayToBinaryArray hashedIntegersEntropy
computedBinaryChecksum = @_firstBitsOfBinaryArray(hashedEntropyBinaryArray, entropyBitLength / 32)
computedChecksum = @_binaryArrayToInteger computedBinaryChecksum
# verify checksum
return computedChecksum == extractedChecksum
generateMnemonic: (entropyBitLength = @ENTROPY_BIT_LENGTH) ->
# generate entropy bytes array
entropyBytesArray = @_randomEntropyBytesArray(entropyBitLength / @BIT_IN_BYTES)
entropyIntegersArray = @_bytesArrayToIntegersArray(entropyBytesArray)
@entropyToMnemonic(entropyBytesArray, entropyBitLength)
entropyToMnemonic: (entropy, entropyBitLength = @ENTROPY_BIT_LENGTH) ->
# convert it to integers array
if typeof entropy == "string"
entropyIntegersArray = entropy.match(/\w{8}/g).map (h) -> parseInt(h,16)
else if entropy instanceof Uint8Array
entropyIntegersArray = @_bytesArrayToIntegersArray(entropy)
else
entropyIntegersArray = entropy
# apply sha256 to hash
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
# get first x bits of hash
hashedEntropyBinaryArray = @_integersArrayToBinaryArray hashedEntropyIntegersArray
checksum = @_firstBitsOfBinaryArray(hashedEntropyBinaryArray, entropyBitLength / 32)
# compute entropy binary array
entropyBinaryArray = @_integersArrayToBinaryArray entropyIntegersArray
# append checksum to entropy
finalEntropyBinaryArray = @_appendBitsToBinaryArray entropyBinaryArray, checksum
# extract words indexes
wordsIndexes = @_binaryArrayToIntegersArray finalEntropyBinaryArray, 11
# generate wordlist
wordlist = @_wordsIndexesToMnemonicArray wordsIndexes
wordlist.join(' ')
generateSeed: (mnemonic, passphrase = "") ->
return undefined if !@mnemonicIsValid mnemonic
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = mnemonic.normalize('N<PASSWORD>')
salt = "<PASSWORD>" + passphrase.normalize('<PASSWORD>')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
numberOfWordsInMnemonic: (mnemonic) ->
return 0 if not mnemonic? or mnemonic.length == 0
count = 0
words = mnemonic.split ' '
for word in words
count++ if word? and word.length > 0
count
mnemonicWordsNumber: ->
return (@ENTROPY_BIT_LENGTH + @ENTROPY_BIT_LENGTH / 32) / 11
_allWordsInMnemonicAreValid: (mnemonic) ->
return 0 if not mnemonic? or mnemonic.length == 0
words = mnemonic.split ' '
for word in words
return no if ledger.bitcoin.bip39.wordlist.indexOf(word) == -1
return yes
_integersArrayToBinaryArray: (integersArray, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
binaryArray = []
for integer in integersArray
partialBinaryArray = @_integerToBinaryArray integer, integerBitLength
@_appendBitsToBinaryArray binaryArray, partialBinaryArray
binaryArray
_integerToBinaryArray: (integer, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
binaryArray = []
for power in [integerBitLength - 1 .. 0]
val = Math.abs ((integer & (1 << power)) >> power)
binaryArray.push val
binaryArray
_binaryArrayToInteger: (binaryArray) ->
return 0 if binaryArray.length == 0
integer = 0
multiplier = 1
for i in [binaryArray.length - 1 .. 0]
if binaryArray[i] == 1
integer += multiplier
multiplier *= 2
integer
_binaryArrayToIntegersArray: (binaryArray, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
integersArray = []
workingArray = binaryArray.slice()
while workingArray.length > 0
integersArray.push @_binaryArrayToInteger(@_firstBitsOfBinaryArray(workingArray, integerBitLength))
workingArray.splice 0, integerBitLength
integersArray
_bytesArrayToIntegersArray: (bytesArray) ->
i = 0
integerArray = []
while i < bytesArray.length
integer = (bytesArray[i] << (@BIT_IN_BYTES * 3)) + (bytesArray[i + 1] << (@BIT_IN_BYTES * 2)) + (bytesArray[i + 2] << (@BIT_IN_BYTES * 1)) + bytesArray[i + 3]
integerArray.push integer
i += @BYTES_IN_INTEGER
integerArray
_firstBitsOfBinaryArray: (binaryArray, numberOfFirstBits) ->
binaryArray.slice 0, numberOfFirstBits
_lastBitsOfBinaryArray: (binaryArray, numberOfLastBits) ->
binaryArray.slice -numberOfLastBits
_appendBitsToBinaryArray: (binaryArray, bitsToAppend) ->
for bit in bitsToAppend
binaryArray.push bit
binaryArray
_wordsIndexesToMnemonicArray: (indexes) ->
mnemonicArray = []
for index in indexes
mnemonicArray.push ledger.bitcoin.bip39.wordlist[index]
mnemonicArray
_mnemonicArrayToWordsIndexes: (mnemonicArray) ->
indexes = []
for word in mnemonicArray
indexes.push ledger.bitcoin.bip39.wordlist.indexOf word
indexes
_nearest32Multiple: (length) ->
power = 0
while (power + 32) <= length
power += 32
power
_randomEntropyBytesArray: (bytesLength) ->
entropy = new Uint8Array(bytesLength)
crypto.getRandomValues entropy
entropy
utils:
BITS_IN_INTEGER: 8 * 4
wordlist: ledger.bitcoin.bip39.wordlist
# @param [string] entropy A hexadecimal string.
# @return [string] Mnemonic phrase. Phrase may contains 12 to 24 words depending of entropy length.
entropyToMnemonicPhrase: (entropy) ->
throw "Invalid entropy format. Wait a hexadecimal string" if ! entropy.match(/^[0-9a-fA-F]+$/)
throw "Invalid entropy length: #{entropy.length*4}" if entropy.length % 8 != 0
# Compute checksum
entropyIntegersArray = entropy.match(/[0-9a-fA-F]{8}/g).map (h) -> parseInt(h,16)
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
hashedEntropy = hashedEntropyIntegersArray.map((i) => @_intToBin(i,32)).join('')
# 1 checksum bit per 32 bits of entropy.
binChecksum = hashedEntropy.slice(0,entropyIntegersArray.length)
binEntropy = entropyIntegersArray.map((i) => @_intToBin(i,32)).join('')
binMnemonic = binEntropy + binChecksum
throw "Invalid binMnemonic length : #{binMnemonic.length}" if binMnemonic.length % 11 != 0
mnemonicIndexes = binMnemonic.match(/[01]{11}/g).map (b) -> parseInt(b,2)
mnemonicWords = mnemonicIndexes.map (idx) => @wordlist[idx]
mnemonicWords.join(' ')
checkMnemonicPhraseValid: (mnemonicPhrase) ->
mnemonicWords = @mnemonicWordsFromPhrase(mnemonicPhrase)
mnemonicIndexes = @mnemonicWordsToIndexes(mnemonicWords)
if mnemonicIndexes.length % 3 != 0
throw "Invalid mnemonic length : #{mnemonicIndexes.length}"
if mnemonicIndexes.indexOf(-1) != -1
word = mnemonicPhrase.trim().split(' ')[mnemonicIndexes.indexOf(-1)]
throw "Invalid mnemonic word : #{word}"
mnemonicBin = @mnemonicIndexesToBin(mnemonicIndexes)
[binEntropy, binChecksum] = @splitMnemonicBin(mnemonicBin)
if ! @checkEntropyChecksum(binEntropy, binChecksum)
throw "Checksum error."
return true
# Do not check if mnemonic words are valids.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Array] Mnemonic words in the phrase.
mnemonicWordsFromPhrase: (mnemonicPhrase) ->
mnemonicPhrase.trim().split(/\ /)
# @param [String] mnemonicWord
# @return [Integer] Index of mnemonicWord in wordlist
mnemonicWordToIndex: (mnemonicWord) ->
@wordlist.indexOf(mnemonicWord)
# @param [Array] mnemonicWords
# @return [Array] Indexes of each mnemonicWord in wordlist
mnemonicWordsToIndexes: (mnemonicWords) ->
@mnemonicWordToIndex(mnemonicWord) for mnemonicWord in mnemonicWords
# @return [Array] Return entropy bits and checksum bits.
splitMnemonicBin: (mnemonicBin) ->
# There is a checksum bit for each 33 bits (= 3 mnemonics word) slice.
[mnemonicBin.slice(0, -(mnemonicBin.length/33)), mnemonicBin.slice(-(mnemonicBin.length/33))]
checkEntropyChecksum: (entropyBin, checksumBin) ->
integersEntropy = entropyBin.match(/[01]{32}/g).map (s) -> parseInt(s,2)
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = hashedIntegersEntropy.map (s) => @_intToBin(s, @BITS_IN_INTEGER)
computedChecksumBin = hashedEntropyBinaryArray.join('').slice(0, checksumBin.length)
return computedChecksumBin == checksumBin
mnemonicIndexToBin: (mnemonicIndex) ->
@_intToBin(mnemonicIndex, 11)
mnemonicIndexesToBin: (mnemonicIndexes) ->
(@mnemonicIndexToBin(index) for index in mnemonicIndexes).join('')
# Do not check if mnemonic phrase is valid.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Integer] The number of mnemonic word in the phrase.
mnemonicPhraseLength: (mnemonicPhrase) ->
@mnemonicWordsFromPhrase().length
# @param [String] mnemonicWord A mnemonic word.
# @return [Boolean] Return true if mnemonic word is in wordlist
isMnemonicWordValid: (mnemonicWord) ->
@mnemonicWordToIndex(mnemonicWord) != -1
# Just check if each mnemonic word is valid.
# Do not check checksum, length, etc.
# @param [Array] mnemonicWords An array of mnemonic words.
# @return [Boolean] Return true if each mnemonic word is in wordlist
isMnemonicWordsValid: (mnemonicWords) ->
_.every(mnemonicWords, (word) => @isMnemonicWordValid(word))
_intToBin: (int, binLength) ->
int += 1 if int < 0
str = int.toString(2)
str = str.replace("-","0").replace(/0/g,'a').replace(/1/g,'0').replace(/a/g,'1') if int < 0
str = (if int < 0 then '1' else '0') + str while str.length < binLength
str
for key, value of ledger.bitcoin.bip39 when _(value).isFunction()
ledger.bitcoin.bip39[key] = ledger.bitcoin.bip39[key].bind ledger.bitcoin.bip39 | true | ledger.bitcoin ?= {}
ledger.bitcoin.bip39 ?= {}
_.extend ledger.bitcoin.bip39,
ENTROPY_BIT_LENGTH: 256
BIT_IN_BYTES: 8
BYTES_IN_INTEGER: 4
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
isMnemonicPhraseValid: (mnemonicPhrase) ->
try
@utils.checkMnemonicPhraseValid(mnemonicPhrase) && true
catch e
false
# @param [String] mnemonicWords Mnemonic words.
# @return [Array] Mnemonic words in the phrase.
mnemonicPhraseToSeed: (mnemonicPhrase, passphrase="") ->
@utils.checkMnemonicPhraseValid(mnemonicPhrase)
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = mnemonic.normalize('PI:PASSWORD:<PASSWORD>END_PI')
salt = "PI:PASSWORD:<PASSWORD>END_PI" + passphrase.normalize('PI:PASSWORD:<PASSWORD>END_PI')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
mnemonicIsValid: (mnemonic) ->
numberOfWords = @numberOfWordsInMnemonic(mnemonic)
return no if (numberOfWords % 3 != 0) or (numberOfWords != @mnemonicWordsNumber())
return no if not @_allWordsInMnemonicAreValid(mnemonic)
# convert wordlist to words indexes
words = mnemonic.split(' ')
wordsIndexes = @_mnemonicArrayToWordsIndexes words
# generate binary array from words indexes
binaryArray = @_integersArrayToBinaryArray wordsIndexes, 11
# extract checksum
entropyBitLength = @_nearest32Multiple binaryArray.length
extractedBinaryChecksum = @_lastBitsOfBinaryArray binaryArray, entropyBitLength / 32
extractedChecksum = @_binaryArrayToInteger extractedBinaryChecksum
# compute checksum
binaryEntropy = @_firstBitsOfBinaryArray binaryArray, entropyBitLength
integersEntropy = @_binaryArrayToIntegersArray binaryEntropy
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = @_integersArrayToBinaryArray hashedIntegersEntropy
computedBinaryChecksum = @_firstBitsOfBinaryArray(hashedEntropyBinaryArray, entropyBitLength / 32)
computedChecksum = @_binaryArrayToInteger computedBinaryChecksum
# verify checksum
return computedChecksum == extractedChecksum
generateMnemonic: (entropyBitLength = @ENTROPY_BIT_LENGTH) ->
# generate entropy bytes array
entropyBytesArray = @_randomEntropyBytesArray(entropyBitLength / @BIT_IN_BYTES)
entropyIntegersArray = @_bytesArrayToIntegersArray(entropyBytesArray)
@entropyToMnemonic(entropyBytesArray, entropyBitLength)
entropyToMnemonic: (entropy, entropyBitLength = @ENTROPY_BIT_LENGTH) ->
# convert it to integers array
if typeof entropy == "string"
entropyIntegersArray = entropy.match(/\w{8}/g).map (h) -> parseInt(h,16)
else if entropy instanceof Uint8Array
entropyIntegersArray = @_bytesArrayToIntegersArray(entropy)
else
entropyIntegersArray = entropy
# apply sha256 to hash
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
# get first x bits of hash
hashedEntropyBinaryArray = @_integersArrayToBinaryArray hashedEntropyIntegersArray
checksum = @_firstBitsOfBinaryArray(hashedEntropyBinaryArray, entropyBitLength / 32)
# compute entropy binary array
entropyBinaryArray = @_integersArrayToBinaryArray entropyIntegersArray
# append checksum to entropy
finalEntropyBinaryArray = @_appendBitsToBinaryArray entropyBinaryArray, checksum
# extract words indexes
wordsIndexes = @_binaryArrayToIntegersArray finalEntropyBinaryArray, 11
# generate wordlist
wordlist = @_wordsIndexesToMnemonicArray wordsIndexes
wordlist.join(' ')
generateSeed: (mnemonic, passphrase = "") ->
return undefined if !@mnemonicIsValid mnemonic
hmacSHA512 = (key) ->
hasher = new sjcl.misc.hmac(key, sjcl.hash.sha512)
@encrypt = ->
return hasher.encrypt.apply(hasher, arguments)
@
password = mnemonic.normalize('NPI:PASSWORD:<PASSWORD>END_PI')
salt = "PI:PASSWORD:<PASSWORD>END_PI" + passphrase.normalize('PI:PASSWORD:<PASSWORD>END_PI')
passwordBits = sjcl.codec.utf8String.toBits(password)
saltBits = sjcl.codec.utf8String.toBits(salt)
result = sjcl.misc.pbkdf2(passwordBits, saltBits, 2048, 512, hmacSHA512)
hashHex = sjcl.codec.hex.fromBits(result)
return hashHex
numberOfWordsInMnemonic: (mnemonic) ->
return 0 if not mnemonic? or mnemonic.length == 0
count = 0
words = mnemonic.split ' '
for word in words
count++ if word? and word.length > 0
count
mnemonicWordsNumber: ->
return (@ENTROPY_BIT_LENGTH + @ENTROPY_BIT_LENGTH / 32) / 11
_allWordsInMnemonicAreValid: (mnemonic) ->
return 0 if not mnemonic? or mnemonic.length == 0
words = mnemonic.split ' '
for word in words
return no if ledger.bitcoin.bip39.wordlist.indexOf(word) == -1
return yes
_integersArrayToBinaryArray: (integersArray, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
binaryArray = []
for integer in integersArray
partialBinaryArray = @_integerToBinaryArray integer, integerBitLength
@_appendBitsToBinaryArray binaryArray, partialBinaryArray
binaryArray
_integerToBinaryArray: (integer, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
binaryArray = []
for power in [integerBitLength - 1 .. 0]
val = Math.abs ((integer & (1 << power)) >> power)
binaryArray.push val
binaryArray
_binaryArrayToInteger: (binaryArray) ->
return 0 if binaryArray.length == 0
integer = 0
multiplier = 1
for i in [binaryArray.length - 1 .. 0]
if binaryArray[i] == 1
integer += multiplier
multiplier *= 2
integer
_binaryArrayToIntegersArray: (binaryArray, integerBitLength = @BYTES_IN_INTEGER * @BIT_IN_BYTES) ->
integersArray = []
workingArray = binaryArray.slice()
while workingArray.length > 0
integersArray.push @_binaryArrayToInteger(@_firstBitsOfBinaryArray(workingArray, integerBitLength))
workingArray.splice 0, integerBitLength
integersArray
_bytesArrayToIntegersArray: (bytesArray) ->
i = 0
integerArray = []
while i < bytesArray.length
integer = (bytesArray[i] << (@BIT_IN_BYTES * 3)) + (bytesArray[i + 1] << (@BIT_IN_BYTES * 2)) + (bytesArray[i + 2] << (@BIT_IN_BYTES * 1)) + bytesArray[i + 3]
integerArray.push integer
i += @BYTES_IN_INTEGER
integerArray
_firstBitsOfBinaryArray: (binaryArray, numberOfFirstBits) ->
binaryArray.slice 0, numberOfFirstBits
_lastBitsOfBinaryArray: (binaryArray, numberOfLastBits) ->
binaryArray.slice -numberOfLastBits
_appendBitsToBinaryArray: (binaryArray, bitsToAppend) ->
for bit in bitsToAppend
binaryArray.push bit
binaryArray
_wordsIndexesToMnemonicArray: (indexes) ->
mnemonicArray = []
for index in indexes
mnemonicArray.push ledger.bitcoin.bip39.wordlist[index]
mnemonicArray
_mnemonicArrayToWordsIndexes: (mnemonicArray) ->
indexes = []
for word in mnemonicArray
indexes.push ledger.bitcoin.bip39.wordlist.indexOf word
indexes
_nearest32Multiple: (length) ->
power = 0
while (power + 32) <= length
power += 32
power
_randomEntropyBytesArray: (bytesLength) ->
entropy = new Uint8Array(bytesLength)
crypto.getRandomValues entropy
entropy
utils:
BITS_IN_INTEGER: 8 * 4
wordlist: ledger.bitcoin.bip39.wordlist
# @param [string] entropy A hexadecimal string.
# @return [string] Mnemonic phrase. Phrase may contains 12 to 24 words depending of entropy length.
entropyToMnemonicPhrase: (entropy) ->
throw "Invalid entropy format. Wait a hexadecimal string" if ! entropy.match(/^[0-9a-fA-F]+$/)
throw "Invalid entropy length: #{entropy.length*4}" if entropy.length % 8 != 0
# Compute checksum
entropyIntegersArray = entropy.match(/[0-9a-fA-F]{8}/g).map (h) -> parseInt(h,16)
hashedEntropyIntegersArray = sjcl.hash.sha256.hash entropyIntegersArray
hashedEntropy = hashedEntropyIntegersArray.map((i) => @_intToBin(i,32)).join('')
# 1 checksum bit per 32 bits of entropy.
binChecksum = hashedEntropy.slice(0,entropyIntegersArray.length)
binEntropy = entropyIntegersArray.map((i) => @_intToBin(i,32)).join('')
binMnemonic = binEntropy + binChecksum
throw "Invalid binMnemonic length : #{binMnemonic.length}" if binMnemonic.length % 11 != 0
mnemonicIndexes = binMnemonic.match(/[01]{11}/g).map (b) -> parseInt(b,2)
mnemonicWords = mnemonicIndexes.map (idx) => @wordlist[idx]
mnemonicWords.join(' ')
checkMnemonicPhraseValid: (mnemonicPhrase) ->
mnemonicWords = @mnemonicWordsFromPhrase(mnemonicPhrase)
mnemonicIndexes = @mnemonicWordsToIndexes(mnemonicWords)
if mnemonicIndexes.length % 3 != 0
throw "Invalid mnemonic length : #{mnemonicIndexes.length}"
if mnemonicIndexes.indexOf(-1) != -1
word = mnemonicPhrase.trim().split(' ')[mnemonicIndexes.indexOf(-1)]
throw "Invalid mnemonic word : #{word}"
mnemonicBin = @mnemonicIndexesToBin(mnemonicIndexes)
[binEntropy, binChecksum] = @splitMnemonicBin(mnemonicBin)
if ! @checkEntropyChecksum(binEntropy, binChecksum)
throw "Checksum error."
return true
# Do not check if mnemonic words are valids.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Array] Mnemonic words in the phrase.
mnemonicWordsFromPhrase: (mnemonicPhrase) ->
mnemonicPhrase.trim().split(/\ /)
# @param [String] mnemonicWord
# @return [Integer] Index of mnemonicWord in wordlist
mnemonicWordToIndex: (mnemonicWord) ->
@wordlist.indexOf(mnemonicWord)
# @param [Array] mnemonicWords
# @return [Array] Indexes of each mnemonicWord in wordlist
mnemonicWordsToIndexes: (mnemonicWords) ->
@mnemonicWordToIndex(mnemonicWord) for mnemonicWord in mnemonicWords
# @return [Array] Return entropy bits and checksum bits.
splitMnemonicBin: (mnemonicBin) ->
# There is a checksum bit for each 33 bits (= 3 mnemonics word) slice.
[mnemonicBin.slice(0, -(mnemonicBin.length/33)), mnemonicBin.slice(-(mnemonicBin.length/33))]
checkEntropyChecksum: (entropyBin, checksumBin) ->
integersEntropy = entropyBin.match(/[01]{32}/g).map (s) -> parseInt(s,2)
hashedIntegersEntropy = sjcl.hash.sha256.hash integersEntropy
hashedEntropyBinaryArray = hashedIntegersEntropy.map (s) => @_intToBin(s, @BITS_IN_INTEGER)
computedChecksumBin = hashedEntropyBinaryArray.join('').slice(0, checksumBin.length)
return computedChecksumBin == checksumBin
mnemonicIndexToBin: (mnemonicIndex) ->
@_intToBin(mnemonicIndex, 11)
mnemonicIndexesToBin: (mnemonicIndexes) ->
(@mnemonicIndexToBin(index) for index in mnemonicIndexes).join('')
# Do not check if mnemonic phrase is valid.
# @param [String] mnemonicPhrase A mnemonic phrase.
# @return [Integer] The number of mnemonic word in the phrase.
mnemonicPhraseLength: (mnemonicPhrase) ->
@mnemonicWordsFromPhrase().length
# @param [String] mnemonicWord A mnemonic word.
# @return [Boolean] Return true if mnemonic word is in wordlist
isMnemonicWordValid: (mnemonicWord) ->
@mnemonicWordToIndex(mnemonicWord) != -1
# Just check if each mnemonic word is valid.
# Do not check checksum, length, etc.
# @param [Array] mnemonicWords An array of mnemonic words.
# @return [Boolean] Return true if each mnemonic word is in wordlist
isMnemonicWordsValid: (mnemonicWords) ->
_.every(mnemonicWords, (word) => @isMnemonicWordValid(word))
_intToBin: (int, binLength) ->
int += 1 if int < 0
str = int.toString(2)
str = str.replace("-","0").replace(/0/g,'a').replace(/1/g,'0').replace(/a/g,'1') if int < 0
str = (if int < 0 then '1' else '0') + str while str.length < binLength
str
for key, value of ledger.bitcoin.bip39 when _(value).isFunction()
ledger.bitcoin.bip39[key] = ledger.bitcoin.bip39[key].bind ledger.bitcoin.bip39 |
[
{
"context": "t(2)\n\n config = getConfig()\n config.password = 'bad-password'\n\n connection = new Connection(config)\n\n connec",
"end": 1300,
"score": 0.9992919564247131,
"start": 1288,
"tag": "PASSWORD",
"value": "bad-password"
}
] | test/integration/connection-test.coffee | arthurschreiber/tedious | 1 | async = require('async')
Connection = require('../../src/connection')
Request = require('../../src/request')
fs = require('fs')
getConfig = ->
config = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).config
instanceName = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).instanceName
config.options.debug =
packet: true
data: true
payload: true
token: true
log: true
config
process.on 'uncaughtException', (err) ->
console.error err.stack
getInstanceName = ->
JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).instanceName
exports.badServer = (test) ->
config = getConfig()
config.server = 'bad-server'
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
)
connection.on('end', (info) ->
test.done()
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.badPort = (test) ->
config = getConfig()
config.options.port = -1
config.options.connectTimeout = 200
connection = null
test.throws ->
connection = new Connection(config)
test.done()
exports.badCredentials = (test) ->
test.expect(2)
config = getConfig()
config.password = 'bad-password'
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
test.ok(~error.message.indexOf('failed'))
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByPort = (test) ->
config = getConfig()
unless config.options?.port?
# Config says don't do this test (probably because ports are dynamic).
console.log('Skipping connectByPort test')
test.done()
return
test.expect(2)
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByInstanceName = (test) ->
if !getInstanceName()
# Config says don't do this test (probably because SQL Server Browser is not available).
console.log('Skipping connectByInstanceName test')
test.done()
return
test.expect(2)
config = getConfig()
delete config.options.port
config.options.instanceName = getInstanceName()
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByInvalidInstanceName = (test) ->
if !getInstanceName()
# Config says don't do this test (probably because SQL Server Browser is not available).
console.log('Skipping connectByInvalidInstanceName test')
test.done()
return
test.expect(1)
config = getConfig()
delete config.options.port
config.options.instanceName = "#{getInstanceName()}X"
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.encrypt = (test) ->
test.expect(5)
config = getConfig()
config.options.encrypt = true
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('secure', (cleartext) ->
test.ok(cleartext)
test.ok(cleartext.getCipher())
test.ok(cleartext.getPeerCertificate())
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSql = (test) ->
test.expect(7)
config = getConfig()
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 8)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.numericColumnName = (test) ->
test.expect(5)
config = getConfig()
config.options.useColumnNames = true
request = new Request('select 8 as [123]', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(Object.keys(columnsMetadata).length, 1)
)
request.on('row', (columns) ->
test.strictEqual(Object.keys(columns).length, 1)
test.strictEqual(columns[123].value, 8)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.duplicateColumnNames = (test) ->
test.expect(6)
config = getConfig()
config.options.useColumnNames = true
request = new Request('select 1 as abc, 2 as xyz, \'3\' as abc', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(Object.keys(columnsMetadata).length, 2)
)
request.on('row', (columns) ->
test.strictEqual(Object.keys(columns).length, 2)
test.strictEqual(columns.abc.value, 1)
test.strictEqual(columns.xyz.value, 2)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlMultipleTimes = (test) ->
timesToExec = 5
sqlExecCount = 0
test.expect(timesToExec * 7)
config = getConfig()
execSql = ->
if sqlExecCount == timesToExec
connection.close()
return
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
sqlExecCount++
execSql()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 8)
)
connection.execSql(request)
connection = new Connection(config)
connection.on('connect', (err) ->
execSql()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlWithOrder = (test) ->
test.expect(10)
config = getConfig()
sql = "select top 2 object_id, name, column_id, system_type_id from sys.columns order by name, system_type_id"
request = new Request(sql, (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 2)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 2)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 4)
)
request.on('order', (orderColumns) ->
test.strictEqual(orderColumns.length, 2)
test.strictEqual(orderColumns[0], 2)
test.strictEqual(orderColumns[1], 4)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 4)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlMultipleTimes = (test) ->
test.expect(20)
requestsToMake = 5;
config = getConfig()
makeRequest = ->
if requestsToMake == 0
connection.close()
return
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
requestsToMake--
makeRequest()
)
request.on('doneInProc', (rowCount, more) ->
test.strictEqual(rowCount, 1)
#makeRequest()
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
)
connection.execSql(request)
connection = new Connection(config)
connection.on('connect', (err) ->
makeRequest()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execBadSql = (test) ->
test.expect(2)
config = getConfig()
request = new Request('bad syntax here', (err) ->
test.ok(err)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
test.ok(error)
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.sqlWithMultipleResultSets = (test) ->
test.expect(8)
config = getConfig()
row = 0
request = new Request('select 1; select 2;', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 2)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns[0].value, ++row)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCountForUpdate = (test) ->
test.expect(2)
config = getConfig()
row = 0
setupSql = """
create table #tab1 (id int, name nvarchar(10));
insert into #tab1 values(1, N'a1');
insert into #tab1 values(2, N'a2');
insert into #tab1 values(3, N'b1');
update #tab1 set name = 'a3' where name like 'a%'
"""
request = new Request(setupSql, (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 5)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCollectionOnRequestCompletion = (test) ->
test.expect(5)
config = getConfig()
config.options.rowCollectionOnRequestCompletion = true
request = new Request('select 1 as a; select 2 as b;', (err, rowCount, rows) ->
test.strictEqual(rows.length, 2)
test.strictEqual(rows[0][0].metadata.colName, 'a')
test.strictEqual(rows[0][0].value, 1)
test.strictEqual(rows[1][0].metadata.colName, 'b')
test.strictEqual(rows[1][0].value, 2)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCollectionOnDone = (test) ->
test.expect(6)
config = getConfig()
config.options.rowCollectionOnDone = true
doneCount = 0
request = new Request('select 1 as a; select 2 as b;', (err, rowCount, rows) ->
connection.close()
)
request.on('doneInProc', (rowCount, more, rows) ->
test.strictEqual(rows.length, 1)
switch ++doneCount
when 1
test.strictEqual(rows[0][0].metadata.colName, 'a')
test.strictEqual(rows[0][0].value, 1)
when 2
test.strictEqual(rows[0][0].metadata.colName, 'b')
test.strictEqual(rows[0][0].value, 2)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execProcAsSql = (test) ->
test.expect(7)
config = getConfig()
request = new Request('exec sp_help int', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 0)
connection.close()
)
request.on('doneProc', (rowCount, more, returnStatus) ->
test.ok(!more)
test.strictEqual(returnStatus, 0)
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
)
request.on('row', (columns) ->
test.ok(true)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.resetConnection = (test) ->
test.expect(4)
config = getConfig()
testAnsiNullsOptionOn = (callback) ->
testAnsiNullsOption(true, callback)
testAnsiNullsOptionOff = (callback) ->
testAnsiNullsOption(false, callback)
testAnsiNullsOption = (expectedOptionOn, callback) ->
request = new Request('select @@options & 32', (err, rowCount) ->
callback(err)
)
request.on('row', (columns) ->
optionOn = columns[0].value == 32
test.strictEqual(optionOn, expectedOptionOn)
)
connection.execSql(request)
setAnsiNullsOptionOff = (callback) ->
request = new Request('set ansi_nulls off', (err, rowCount) ->
callback(err)
)
connection.execSqlBatch(request)
connection = new Connection(config)
connection.on('resetConnection', ->
test.ok(true)
)
connection.on('connect', (err) ->
async.series([
testAnsiNullsOptionOn,
setAnsiNullsOptionOff,
testAnsiNullsOptionOff,
(callback) ->
connection.reset (err) ->
if connection.config.options.tdsVersion < '7_2'
# TDS 7_1 doesnt send RESETCONNECTION acknowledgement packet
test.ok(true)
callback err
testAnsiNullsOptionOn,
(callback) ->
connection.close()
callback()
])
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.cancelRequest = (test) ->
test.expect(8)
config = getConfig()
request = new Request('select 1 as C1;waitfor delay \'00:00:05\';select 2 as C2', (err, rowCount, rows) ->
test.strictEqual err.message, 'Canceled.'
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok false
)
request.on('doneProc', (rowCount, more) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('done', (rowCount, more, rows) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 1)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
setTimeout(connection.cancel.bind(connection), 2000)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.requestTimeout = (test) ->
test.expect(8)
config = getConfig()
config.options.requestTimeout = 1000
request = new Request('select 1 as C1;waitfor delay \'00:00:05\';select 2 as C2', (err, rowCount, rows) ->
test.equal err.message, 'Timeout: Request failed to complete in 1000ms'
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok false
)
request.on('doneProc', (rowCount, more) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('done', (rowCount, more, rows) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 1)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
| 224485 | async = require('async')
Connection = require('../../src/connection')
Request = require('../../src/request')
fs = require('fs')
getConfig = ->
config = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).config
instanceName = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).instanceName
config.options.debug =
packet: true
data: true
payload: true
token: true
log: true
config
process.on 'uncaughtException', (err) ->
console.error err.stack
getInstanceName = ->
JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).instanceName
exports.badServer = (test) ->
config = getConfig()
config.server = 'bad-server'
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
)
connection.on('end', (info) ->
test.done()
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.badPort = (test) ->
config = getConfig()
config.options.port = -1
config.options.connectTimeout = 200
connection = null
test.throws ->
connection = new Connection(config)
test.done()
exports.badCredentials = (test) ->
test.expect(2)
config = getConfig()
config.password = '<PASSWORD>'
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
test.ok(~error.message.indexOf('failed'))
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByPort = (test) ->
config = getConfig()
unless config.options?.port?
# Config says don't do this test (probably because ports are dynamic).
console.log('Skipping connectByPort test')
test.done()
return
test.expect(2)
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByInstanceName = (test) ->
if !getInstanceName()
# Config says don't do this test (probably because SQL Server Browser is not available).
console.log('Skipping connectByInstanceName test')
test.done()
return
test.expect(2)
config = getConfig()
delete config.options.port
config.options.instanceName = getInstanceName()
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByInvalidInstanceName = (test) ->
if !getInstanceName()
# Config says don't do this test (probably because SQL Server Browser is not available).
console.log('Skipping connectByInvalidInstanceName test')
test.done()
return
test.expect(1)
config = getConfig()
delete config.options.port
config.options.instanceName = "#{getInstanceName()}X"
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.encrypt = (test) ->
test.expect(5)
config = getConfig()
config.options.encrypt = true
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('secure', (cleartext) ->
test.ok(cleartext)
test.ok(cleartext.getCipher())
test.ok(cleartext.getPeerCertificate())
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSql = (test) ->
test.expect(7)
config = getConfig()
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 8)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.numericColumnName = (test) ->
test.expect(5)
config = getConfig()
config.options.useColumnNames = true
request = new Request('select 8 as [123]', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(Object.keys(columnsMetadata).length, 1)
)
request.on('row', (columns) ->
test.strictEqual(Object.keys(columns).length, 1)
test.strictEqual(columns[123].value, 8)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.duplicateColumnNames = (test) ->
test.expect(6)
config = getConfig()
config.options.useColumnNames = true
request = new Request('select 1 as abc, 2 as xyz, \'3\' as abc', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(Object.keys(columnsMetadata).length, 2)
)
request.on('row', (columns) ->
test.strictEqual(Object.keys(columns).length, 2)
test.strictEqual(columns.abc.value, 1)
test.strictEqual(columns.xyz.value, 2)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlMultipleTimes = (test) ->
timesToExec = 5
sqlExecCount = 0
test.expect(timesToExec * 7)
config = getConfig()
execSql = ->
if sqlExecCount == timesToExec
connection.close()
return
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
sqlExecCount++
execSql()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 8)
)
connection.execSql(request)
connection = new Connection(config)
connection.on('connect', (err) ->
execSql()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlWithOrder = (test) ->
test.expect(10)
config = getConfig()
sql = "select top 2 object_id, name, column_id, system_type_id from sys.columns order by name, system_type_id"
request = new Request(sql, (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 2)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 2)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 4)
)
request.on('order', (orderColumns) ->
test.strictEqual(orderColumns.length, 2)
test.strictEqual(orderColumns[0], 2)
test.strictEqual(orderColumns[1], 4)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 4)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlMultipleTimes = (test) ->
test.expect(20)
requestsToMake = 5;
config = getConfig()
makeRequest = ->
if requestsToMake == 0
connection.close()
return
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
requestsToMake--
makeRequest()
)
request.on('doneInProc', (rowCount, more) ->
test.strictEqual(rowCount, 1)
#makeRequest()
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
)
connection.execSql(request)
connection = new Connection(config)
connection.on('connect', (err) ->
makeRequest()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execBadSql = (test) ->
test.expect(2)
config = getConfig()
request = new Request('bad syntax here', (err) ->
test.ok(err)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
test.ok(error)
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.sqlWithMultipleResultSets = (test) ->
test.expect(8)
config = getConfig()
row = 0
request = new Request('select 1; select 2;', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 2)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns[0].value, ++row)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCountForUpdate = (test) ->
test.expect(2)
config = getConfig()
row = 0
setupSql = """
create table #tab1 (id int, name nvarchar(10));
insert into #tab1 values(1, N'a1');
insert into #tab1 values(2, N'a2');
insert into #tab1 values(3, N'b1');
update #tab1 set name = 'a3' where name like 'a%'
"""
request = new Request(setupSql, (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 5)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCollectionOnRequestCompletion = (test) ->
test.expect(5)
config = getConfig()
config.options.rowCollectionOnRequestCompletion = true
request = new Request('select 1 as a; select 2 as b;', (err, rowCount, rows) ->
test.strictEqual(rows.length, 2)
test.strictEqual(rows[0][0].metadata.colName, 'a')
test.strictEqual(rows[0][0].value, 1)
test.strictEqual(rows[1][0].metadata.colName, 'b')
test.strictEqual(rows[1][0].value, 2)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCollectionOnDone = (test) ->
test.expect(6)
config = getConfig()
config.options.rowCollectionOnDone = true
doneCount = 0
request = new Request('select 1 as a; select 2 as b;', (err, rowCount, rows) ->
connection.close()
)
request.on('doneInProc', (rowCount, more, rows) ->
test.strictEqual(rows.length, 1)
switch ++doneCount
when 1
test.strictEqual(rows[0][0].metadata.colName, 'a')
test.strictEqual(rows[0][0].value, 1)
when 2
test.strictEqual(rows[0][0].metadata.colName, 'b')
test.strictEqual(rows[0][0].value, 2)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execProcAsSql = (test) ->
test.expect(7)
config = getConfig()
request = new Request('exec sp_help int', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 0)
connection.close()
)
request.on('doneProc', (rowCount, more, returnStatus) ->
test.ok(!more)
test.strictEqual(returnStatus, 0)
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
)
request.on('row', (columns) ->
test.ok(true)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.resetConnection = (test) ->
test.expect(4)
config = getConfig()
testAnsiNullsOptionOn = (callback) ->
testAnsiNullsOption(true, callback)
testAnsiNullsOptionOff = (callback) ->
testAnsiNullsOption(false, callback)
testAnsiNullsOption = (expectedOptionOn, callback) ->
request = new Request('select @@options & 32', (err, rowCount) ->
callback(err)
)
request.on('row', (columns) ->
optionOn = columns[0].value == 32
test.strictEqual(optionOn, expectedOptionOn)
)
connection.execSql(request)
setAnsiNullsOptionOff = (callback) ->
request = new Request('set ansi_nulls off', (err, rowCount) ->
callback(err)
)
connection.execSqlBatch(request)
connection = new Connection(config)
connection.on('resetConnection', ->
test.ok(true)
)
connection.on('connect', (err) ->
async.series([
testAnsiNullsOptionOn,
setAnsiNullsOptionOff,
testAnsiNullsOptionOff,
(callback) ->
connection.reset (err) ->
if connection.config.options.tdsVersion < '7_2'
# TDS 7_1 doesnt send RESETCONNECTION acknowledgement packet
test.ok(true)
callback err
testAnsiNullsOptionOn,
(callback) ->
connection.close()
callback()
])
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.cancelRequest = (test) ->
test.expect(8)
config = getConfig()
request = new Request('select 1 as C1;waitfor delay \'00:00:05\';select 2 as C2', (err, rowCount, rows) ->
test.strictEqual err.message, 'Canceled.'
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok false
)
request.on('doneProc', (rowCount, more) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('done', (rowCount, more, rows) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 1)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
setTimeout(connection.cancel.bind(connection), 2000)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.requestTimeout = (test) ->
test.expect(8)
config = getConfig()
config.options.requestTimeout = 1000
request = new Request('select 1 as C1;waitfor delay \'00:00:05\';select 2 as C2', (err, rowCount, rows) ->
test.equal err.message, 'Timeout: Request failed to complete in 1000ms'
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok false
)
request.on('doneProc', (rowCount, more) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('done', (rowCount, more, rows) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 1)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
| true | async = require('async')
Connection = require('../../src/connection')
Request = require('../../src/request')
fs = require('fs')
getConfig = ->
config = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).config
instanceName = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).instanceName
config.options.debug =
packet: true
data: true
payload: true
token: true
log: true
config
process.on 'uncaughtException', (err) ->
console.error err.stack
getInstanceName = ->
JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).instanceName
exports.badServer = (test) ->
config = getConfig()
config.server = 'bad-server'
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
)
connection.on('end', (info) ->
test.done()
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.badPort = (test) ->
config = getConfig()
config.options.port = -1
config.options.connectTimeout = 200
connection = null
test.throws ->
connection = new Connection(config)
test.done()
exports.badCredentials = (test) ->
test.expect(2)
config = getConfig()
config.password = 'PI:PASSWORD:<PASSWORD>END_PI'
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
test.ok(~error.message.indexOf('failed'))
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByPort = (test) ->
config = getConfig()
unless config.options?.port?
# Config says don't do this test (probably because ports are dynamic).
console.log('Skipping connectByPort test')
test.done()
return
test.expect(2)
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByInstanceName = (test) ->
if !getInstanceName()
# Config says don't do this test (probably because SQL Server Browser is not available).
console.log('Skipping connectByInstanceName test')
test.done()
return
test.expect(2)
config = getConfig()
delete config.options.port
config.options.instanceName = getInstanceName()
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.connectByInvalidInstanceName = (test) ->
if !getInstanceName()
# Config says don't do this test (probably because SQL Server Browser is not available).
console.log('Skipping connectByInvalidInstanceName test')
test.done()
return
test.expect(1)
config = getConfig()
delete config.options.port
config.options.instanceName = "#{getInstanceName()}X"
connection = new Connection(config)
connection.on('connect', (err) ->
test.ok(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.encrypt = (test) ->
test.expect(5)
config = getConfig()
config.options.encrypt = true
connection = new Connection(config)
connection.on('connect', (err) ->
test.ifError(err)
connection.close()
)
connection.on('end', (info) ->
test.done()
)
connection.on('databaseChange', (database) ->
test.strictEqual(database, config.options.database)
)
connection.on('secure', (cleartext) ->
test.ok(cleartext)
test.ok(cleartext.getCipher())
test.ok(cleartext.getPeerCertificate())
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSql = (test) ->
test.expect(7)
config = getConfig()
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 8)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.numericColumnName = (test) ->
test.expect(5)
config = getConfig()
config.options.useColumnNames = true
request = new Request('select 8 as [123]', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(Object.keys(columnsMetadata).length, 1)
)
request.on('row', (columns) ->
test.strictEqual(Object.keys(columns).length, 1)
test.strictEqual(columns[123].value, 8)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.duplicateColumnNames = (test) ->
test.expect(6)
config = getConfig()
config.options.useColumnNames = true
request = new Request('select 1 as abc, 2 as xyz, \'3\' as abc', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
connection.close()
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(Object.keys(columnsMetadata).length, 2)
)
request.on('row', (columns) ->
test.strictEqual(Object.keys(columns).length, 2)
test.strictEqual(columns.abc.value, 1)
test.strictEqual(columns.xyz.value, 2)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlMultipleTimes = (test) ->
timesToExec = 5
sqlExecCount = 0
test.expect(timesToExec * 7)
config = getConfig()
execSql = ->
if sqlExecCount == timesToExec
connection.close()
return
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
sqlExecCount++
execSql()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 8)
)
connection.execSql(request)
connection = new Connection(config)
connection.on('connect', (err) ->
execSql()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlWithOrder = (test) ->
test.expect(10)
config = getConfig()
sql = "select top 2 object_id, name, column_id, system_type_id from sys.columns order by name, system_type_id"
request = new Request(sql, (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 2)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
test.strictEqual(rowCount, 2)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 4)
)
request.on('order', (orderColumns) ->
test.strictEqual(orderColumns.length, 2)
test.strictEqual(orderColumns[0], 2)
test.strictEqual(orderColumns[1], 4)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 4)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execSqlMultipleTimes = (test) ->
test.expect(20)
requestsToMake = 5;
config = getConfig()
makeRequest = ->
if requestsToMake == 0
connection.close()
return
request = new Request('select 8 as C1', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 1)
requestsToMake--
makeRequest()
)
request.on('doneInProc', (rowCount, more) ->
test.strictEqual(rowCount, 1)
#makeRequest()
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
)
connection.execSql(request)
connection = new Connection(config)
connection.on('connect', (err) ->
makeRequest()
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execBadSql = (test) ->
test.expect(2)
config = getConfig()
request = new Request('bad syntax here', (err) ->
test.ok(err)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('errorMessage', (error) ->
#console.log("#{error.number} : #{error.message}")
test.ok(error)
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.sqlWithMultipleResultSets = (test) ->
test.expect(8)
config = getConfig()
row = 0
request = new Request('select 1; select 2;', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 2)
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.strictEqual(rowCount, 1)
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns[0].value, ++row)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCountForUpdate = (test) ->
test.expect(2)
config = getConfig()
row = 0
setupSql = """
create table #tab1 (id int, name nvarchar(10));
insert into #tab1 values(1, N'a1');
insert into #tab1 values(2, N'a2');
insert into #tab1 values(3, N'b1');
update #tab1 set name = 'a3' where name like 'a%'
"""
request = new Request(setupSql, (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 5)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCollectionOnRequestCompletion = (test) ->
test.expect(5)
config = getConfig()
config.options.rowCollectionOnRequestCompletion = true
request = new Request('select 1 as a; select 2 as b;', (err, rowCount, rows) ->
test.strictEqual(rows.length, 2)
test.strictEqual(rows[0][0].metadata.colName, 'a')
test.strictEqual(rows[0][0].value, 1)
test.strictEqual(rows[1][0].metadata.colName, 'b')
test.strictEqual(rows[1][0].value, 2)
connection.close()
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.rowCollectionOnDone = (test) ->
test.expect(6)
config = getConfig()
config.options.rowCollectionOnDone = true
doneCount = 0
request = new Request('select 1 as a; select 2 as b;', (err, rowCount, rows) ->
connection.close()
)
request.on('doneInProc', (rowCount, more, rows) ->
test.strictEqual(rows.length, 1)
switch ++doneCount
when 1
test.strictEqual(rows[0][0].metadata.colName, 'a')
test.strictEqual(rows[0][0].value, 1)
when 2
test.strictEqual(rows[0][0].metadata.colName, 'b')
test.strictEqual(rows[0][0].value, 2)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.execProcAsSql = (test) ->
test.expect(7)
config = getConfig()
request = new Request('exec sp_help int', (err, rowCount) ->
test.ifError(err)
test.strictEqual(rowCount, 0)
connection.close()
)
request.on('doneProc', (rowCount, more, returnStatus) ->
test.ok(!more)
test.strictEqual(returnStatus, 0)
)
request.on('doneInProc', (rowCount, more) ->
test.ok(more)
)
request.on('row', (columns) ->
test.ok(true)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.resetConnection = (test) ->
test.expect(4)
config = getConfig()
testAnsiNullsOptionOn = (callback) ->
testAnsiNullsOption(true, callback)
testAnsiNullsOptionOff = (callback) ->
testAnsiNullsOption(false, callback)
testAnsiNullsOption = (expectedOptionOn, callback) ->
request = new Request('select @@options & 32', (err, rowCount) ->
callback(err)
)
request.on('row', (columns) ->
optionOn = columns[0].value == 32
test.strictEqual(optionOn, expectedOptionOn)
)
connection.execSql(request)
setAnsiNullsOptionOff = (callback) ->
request = new Request('set ansi_nulls off', (err, rowCount) ->
callback(err)
)
connection.execSqlBatch(request)
connection = new Connection(config)
connection.on('resetConnection', ->
test.ok(true)
)
connection.on('connect', (err) ->
async.series([
testAnsiNullsOptionOn,
setAnsiNullsOptionOff,
testAnsiNullsOptionOff,
(callback) ->
connection.reset (err) ->
if connection.config.options.tdsVersion < '7_2'
# TDS 7_1 doesnt send RESETCONNECTION acknowledgement packet
test.ok(true)
callback err
testAnsiNullsOptionOn,
(callback) ->
connection.close()
callback()
])
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.cancelRequest = (test) ->
test.expect(8)
config = getConfig()
request = new Request('select 1 as C1;waitfor delay \'00:00:05\';select 2 as C2', (err, rowCount, rows) ->
test.strictEqual err.message, 'Canceled.'
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok false
)
request.on('doneProc', (rowCount, more) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('done', (rowCount, more, rows) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 1)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
setTimeout(connection.cancel.bind(connection), 2000)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
exports.requestTimeout = (test) ->
test.expect(8)
config = getConfig()
config.options.requestTimeout = 1000
request = new Request('select 1 as C1;waitfor delay \'00:00:05\';select 2 as C2', (err, rowCount, rows) ->
test.equal err.message, 'Timeout: Request failed to complete in 1000ms'
connection.close()
)
request.on('doneInProc', (rowCount, more) ->
test.ok false
)
request.on('doneProc', (rowCount, more) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('done', (rowCount, more, rows) ->
test.ok !rowCount
test.strictEqual more, false
)
request.on('columnMetadata', (columnsMetadata) ->
test.strictEqual(columnsMetadata.length, 1)
)
request.on('row', (columns) ->
test.strictEqual(columns.length, 1)
test.strictEqual(columns[0].value, 1)
)
connection = new Connection(config)
connection.on('connect', (err) ->
connection.execSql(request)
)
connection.on('end', (info) ->
test.done()
)
connection.on('infoMessage', (info) ->
#console.log("#{info.number} : #{info.message}")
)
connection.on('debug', (text) ->
#console.log(text)
)
|
[
{
"context": "erms of the MIT license.\nCopyright 2012 - 2014 (c) Markus Kohlhase <mail@markus-kohlhase.de>\n###\n\nJOAP_NS = \"jabber:",
"end": 109,
"score": 0.999897301197052,
"start": 94,
"tag": "NAME",
"value": "Markus Kohlhase"
},
{
"context": "cense.\nCopyright 2012 - 2014 (c) ... | dist/bower_components/strophejs-plugins/joap/strophe.joap.coffee | A-StadLabs/labs-002 | 1 | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2014 (c) Markus Kohlhase <mail@markus-kohlhase.de>
###
JOAP_NS = "jabber:iq:joap"
RPC_NS = "jabber:iq:rpc"
# Private static members
conn = null
onError = (cb=->) -> (iq) ->
err = iq.getElementsByTagName("error")[0]
if err?
code = err.getAttribute("code") * 1
msg = err.textContent
msg = "JOAP server is unavailable" if code is 503
cb iq, new JOAPError msg, code
else
cb iq, new JOAPError "Unknown error"
addXMLAttributes = (iq, attrs) ->
return if not attrs?
if attrs instanceof Array
return console?.warn? "No attributes added: \
attribute parameter is not an object"
else if typeof attrs is "object"
for k,v of attrs
iq.c("attribute")
.c("name").t(k).up()
.cnode(conn.rpc._convertToXML v).up().up()
addRPCElements = (iq, method, params=[]) ->
throw new TypeError unless typeof method is "string"
iq.c("methodCall").c("methodName").t(method).up()
if not (params instanceof Array)
console?.warn? "No parameters added: parameter is not an array"
return
if params.length > 0
iq.c("params")
for p in params
iq.c("param")
.cnode(conn.rpc._convertToXML p).up().up()
parseAttributes = (iq) ->
attrs = iq.getElementsByTagName("attribute")
data = {}
for a in attrs
key = a.getElementsByTagName("name")[0].textContent
data[key] = conn.rpc._convertFromXML a.getElementsByTagName("value")[0]
data
parseRPCParams = (iq) ->
conn.rpc._convertFromXML(
iq.getElementsByTagName("param")[0]
.getElementsByTagName("value")[0]
)
parseNewAddress = (iq) ->
a = iq.getElementsByTagName("newAddress")[0]
if a? then new JID(a.textContent).toString()
else undefined
parseSearch = (iq) ->
items = iq.getElementsByTagName("item")
(new JID(i.textContent).toString() for i in items)
parseAttributeDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
type: d.getElementsByTagName("type")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseMethodDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
returnType: d.getElementsByTagName("returnType")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseDesc = (desc) ->
res = {}
if desc instanceof NodeList
for c in desc
res[c.getAttribute "xml:lang"] = c.textContent
else
res.desc[desc.getAttribute "xml:lang"] = desc.textContent
res
parseDescription = (iq) ->
result = desc: {}, attributes: {}, methods: {}, classes: []
describe = iq.getElementsByTagName("describe")[0]
if describe?
for c in describe.childNodes
switch c.tagName.toLowerCase()
when "desc"
result.desc[c.getAttribute "xml:lang"] = c.textContent
when "attributedescription"
ad = parseAttributeDescription c
result.attributes[ad.name] = ad
when "methoddescription"
md = parseMethodDescription c
result.methods[md.name] = md
when "superclass"
result.superclass = new JID(c.textContent).toString()
when "timestamp"
result.timestamp = c.textContent
when "class"
classes.push = c.textContent
result
getAddress = (clazz, service, instance) ->
(new JID clazz, service, instance).toString()
createIq = (type, to, customAttrs) ->
iqType = if (type in ["read", "search", "describe"]) then "get" else "set"
xmlns = if type is "query" then RPC_NS else JOAP_NS
attrs = xmlns: xmlns
attrs[k]=v for k,v of customAttrs when v? if customAttrs?
$iq(to: to, type: iqType).c(type, attrs)
sendRequest = (type, to, cb, opt={}) ->
iq = createIq type, to, opt.attrs
opt.beforeSend? iq
success = (res) -> cb? res, null, opt.onResult?(res)
conn.sendIQ iq, success, onError(cb)
describe = (id, cb) ->
sendRequest "describe", id, cb,
onResult: parseDescription
read = (instance, limits, cb) ->
if typeof limits is "function"
cb = limits; limits = null
sendRequest "read", instance, cb,
beforeSend: (iq) -> if limits instanceof Array
iq.c("name").t(l).up() for l in limits
onResult: parseAttributes
add = (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
sendRequest "add", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
edit = (instance, attrs, cb) ->
sendRequest "edit", instance, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
search = (clazz, attrs, cb) ->
if typeof attrs is "function"
cb = attrs; attrs=null
sendRequest "search", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseSearch
subscribe = (clazz, cb, handler, opt={}) ->
if handler?
ref = conn.addHandler handler, JOAP_NS, "message"
sendRequest "subscribe", clazz, cb,
attrs: { bare: opt.bare, type: opt.type }
onResult: (iq) ->
if handler?
if iq.getAttribute 'type' is 'error'
conn.deleteHandler ref
else
ref
unsubscribe = (clazz, cb, handler, opt={}) ->
sendRequest "unsubscribe", clazz, cb,
attrs: { bare: opt.bare, type: opt.type }
onResult: (iq) ->
if handler?
conn.deleteHandler handler
searchAndRead = (clazz, attrs, limits, cb) ->
if typeof limits is "function"
cb = limits; limits = null
if typeof attrs is "function" and not limits?
cb = attrs; attrs = null
else if attrs instanceof Array and not limits?
limits = attrs; attrs = null
search clazz, attrs, (iq, err, res) ->
if err?
cb err
else
objects = []
count = res.length
if count > 0
readCB = (iq, err, o) ->
if err?
cb err
else
count--
objects.push o
cb null, objects if count is 0
for id in res then do (id) -> read id, limits, readCB
else
cb null, objects
del = (instance, cb) ->
sendRequest "delete", instance, cb
methodCall = (method, address, params, cb) ->
sendRequest "query", address, cb,
beforeSend: (iq) -> addRPCElements iq, method, params
onResult: parseRPCParams
createEventWrapper = (type, jid, fn) ->
return (-> false) unless typeof fn is "function"
match = switch type
when "server"
(from) -> from.domain is jid.domain
when "class"
(from) -> from.user is jid.user and from.domain is jid.domain
when "instance"
(from) -> from.equals jid
(xml) ->
from = new JID xml.getAttribute 'from'
if match from
fn xml, parseAttributes(xml.getElementsByTagName("event")[0]), from
else true
class JOAPError extends Error
constructor: (@message, @code)->
@name = "JOAPError"
class JOAPServer
constructor: (service) ->
@jid = new JID service
describe: (clazz, instance, cb) ->
if typeof clazz is "function"
cb = clazz; clazz = instance = null
else if typeof instance is "function"
cb = instance; instance = null
describe getAddress(clazz, @jid.domain, instance), cb
add: (clazz, attrs, cb) ->
add getAddress(clazz, @jid.domain), attrs, cb
read: (clazz, instance, limits, cb) ->
read getAddress(clazz, @jid.domain, instance), limits, cb
edit: (clazz, instance, attrs, cb) ->
edit getAddress(clazz, @jid.domain, instance), attrs, cb
delete: (clazz, instance, cb) ->
del getAddress(clazz, @jid.domain, instance), cb
search: (clazz, attrs, cb) ->
search getAddress(clazz, @jid.domain), attrs, cb
searchAndRead: (clazz, attrs, limits, cb) ->
searchAndRead getAddress(clazz, @jid.domain), attrs, limits, cb
methodCall: (method, clazz, instance, params, cb) ->
if typeof clazz is "function"
cb = clazz; clazz = instance = params = null
else if typeof instance is "function"
cb = instance; instance = params = null
else if typeof params is "function"
cb = params; params = null
methodCall method, getAddress(clazz, @jid.domain, instance), params, cb
class JOAPObject
constructor: (id) ->
@jid = new JID id
read: (limits, cb) -> read @jid.toString(), limits, cb
edit: (attrs, cb) -> edit @jid.toString(), attrs, cb
describe: (cb) -> describe @jid.toString(), cb
subscribe: (cb, handler, opt) ->
wrapper = createEventWrapper "instance", @jid, handler
subscribe @jid.toString(), cb, wrapper, opt
unsubscribe: (cb, handlerRef, opt) ->
unsubscribe @jid.toString(), cb, handlerRef, opt
methodCall: (method, params, cb) ->
if typeof params is "function"
cb = params; params = null
methodCall method, @jid.toString(), params, cb
class JOAPClass
constructor: (id) ->
@jid = new JID id
describe: (instance, cb) ->
if typeof instance is "function"
cb = instance
instance = null
describe getAddress(@jid.user, @jid.domain, instance), cb
add: (attrs, cb) ->
add getAddress(@jid.user, @jid.domain), attrs, cb
read: (instance, limits, cb) ->
read getAddress(@jid.user, @jid.domain, instance), limits, cb
edit: (instance, attrs, cb) ->
edit getAddress(@jid.user, @jid.domain, instance), attrs, cb
delete: (instance, cb) ->
del getAddress(@jid.user, @jid.domain, instance), cb
search: (attrs, cb) ->
search getAddress(@jid.user, @jid.domain), attrs, cb
searchAndRead: (attrs, limits, cb) ->
searchAndRead getAddress(@jid.user, @jid.domain), attrs, limits, cb
subscribe: (cb, handler, opt) ->
wrapper = createEventWrapper "class", @jid, handler
subscribe getAddress(@jid.user, @jid.domain), cb, wrapper, opt
unsubscribe: (cb, handlerRef, opt) ->
unsubscribe getAddress(@jid.user, @jid.domain), cb, handlerRef, opt
methodCall: (method, instance, params, cb) ->
if typeof instance is "function"
cb = instance; instance = params = null
else if typeof params is "function"
cb = params; params = null
methodCall method, getAddress(@jid.user, @jid.domain, instance), params, cb
Strophe.addConnectionPlugin 'joap', do ->
init = (c) ->
conn = c
Strophe.addNamespace "JOAP", JOAP_NS
if not conn.hasOwnProperty "disco"
Strophe.warn "You need the discovery plugin \
to have JOAP fully implemented."
else
conn.disco.addIdentity "automation", "joap"
conn.disco.addFeature Strophe.NS.JOAP
### public API ###
{
init
describe
add
read
edit
delete: del
search
searchAndRead
methodCall
JOAPError
JOAPServer
JOAPObject
JOAPClass
}
| 124654 | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2014 (c) <NAME> <<EMAIL>>
###
JOAP_NS = "jabber:iq:joap"
RPC_NS = "jabber:iq:rpc"
# Private static members
conn = null
onError = (cb=->) -> (iq) ->
err = iq.getElementsByTagName("error")[0]
if err?
code = err.getAttribute("code") * 1
msg = err.textContent
msg = "JOAP server is unavailable" if code is 503
cb iq, new JOAPError msg, code
else
cb iq, new JOAPError "Unknown error"
addXMLAttributes = (iq, attrs) ->
return if not attrs?
if attrs instanceof Array
return console?.warn? "No attributes added: \
attribute parameter is not an object"
else if typeof attrs is "object"
for k,v of attrs
iq.c("attribute")
.c("name").t(k).up()
.cnode(conn.rpc._convertToXML v).up().up()
addRPCElements = (iq, method, params=[]) ->
throw new TypeError unless typeof method is "string"
iq.c("methodCall").c("methodName").t(method).up()
if not (params instanceof Array)
console?.warn? "No parameters added: parameter is not an array"
return
if params.length > 0
iq.c("params")
for p in params
iq.c("param")
.cnode(conn.rpc._convertToXML p).up().up()
parseAttributes = (iq) ->
attrs = iq.getElementsByTagName("attribute")
data = {}
for a in attrs
key = a.getElementsByTagName("name")[<KEY>
data[key] = conn.rpc._convertFromXML a.getElementsByTagName("value")[0]
data
parseRPCParams = (iq) ->
conn.rpc._convertFromXML(
iq.getElementsByTagName("param")[0]
.getElementsByTagName("value")[0]
)
parseNewAddress = (iq) ->
a = iq.getElementsByTagName("newAddress")[0]
if a? then new JID(a.textContent).toString()
else undefined
parseSearch = (iq) ->
items = iq.getElementsByTagName("item")
(new JID(i.textContent).toString() for i in items)
parseAttributeDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
type: d.getElementsByTagName("type")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseMethodDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
returnType: d.getElementsByTagName("returnType")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseDesc = (desc) ->
res = {}
if desc instanceof NodeList
for c in desc
res[c.getAttribute "xml:lang"] = c.textContent
else
res.desc[desc.getAttribute "xml:lang"] = desc.textContent
res
parseDescription = (iq) ->
result = desc: {}, attributes: {}, methods: {}, classes: []
describe = iq.getElementsByTagName("describe")[0]
if describe?
for c in describe.childNodes
switch c.tagName.toLowerCase()
when "desc"
result.desc[c.getAttribute "xml:lang"] = c.textContent
when "attributedescription"
ad = parseAttributeDescription c
result.attributes[ad.name] = ad
when "methoddescription"
md = parseMethodDescription c
result.methods[md.name] = md
when "superclass"
result.superclass = new JID(c.textContent).toString()
when "timestamp"
result.timestamp = c.textContent
when "class"
classes.push = c.textContent
result
getAddress = (clazz, service, instance) ->
(new JID clazz, service, instance).toString()
createIq = (type, to, customAttrs) ->
iqType = if (type in ["read", "search", "describe"]) then "get" else "set"
xmlns = if type is "query" then RPC_NS else JOAP_NS
attrs = xmlns: xmlns
attrs[k]=v for k,v of customAttrs when v? if customAttrs?
$iq(to: to, type: iqType).c(type, attrs)
sendRequest = (type, to, cb, opt={}) ->
iq = createIq type, to, opt.attrs
opt.beforeSend? iq
success = (res) -> cb? res, null, opt.onResult?(res)
conn.sendIQ iq, success, onError(cb)
describe = (id, cb) ->
sendRequest "describe", id, cb,
onResult: parseDescription
read = (instance, limits, cb) ->
if typeof limits is "function"
cb = limits; limits = null
sendRequest "read", instance, cb,
beforeSend: (iq) -> if limits instanceof Array
iq.c("name").t(l).up() for l in limits
onResult: parseAttributes
add = (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
sendRequest "add", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
edit = (instance, attrs, cb) ->
sendRequest "edit", instance, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
search = (clazz, attrs, cb) ->
if typeof attrs is "function"
cb = attrs; attrs=null
sendRequest "search", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseSearch
subscribe = (clazz, cb, handler, opt={}) ->
if handler?
ref = conn.addHandler handler, JOAP_NS, "message"
sendRequest "subscribe", clazz, cb,
attrs: { bare: opt.bare, type: opt.type }
onResult: (iq) ->
if handler?
if iq.getAttribute 'type' is 'error'
conn.deleteHandler ref
else
ref
unsubscribe = (clazz, cb, handler, opt={}) ->
sendRequest "unsubscribe", clazz, cb,
attrs: { bare: opt.bare, type: opt.type }
onResult: (iq) ->
if handler?
conn.deleteHandler handler
searchAndRead = (clazz, attrs, limits, cb) ->
if typeof limits is "function"
cb = limits; limits = null
if typeof attrs is "function" and not limits?
cb = attrs; attrs = null
else if attrs instanceof Array and not limits?
limits = attrs; attrs = null
search clazz, attrs, (iq, err, res) ->
if err?
cb err
else
objects = []
count = res.length
if count > 0
readCB = (iq, err, o) ->
if err?
cb err
else
count--
objects.push o
cb null, objects if count is 0
for id in res then do (id) -> read id, limits, readCB
else
cb null, objects
del = (instance, cb) ->
sendRequest "delete", instance, cb
methodCall = (method, address, params, cb) ->
sendRequest "query", address, cb,
beforeSend: (iq) -> addRPCElements iq, method, params
onResult: parseRPCParams
createEventWrapper = (type, jid, fn) ->
return (-> false) unless typeof fn is "function"
match = switch type
when "server"
(from) -> from.domain is jid.domain
when "class"
(from) -> from.user is jid.user and from.domain is jid.domain
when "instance"
(from) -> from.equals jid
(xml) ->
from = new JID xml.getAttribute 'from'
if match from
fn xml, parseAttributes(xml.getElementsByTagName("event")[0]), from
else true
class JOAPError extends Error
constructor: (@message, @code)->
@name = "JOAPError"
class JOAPServer
constructor: (service) ->
@jid = new JID service
describe: (clazz, instance, cb) ->
if typeof clazz is "function"
cb = clazz; clazz = instance = null
else if typeof instance is "function"
cb = instance; instance = null
describe getAddress(clazz, @jid.domain, instance), cb
add: (clazz, attrs, cb) ->
add getAddress(clazz, @jid.domain), attrs, cb
read: (clazz, instance, limits, cb) ->
read getAddress(clazz, @jid.domain, instance), limits, cb
edit: (clazz, instance, attrs, cb) ->
edit getAddress(clazz, @jid.domain, instance), attrs, cb
delete: (clazz, instance, cb) ->
del getAddress(clazz, @jid.domain, instance), cb
search: (clazz, attrs, cb) ->
search getAddress(clazz, @jid.domain), attrs, cb
searchAndRead: (clazz, attrs, limits, cb) ->
searchAndRead getAddress(clazz, @jid.domain), attrs, limits, cb
methodCall: (method, clazz, instance, params, cb) ->
if typeof clazz is "function"
cb = clazz; clazz = instance = params = null
else if typeof instance is "function"
cb = instance; instance = params = null
else if typeof params is "function"
cb = params; params = null
methodCall method, getAddress(clazz, @jid.domain, instance), params, cb
class JOAPObject
constructor: (id) ->
@jid = new JID id
read: (limits, cb) -> read @jid.toString(), limits, cb
edit: (attrs, cb) -> edit @jid.toString(), attrs, cb
describe: (cb) -> describe @jid.toString(), cb
subscribe: (cb, handler, opt) ->
wrapper = createEventWrapper "instance", @jid, handler
subscribe @jid.toString(), cb, wrapper, opt
unsubscribe: (cb, handlerRef, opt) ->
unsubscribe @jid.toString(), cb, handlerRef, opt
methodCall: (method, params, cb) ->
if typeof params is "function"
cb = params; params = null
methodCall method, @jid.toString(), params, cb
class JOAPClass
constructor: (id) ->
@jid = new JID id
describe: (instance, cb) ->
if typeof instance is "function"
cb = instance
instance = null
describe getAddress(@jid.user, @jid.domain, instance), cb
add: (attrs, cb) ->
add getAddress(@jid.user, @jid.domain), attrs, cb
read: (instance, limits, cb) ->
read getAddress(@jid.user, @jid.domain, instance), limits, cb
edit: (instance, attrs, cb) ->
edit getAddress(@jid.user, @jid.domain, instance), attrs, cb
delete: (instance, cb) ->
del getAddress(@jid.user, @jid.domain, instance), cb
search: (attrs, cb) ->
search getAddress(@jid.user, @jid.domain), attrs, cb
searchAndRead: (attrs, limits, cb) ->
searchAndRead getAddress(@jid.user, @jid.domain), attrs, limits, cb
subscribe: (cb, handler, opt) ->
wrapper = createEventWrapper "class", @jid, handler
subscribe getAddress(@jid.user, @jid.domain), cb, wrapper, opt
unsubscribe: (cb, handlerRef, opt) ->
unsubscribe getAddress(@jid.user, @jid.domain), cb, handlerRef, opt
methodCall: (method, instance, params, cb) ->
if typeof instance is "function"
cb = instance; instance = params = null
else if typeof params is "function"
cb = params; params = null
methodCall method, getAddress(@jid.user, @jid.domain, instance), params, cb
Strophe.addConnectionPlugin 'joap', do ->
init = (c) ->
conn = c
Strophe.addNamespace "JOAP", JOAP_NS
if not conn.hasOwnProperty "disco"
Strophe.warn "You need the discovery plugin \
to have JOAP fully implemented."
else
conn.disco.addIdentity "automation", "joap"
conn.disco.addFeature Strophe.NS.JOAP
### public API ###
{
init
describe
add
read
edit
delete: del
search
searchAndRead
methodCall
JOAPError
JOAPServer
JOAPObject
JOAPClass
}
| true | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2014 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
JOAP_NS = "jabber:iq:joap"
RPC_NS = "jabber:iq:rpc"
# Private static members
conn = null
onError = (cb=->) -> (iq) ->
err = iq.getElementsByTagName("error")[0]
if err?
code = err.getAttribute("code") * 1
msg = err.textContent
msg = "JOAP server is unavailable" if code is 503
cb iq, new JOAPError msg, code
else
cb iq, new JOAPError "Unknown error"
addXMLAttributes = (iq, attrs) ->
return if not attrs?
if attrs instanceof Array
return console?.warn? "No attributes added: \
attribute parameter is not an object"
else if typeof attrs is "object"
for k,v of attrs
iq.c("attribute")
.c("name").t(k).up()
.cnode(conn.rpc._convertToXML v).up().up()
addRPCElements = (iq, method, params=[]) ->
throw new TypeError unless typeof method is "string"
iq.c("methodCall").c("methodName").t(method).up()
if not (params instanceof Array)
console?.warn? "No parameters added: parameter is not an array"
return
if params.length > 0
iq.c("params")
for p in params
iq.c("param")
.cnode(conn.rpc._convertToXML p).up().up()
parseAttributes = (iq) ->
attrs = iq.getElementsByTagName("attribute")
data = {}
for a in attrs
key = a.getElementsByTagName("name")[PI:KEY:<KEY>END_PI
data[key] = conn.rpc._convertFromXML a.getElementsByTagName("value")[0]
data
parseRPCParams = (iq) ->
conn.rpc._convertFromXML(
iq.getElementsByTagName("param")[0]
.getElementsByTagName("value")[0]
)
parseNewAddress = (iq) ->
a = iq.getElementsByTagName("newAddress")[0]
if a? then new JID(a.textContent).toString()
else undefined
parseSearch = (iq) ->
items = iq.getElementsByTagName("item")
(new JID(i.textContent).toString() for i in items)
parseAttributeDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
type: d.getElementsByTagName("type")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseMethodDescription = (d) ->
name: d.getElementsByTagName("name")[0]?.textContent
returnType: d.getElementsByTagName("returnType")[0]?.textContent
desc: parseDesc d.getElementsByTagName("desc")
parseDesc = (desc) ->
res = {}
if desc instanceof NodeList
for c in desc
res[c.getAttribute "xml:lang"] = c.textContent
else
res.desc[desc.getAttribute "xml:lang"] = desc.textContent
res
parseDescription = (iq) ->
result = desc: {}, attributes: {}, methods: {}, classes: []
describe = iq.getElementsByTagName("describe")[0]
if describe?
for c in describe.childNodes
switch c.tagName.toLowerCase()
when "desc"
result.desc[c.getAttribute "xml:lang"] = c.textContent
when "attributedescription"
ad = parseAttributeDescription c
result.attributes[ad.name] = ad
when "methoddescription"
md = parseMethodDescription c
result.methods[md.name] = md
when "superclass"
result.superclass = new JID(c.textContent).toString()
when "timestamp"
result.timestamp = c.textContent
when "class"
classes.push = c.textContent
result
getAddress = (clazz, service, instance) ->
(new JID clazz, service, instance).toString()
createIq = (type, to, customAttrs) ->
iqType = if (type in ["read", "search", "describe"]) then "get" else "set"
xmlns = if type is "query" then RPC_NS else JOAP_NS
attrs = xmlns: xmlns
attrs[k]=v for k,v of customAttrs when v? if customAttrs?
$iq(to: to, type: iqType).c(type, attrs)
sendRequest = (type, to, cb, opt={}) ->
iq = createIq type, to, opt.attrs
opt.beforeSend? iq
success = (res) -> cb? res, null, opt.onResult?(res)
conn.sendIQ iq, success, onError(cb)
describe = (id, cb) ->
sendRequest "describe", id, cb,
onResult: parseDescription
read = (instance, limits, cb) ->
if typeof limits is "function"
cb = limits; limits = null
sendRequest "read", instance, cb,
beforeSend: (iq) -> if limits instanceof Array
iq.c("name").t(l).up() for l in limits
onResult: parseAttributes
add = (clazz, attrs, cb) ->
cb = attrs if typeof attrs is "function"
sendRequest "add", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
edit = (instance, attrs, cb) ->
sendRequest "edit", instance, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseNewAddress
search = (clazz, attrs, cb) ->
if typeof attrs is "function"
cb = attrs; attrs=null
sendRequest "search", clazz, cb,
beforeSend: (iq) -> addXMLAttributes iq, attrs
onResult: parseSearch
subscribe = (clazz, cb, handler, opt={}) ->
if handler?
ref = conn.addHandler handler, JOAP_NS, "message"
sendRequest "subscribe", clazz, cb,
attrs: { bare: opt.bare, type: opt.type }
onResult: (iq) ->
if handler?
if iq.getAttribute 'type' is 'error'
conn.deleteHandler ref
else
ref
unsubscribe = (clazz, cb, handler, opt={}) ->
sendRequest "unsubscribe", clazz, cb,
attrs: { bare: opt.bare, type: opt.type }
onResult: (iq) ->
if handler?
conn.deleteHandler handler
searchAndRead = (clazz, attrs, limits, cb) ->
if typeof limits is "function"
cb = limits; limits = null
if typeof attrs is "function" and not limits?
cb = attrs; attrs = null
else if attrs instanceof Array and not limits?
limits = attrs; attrs = null
search clazz, attrs, (iq, err, res) ->
if err?
cb err
else
objects = []
count = res.length
if count > 0
readCB = (iq, err, o) ->
if err?
cb err
else
count--
objects.push o
cb null, objects if count is 0
for id in res then do (id) -> read id, limits, readCB
else
cb null, objects
del = (instance, cb) ->
sendRequest "delete", instance, cb
methodCall = (method, address, params, cb) ->
sendRequest "query", address, cb,
beforeSend: (iq) -> addRPCElements iq, method, params
onResult: parseRPCParams
createEventWrapper = (type, jid, fn) ->
return (-> false) unless typeof fn is "function"
match = switch type
when "server"
(from) -> from.domain is jid.domain
when "class"
(from) -> from.user is jid.user and from.domain is jid.domain
when "instance"
(from) -> from.equals jid
(xml) ->
from = new JID xml.getAttribute 'from'
if match from
fn xml, parseAttributes(xml.getElementsByTagName("event")[0]), from
else true
class JOAPError extends Error
constructor: (@message, @code)->
@name = "JOAPError"
class JOAPServer
constructor: (service) ->
@jid = new JID service
describe: (clazz, instance, cb) ->
if typeof clazz is "function"
cb = clazz; clazz = instance = null
else if typeof instance is "function"
cb = instance; instance = null
describe getAddress(clazz, @jid.domain, instance), cb
add: (clazz, attrs, cb) ->
add getAddress(clazz, @jid.domain), attrs, cb
read: (clazz, instance, limits, cb) ->
read getAddress(clazz, @jid.domain, instance), limits, cb
edit: (clazz, instance, attrs, cb) ->
edit getAddress(clazz, @jid.domain, instance), attrs, cb
delete: (clazz, instance, cb) ->
del getAddress(clazz, @jid.domain, instance), cb
search: (clazz, attrs, cb) ->
search getAddress(clazz, @jid.domain), attrs, cb
searchAndRead: (clazz, attrs, limits, cb) ->
searchAndRead getAddress(clazz, @jid.domain), attrs, limits, cb
methodCall: (method, clazz, instance, params, cb) ->
if typeof clazz is "function"
cb = clazz; clazz = instance = params = null
else if typeof instance is "function"
cb = instance; instance = params = null
else if typeof params is "function"
cb = params; params = null
methodCall method, getAddress(clazz, @jid.domain, instance), params, cb
class JOAPObject
constructor: (id) ->
@jid = new JID id
read: (limits, cb) -> read @jid.toString(), limits, cb
edit: (attrs, cb) -> edit @jid.toString(), attrs, cb
describe: (cb) -> describe @jid.toString(), cb
subscribe: (cb, handler, opt) ->
wrapper = createEventWrapper "instance", @jid, handler
subscribe @jid.toString(), cb, wrapper, opt
unsubscribe: (cb, handlerRef, opt) ->
unsubscribe @jid.toString(), cb, handlerRef, opt
methodCall: (method, params, cb) ->
if typeof params is "function"
cb = params; params = null
methodCall method, @jid.toString(), params, cb
class JOAPClass
constructor: (id) ->
@jid = new JID id
describe: (instance, cb) ->
if typeof instance is "function"
cb = instance
instance = null
describe getAddress(@jid.user, @jid.domain, instance), cb
add: (attrs, cb) ->
add getAddress(@jid.user, @jid.domain), attrs, cb
read: (instance, limits, cb) ->
read getAddress(@jid.user, @jid.domain, instance), limits, cb
edit: (instance, attrs, cb) ->
edit getAddress(@jid.user, @jid.domain, instance), attrs, cb
delete: (instance, cb) ->
del getAddress(@jid.user, @jid.domain, instance), cb
search: (attrs, cb) ->
search getAddress(@jid.user, @jid.domain), attrs, cb
searchAndRead: (attrs, limits, cb) ->
searchAndRead getAddress(@jid.user, @jid.domain), attrs, limits, cb
subscribe: (cb, handler, opt) ->
wrapper = createEventWrapper "class", @jid, handler
subscribe getAddress(@jid.user, @jid.domain), cb, wrapper, opt
unsubscribe: (cb, handlerRef, opt) ->
unsubscribe getAddress(@jid.user, @jid.domain), cb, handlerRef, opt
methodCall: (method, instance, params, cb) ->
if typeof instance is "function"
cb = instance; instance = params = null
else if typeof params is "function"
cb = params; params = null
methodCall method, getAddress(@jid.user, @jid.domain, instance), params, cb
Strophe.addConnectionPlugin 'joap', do ->
init = (c) ->
conn = c
Strophe.addNamespace "JOAP", JOAP_NS
if not conn.hasOwnProperty "disco"
Strophe.warn "You need the discovery plugin \
to have JOAP fully implemented."
else
conn.disco.addIdentity "automation", "joap"
conn.disco.addFeature Strophe.NS.JOAP
### public API ###
{
init
describe
add
read
edit
delete: del
search
searchAndRead
methodCall
JOAPError
JOAPServer
JOAPObject
JOAPClass
}
|
[
{
"context": "ctoryPath, fileName)\n\n customDirectoryNameKey = '_directoryName'\n customFilesKey = '_files'\n customFileName",
"end": 2424,
"score": 0.9911615252494812,
"start": 2409,
"tag": "KEY",
"value": "'_directoryName"
},
{
"context": "oryNameKey = '_directoryName'\n ... | test/indexSpec.coffee | jeffreymorganio/file-size-tree-js | 1 | 'use strict'
fs = require('fs')
tmp = require('tmp')
path = require('path')
touch = require('touch')
chai = require('chai')
chai.use(require('chai-things'))
assert = chai.assert
expect = chai.expect
should = chai.should()
fileSizeTree = require('../src/index')
NOT_FOUND = -1
describe 'The fileSizeTree() function', ->
tmp.setGracefulCleanup()
it 'should be defined', ->
assert.isDefined(fileSizeTree)
it 'should return null when the path is null', ->
directoryPath = null
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should return null when the path is empty', ->
directoryPath = ''
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should return null when the path is not a directory', ->
directoryPath = '/not/a/path/to/a/directory'
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should not return null for a valid directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree).to.exist
it 'should return an object for a valid directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree).to.be.an('object')
it 'should return a tree object representing an empty directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree.directoryName).to.equal(path.basename(testDirectoryPath))
expect(tree.files.length).to.equal(0)
it 'should return a tree object representing a directory with one file', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
fileName = 'a'
createFile(testDirectoryPath, fileName)
tree = fileSizeTree(testDirectoryPath)
expect(tree.directoryName).to.equal(path.basename(testDirectoryPath))
expect(tree.files.length).to.equal(1)
file = tree.files[0]
expect(file.fileName).to.equal(fileName)
expect(file.size).to.equal(0)
it 'should return a tree object representing a directory with one file using custom tree object key names', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
fileName = 'a'
createFile(testDirectoryPath, fileName)
customDirectoryNameKey = '_directoryName'
customFilesKey = '_files'
customFileNameKey = '_filename'
customFileSizeKey = '_size'
options =
directoryName: customDirectoryNameKey
files: customFilesKey
fileName: customFileNameKey
fileSize: customFileSizeKey
tree = fileSizeTree(testDirectoryPath, options)
expect(tree[customDirectoryNameKey]).to.equal(path.basename(testDirectoryPath))
expect(tree[customFilesKey].length).to.equal(1)
file = tree[customFilesKey][0]
expect(file[customFileNameKey]).to.equal(fileName)
expect(file[customFileSizeKey]).to.equal(0)
it 'should return a tree object representing a directory structure', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
directoryNameA = 'A'
directoryA = path.join(testDirectoryPath, directoryNameA)
createDirectory(testDirectoryPath, directoryNameA)
directoryNameB = 'B'
directoryB = path.join(directoryA, directoryNameB)
createDirectory(directoryA, directoryNameB)
directoryNameC = 'C'
directoryC = path.join(testDirectoryPath, directoryNameC)
createDirectory(testDirectoryPath, directoryNameC)
fileNameA1 = 'a1'; createFile(directoryA, fileNameA1)
fileNameA2 = 'a2'; createFile(directoryA, fileNameA2)
fileNameB1 = 'b1'; createFile(directoryB, fileNameB1)
fileNameB2 = 'b2'; createFile(directoryB, fileNameB2)
fileNameC1 = 'c1'; createFile(directoryC, fileNameC1)
fileNameC2 = 'c2'; createFile(directoryC, fileNameC2)
testFileObjectA1 = { fileName: fileNameA1, size: 0 }
testFileObjectA2 = { fileName: fileNameA2, size: 0 }
testFileObjectB1 = { fileName: fileNameB1, size: 0 }
testFileObjectB2 = { fileName: fileNameB2, size: 0 }
testFileObjectC1 = { fileName: fileNameC1, size: 0 }
testFileObjectC2 = { fileName: fileNameC2, size: 0 }
tree = fileSizeTree(testDirectoryPath)
# Check for presence of directory A
indexOfActualDirectoryA = indexOfDirectoryObject(tree, directoryNameA)
assert.isAbove(indexOfActualDirectoryA, NOT_FOUND)
actualDirectoryA = tree.files[indexOfActualDirectoryA]
actualDirectoryA.files.should.include.something.that.deep.equals(testFileObjectA1)
actualDirectoryA.files.should.include.something.that.deep.equals(testFileObjectA2)
# Check for presence of directory B within directory A
indexOfActualDirectoryB = indexOfDirectoryObject(actualDirectoryA, directoryNameB)
assert.isAbove(indexOfActualDirectoryB, NOT_FOUND)
actualDirectoryB = actualDirectoryA.files[indexOfActualDirectoryB]
expect(actualDirectoryB.directoryName).to.equal(directoryNameB)
actualDirectoryB.files.should.include.something.that.deep.equals(testFileObjectB1)
actualDirectoryB.files.should.include.something.that.deep.equals(testFileObjectB2)
# Check for presence of directory C
indexOfActualDirectoryC = indexOfDirectoryObject(tree, directoryNameC)
assert.isAbove(indexOfActualDirectoryC, NOT_FOUND)
actualDirectoryC = tree.files[indexOfActualDirectoryC]
expect(actualDirectoryC.directoryName).to.equal(directoryNameC)
actualDirectoryC.files.should.include.something.that.deep.equals(testFileObjectC1)
actualDirectoryC.files.should.include.something.that.deep.equals(testFileObjectC2)
indexOfDirectoryObject = (treeNode, directoryName) ->
foundAtIndex = NOT_FOUND
treeNode.files.forEach (fileObject, index) ->
if fileObject.directoryName and fileObject.directoryName is directoryName
foundAtIndex = index
foundAtIndex
createTestDirectory = ->
tmp.dirSync()
createDirectory = (pathTo, directoryName) ->
fs.mkdirSync(path.join(pathTo, directoryName))
createFile = (pathTo, filename) ->
touch.sync(path.join(pathTo, filename))
| 222492 | 'use strict'
fs = require('fs')
tmp = require('tmp')
path = require('path')
touch = require('touch')
chai = require('chai')
chai.use(require('chai-things'))
assert = chai.assert
expect = chai.expect
should = chai.should()
fileSizeTree = require('../src/index')
NOT_FOUND = -1
describe 'The fileSizeTree() function', ->
tmp.setGracefulCleanup()
it 'should be defined', ->
assert.isDefined(fileSizeTree)
it 'should return null when the path is null', ->
directoryPath = null
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should return null when the path is empty', ->
directoryPath = ''
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should return null when the path is not a directory', ->
directoryPath = '/not/a/path/to/a/directory'
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should not return null for a valid directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree).to.exist
it 'should return an object for a valid directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree).to.be.an('object')
it 'should return a tree object representing an empty directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree.directoryName).to.equal(path.basename(testDirectoryPath))
expect(tree.files.length).to.equal(0)
it 'should return a tree object representing a directory with one file', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
fileName = 'a'
createFile(testDirectoryPath, fileName)
tree = fileSizeTree(testDirectoryPath)
expect(tree.directoryName).to.equal(path.basename(testDirectoryPath))
expect(tree.files.length).to.equal(1)
file = tree.files[0]
expect(file.fileName).to.equal(fileName)
expect(file.size).to.equal(0)
it 'should return a tree object representing a directory with one file using custom tree object key names', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
fileName = 'a'
createFile(testDirectoryPath, fileName)
customDirectoryNameKey = <KEY>'
customFilesKey = <KEY>'
customFileNameKey = <KEY>'
customFileSizeKey = <KEY>'
options =
directoryName: customDirectoryNameKey
files: customFilesKey
fileName: customFileNameKey
fileSize: customFileSizeKey
tree = fileSizeTree(testDirectoryPath, options)
expect(tree[customDirectoryNameKey]).to.equal(path.basename(testDirectoryPath))
expect(tree[customFilesKey].length).to.equal(1)
file = tree[customFilesKey][0]
expect(file[customFileNameKey]).to.equal(fileName)
expect(file[customFileSizeKey]).to.equal(0)
it 'should return a tree object representing a directory structure', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
directoryNameA = 'A'
directoryA = path.join(testDirectoryPath, directoryNameA)
createDirectory(testDirectoryPath, directoryNameA)
directoryNameB = 'B'
directoryB = path.join(directoryA, directoryNameB)
createDirectory(directoryA, directoryNameB)
directoryNameC = 'C'
directoryC = path.join(testDirectoryPath, directoryNameC)
createDirectory(testDirectoryPath, directoryNameC)
fileNameA1 = 'a1'; createFile(directoryA, fileNameA1)
fileNameA2 = 'a2'; createFile(directoryA, fileNameA2)
fileNameB1 = 'b1'; createFile(directoryB, fileNameB1)
fileNameB2 = 'b2'; createFile(directoryB, fileNameB2)
fileNameC1 = 'c1'; createFile(directoryC, fileNameC1)
fileNameC2 = 'c2'; createFile(directoryC, fileNameC2)
testFileObjectA1 = { fileName: fileNameA1, size: 0 }
testFileObjectA2 = { fileName: fileNameA2, size: 0 }
testFileObjectB1 = { fileName: fileNameB1, size: 0 }
testFileObjectB2 = { fileName: fileNameB2, size: 0 }
testFileObjectC1 = { fileName: fileNameC1, size: 0 }
testFileObjectC2 = { fileName: fileNameC2, size: 0 }
tree = fileSizeTree(testDirectoryPath)
# Check for presence of directory A
indexOfActualDirectoryA = indexOfDirectoryObject(tree, directoryNameA)
assert.isAbove(indexOfActualDirectoryA, NOT_FOUND)
actualDirectoryA = tree.files[indexOfActualDirectoryA]
actualDirectoryA.files.should.include.something.that.deep.equals(testFileObjectA1)
actualDirectoryA.files.should.include.something.that.deep.equals(testFileObjectA2)
# Check for presence of directory B within directory A
indexOfActualDirectoryB = indexOfDirectoryObject(actualDirectoryA, directoryNameB)
assert.isAbove(indexOfActualDirectoryB, NOT_FOUND)
actualDirectoryB = actualDirectoryA.files[indexOfActualDirectoryB]
expect(actualDirectoryB.directoryName).to.equal(directoryNameB)
actualDirectoryB.files.should.include.something.that.deep.equals(testFileObjectB1)
actualDirectoryB.files.should.include.something.that.deep.equals(testFileObjectB2)
# Check for presence of directory C
indexOfActualDirectoryC = indexOfDirectoryObject(tree, directoryNameC)
assert.isAbove(indexOfActualDirectoryC, NOT_FOUND)
actualDirectoryC = tree.files[indexOfActualDirectoryC]
expect(actualDirectoryC.directoryName).to.equal(directoryNameC)
actualDirectoryC.files.should.include.something.that.deep.equals(testFileObjectC1)
actualDirectoryC.files.should.include.something.that.deep.equals(testFileObjectC2)
indexOfDirectoryObject = (treeNode, directoryName) ->
foundAtIndex = NOT_FOUND
treeNode.files.forEach (fileObject, index) ->
if fileObject.directoryName and fileObject.directoryName is directoryName
foundAtIndex = index
foundAtIndex
createTestDirectory = ->
tmp.dirSync()
createDirectory = (pathTo, directoryName) ->
fs.mkdirSync(path.join(pathTo, directoryName))
createFile = (pathTo, filename) ->
touch.sync(path.join(pathTo, filename))
| true | 'use strict'
fs = require('fs')
tmp = require('tmp')
path = require('path')
touch = require('touch')
chai = require('chai')
chai.use(require('chai-things'))
assert = chai.assert
expect = chai.expect
should = chai.should()
fileSizeTree = require('../src/index')
NOT_FOUND = -1
describe 'The fileSizeTree() function', ->
tmp.setGracefulCleanup()
it 'should be defined', ->
assert.isDefined(fileSizeTree)
it 'should return null when the path is null', ->
directoryPath = null
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should return null when the path is empty', ->
directoryPath = ''
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should return null when the path is not a directory', ->
directoryPath = '/not/a/path/to/a/directory'
tree = fileSizeTree(directoryPath)
assert.isNull(tree)
it 'should not return null for a valid directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree).to.exist
it 'should return an object for a valid directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree).to.be.an('object')
it 'should return a tree object representing an empty directory', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
tree = fileSizeTree(testDirectoryPath)
expect(tree.directoryName).to.equal(path.basename(testDirectoryPath))
expect(tree.files.length).to.equal(0)
it 'should return a tree object representing a directory with one file', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
fileName = 'a'
createFile(testDirectoryPath, fileName)
tree = fileSizeTree(testDirectoryPath)
expect(tree.directoryName).to.equal(path.basename(testDirectoryPath))
expect(tree.files.length).to.equal(1)
file = tree.files[0]
expect(file.fileName).to.equal(fileName)
expect(file.size).to.equal(0)
it 'should return a tree object representing a directory with one file using custom tree object key names', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
fileName = 'a'
createFile(testDirectoryPath, fileName)
customDirectoryNameKey = PI:KEY:<KEY>END_PI'
customFilesKey = PI:KEY:<KEY>END_PI'
customFileNameKey = PI:KEY:<KEY>END_PI'
customFileSizeKey = PI:KEY:<KEY>END_PI'
options =
directoryName: customDirectoryNameKey
files: customFilesKey
fileName: customFileNameKey
fileSize: customFileSizeKey
tree = fileSizeTree(testDirectoryPath, options)
expect(tree[customDirectoryNameKey]).to.equal(path.basename(testDirectoryPath))
expect(tree[customFilesKey].length).to.equal(1)
file = tree[customFilesKey][0]
expect(file[customFileNameKey]).to.equal(fileName)
expect(file[customFileSizeKey]).to.equal(0)
it 'should return a tree object representing a directory structure', ->
testDirectory = createTestDirectory()
testDirectoryPath = testDirectory.name
directoryNameA = 'A'
directoryA = path.join(testDirectoryPath, directoryNameA)
createDirectory(testDirectoryPath, directoryNameA)
directoryNameB = 'B'
directoryB = path.join(directoryA, directoryNameB)
createDirectory(directoryA, directoryNameB)
directoryNameC = 'C'
directoryC = path.join(testDirectoryPath, directoryNameC)
createDirectory(testDirectoryPath, directoryNameC)
fileNameA1 = 'a1'; createFile(directoryA, fileNameA1)
fileNameA2 = 'a2'; createFile(directoryA, fileNameA2)
fileNameB1 = 'b1'; createFile(directoryB, fileNameB1)
fileNameB2 = 'b2'; createFile(directoryB, fileNameB2)
fileNameC1 = 'c1'; createFile(directoryC, fileNameC1)
fileNameC2 = 'c2'; createFile(directoryC, fileNameC2)
testFileObjectA1 = { fileName: fileNameA1, size: 0 }
testFileObjectA2 = { fileName: fileNameA2, size: 0 }
testFileObjectB1 = { fileName: fileNameB1, size: 0 }
testFileObjectB2 = { fileName: fileNameB2, size: 0 }
testFileObjectC1 = { fileName: fileNameC1, size: 0 }
testFileObjectC2 = { fileName: fileNameC2, size: 0 }
tree = fileSizeTree(testDirectoryPath)
# Check for presence of directory A
indexOfActualDirectoryA = indexOfDirectoryObject(tree, directoryNameA)
assert.isAbove(indexOfActualDirectoryA, NOT_FOUND)
actualDirectoryA = tree.files[indexOfActualDirectoryA]
actualDirectoryA.files.should.include.something.that.deep.equals(testFileObjectA1)
actualDirectoryA.files.should.include.something.that.deep.equals(testFileObjectA2)
# Check for presence of directory B within directory A
indexOfActualDirectoryB = indexOfDirectoryObject(actualDirectoryA, directoryNameB)
assert.isAbove(indexOfActualDirectoryB, NOT_FOUND)
actualDirectoryB = actualDirectoryA.files[indexOfActualDirectoryB]
expect(actualDirectoryB.directoryName).to.equal(directoryNameB)
actualDirectoryB.files.should.include.something.that.deep.equals(testFileObjectB1)
actualDirectoryB.files.should.include.something.that.deep.equals(testFileObjectB2)
# Check for presence of directory C
indexOfActualDirectoryC = indexOfDirectoryObject(tree, directoryNameC)
assert.isAbove(indexOfActualDirectoryC, NOT_FOUND)
actualDirectoryC = tree.files[indexOfActualDirectoryC]
expect(actualDirectoryC.directoryName).to.equal(directoryNameC)
actualDirectoryC.files.should.include.something.that.deep.equals(testFileObjectC1)
actualDirectoryC.files.should.include.something.that.deep.equals(testFileObjectC2)
indexOfDirectoryObject = (treeNode, directoryName) ->
foundAtIndex = NOT_FOUND
treeNode.files.forEach (fileObject, index) ->
if fileObject.directoryName and fileObject.directoryName is directoryName
foundAtIndex = index
foundAtIndex
createTestDirectory = ->
tmp.dirSync()
createDirectory = (pathTo, directoryName) ->
fs.mkdirSync(path.join(pathTo, directoryName))
createFile = (pathTo, filename) ->
touch.sync(path.join(pathTo, filename))
|
[
{
"context": "###\n X-Wing Squad Builder\n Geordan Rosario <geordan@gmail.com>\n https://github.com/georda",
"end": 48,
"score": 0.9998849630355835,
"start": 33,
"tag": "NAME",
"value": "Geordan Rosario"
},
{
"context": "###\n X-Wing Squad Builder\n Geordan Rosario <ge... | coffeescripts/xwing.coffee | evcameron/xwing | 0 | ###
X-Wing Squad Builder
Geordan Rosario <geordan@gmail.com>
https://github.com/geordanr/xwing
###
exportObj = exports ? this
exportObj.sortHelper = (a, b) ->
if a.points == b.points
a_name = a.text.replace(/[^a-z0-9]/ig, '')
b_name = b.text.replace(/[^a-z0-9]/ig, '')
if a_name == b_name
0
else
if a_name > b_name then 1 else -1
else
if a.points > b.points then 1 else -1
$.isMobile = ->
navigator.userAgent.match /(iPhone|iPod|iPad|Android)/i
$.randomInt = (n) ->
Math.floor(Math.random() * n)
# ripped from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
$.getParameterByName = (name) ->
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
regexS = "[\\?&]" + name + "=([^&#]*)"
regex = new RegExp(regexS)
results = regex.exec(window.location.search)
if results == null
return ""
else
return decodeURIComponent(results[1].replace(/\+/g, " "))
Array::intersects = (other) ->
for item in this
if item in other
return true
return false
Array::removeItem = (item) ->
idx = @indexOf item
@splice(idx, 1) unless idx == -1
this
String::capitalize = ->
@charAt(0).toUpperCase() + @slice(1)
String::getXWSBaseName = ->
@split('-')[0]
URL_BASE = "#{window.location.protocol}//#{window.location.host}#{window.location.pathname}"
SQUAD_DISPLAY_NAME_MAX_LENGTH = 24
statAndEffectiveStat = (base_stat, effective_stats, key) ->
"""#{base_stat}#{if effective_stats[key] != base_stat then " (#{effective_stats[key]})" else ""}"""
getPrimaryFaction = (faction) ->
switch faction
when 'Rebel Alliance'
'Rebel Alliance'
when 'Galactic Empire'
'Galactic Empire'
else
faction
conditionToHTML = (condition) ->
html = $.trim """
<div class="condition">
<div class="name">#{if condition.unique then "· " else ""}#{condition.name}</div>
<div class="text">#{condition.text}</div>
</div>
"""
# Assumes cards.js will be loaded
class exportObj.SquadBuilder
constructor: (args) ->
# args
@container = $ args.container
@faction = $.trim args.faction
@printable_container = $ args.printable_container
@tab = $ args.tab
# internal state
@ships = []
@uniques_in_use =
Pilot:
[]
Upgrade:
[]
Modification:
[]
Title:
[]
@suppress_automatic_new_ship = false
@tooltip_currently_displaying = null
@randomizer_options =
sources: null
points: 100
@total_points = 0
@isCustom = false
@isEpic = false
@maxEpicPointsAllowed = 0
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
@backend = null
@current_squad = {}
@language = 'English'
@collection = null
@current_obstacles = []
@setupUI()
@setupEventHandlers()
window.setInterval @updatePermaLink, 250
@isUpdatingPoints = false
if $.getParameterByName('f') == @faction
@resetCurrentSquad(true)
@loadFromSerialized $.getParameterByName('d')
else
@resetCurrentSquad()
@addShip()
resetCurrentSquad: (initial_load=false) ->
default_squad_name = 'Unnamed Squadron'
squad_name = $.trim(@squad_name_input.val()) or default_squad_name
if initial_load and $.trim $.getParameterByName('sn')
squad_name = $.trim $.getParameterByName('sn')
squad_obstacles = []
if initial_load and $.trim $.getParameterByName('obs')
squad_obstacles = ($.trim $.getParameterByName('obs')).split(",").slice(0, 3)
@current_obstacles = squad_obstacles
else if @current_obstacles
squad_obstacles = @current_obstacles
@current_squad =
id: null
name: squad_name
dirty: false
additional_data:
points: @total_points
description: ''
cards: []
notes: ''
obstacles: squad_obstacles
faction: @faction
if @total_points > 0
if squad_name == default_squad_name
@current_squad.name = 'Unsaved Squadron'
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadNameChanged'
@container.trigger 'xwing-backend:squadDirtinessChanged'
newSquadFromScratch: ->
@squad_name_input.val 'New Squadron'
@removeAllShips()
@addShip()
@current_obstacles = []
@resetCurrentSquad()
@notes.val ''
setupUI: ->
DEFAULT_RANDOMIZER_POINTS = 100
DEFAULT_RANDOMIZER_TIMEOUT_SEC = 2
DEFAULT_RANDOMIZER_ITERATIONS = 1000
@status_container = $ document.createElement 'DIV'
@status_container.addClass 'container-fluid'
@status_container.append $.trim '''
<div class="row-fluid">
<div class="span3 squad-name-container">
<div class="display-name">
<span class="squad-name"></span>
<i class="fa fa-pencil"></i>
</div>
<div class="input-append">
<input type="text" maxlength="64" placeholder="Name your squad..." />
<button class="btn save"><i class="fa fa-pencil-square-o"></i></button>
</div>
</div>
<div class="span4 points-display-container">
Points: <span class="total-points">0</span> / <input type="number" class="desired-points" value="100">
<select class="game-type-selector">
<option value="standard">Standard</option>
<option value="custom">Custom</option>
</select>
<span class="points-remaining-container">(<span class="points-remaining"></span> left)</span>
<span class="total-epic-points-container hidden"><br /><span class="total-epic-points">0</span> / <span class="max-epic-points">5</span> Epic Points</span>
<span class="content-warning unreleased-content-used hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning epic-content-used hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning illegal-epic-upgrades hidden"><br /><i class="fa fa-exclamation-circle"></i> Navigator cannot be equipped onto Huge ships in Epic tournament play!</span>
<span class="content-warning illegal-epic-too-many-small-ships hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning illegal-epic-too-many-large-ships hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning collection-invalid hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
</div>
<div class="span5 pull-right button-container">
<div class="btn-group pull-right">
<button class="btn btn-primary view-as-text"><span class="hidden-phone"><i class="fa fa-print"></i> Print/View as </span>Text</button>
<!-- <button class="btn btn-primary print-list hidden-phone hidden-tablet"><i class="fa fa-print"></i> Print</button> -->
<a class="btn btn-primary hidden collection"><i class="fa fa-folder-open hidden-phone hidden-tabler"></i> Your Collection</a>
<!--
<button class="btn btn-primary randomize" ><i class="fa fa-random hidden-phone hidden-tablet"></i> Random!</button>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a class="randomize-options">Randomizer Options...</a></li>
</ul>
-->
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<button class="show-authenticated btn btn-primary save-list"><i class="fa fa-floppy-o"></i> Save</button>
<button class="show-authenticated btn btn-primary save-list-as"><i class="fa fa-files-o"></i> Save As...</button>
<button class="show-authenticated btn btn-primary delete-list disabled"><i class="fa fa-trash-o"></i> Delete</button>
<button class="show-authenticated btn btn-primary backend-list-my-squads show-authenticated">Load Squad</button>
<button class="btn btn-danger clear-squad">New Squad</button>
<span class="show-authenticated backend-status"></span>
</div>
</div>
'''
@container.append @status_container
@list_modal = $ document.createElement 'DIV'
@list_modal.addClass 'modal hide fade text-list-modal'
@container.append @list_modal
@list_modal.append $.trim """
<div class="modal-header">
<button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">×</button>
<div class="hidden-phone hidden-print">
<h3><span class="squad-name"></span> (<span class="total-points"></span>)<h3>
</div>
<div class="visible-phone hidden-print">
<h4><span class="squad-name"></span> (<span class="total-points"></span>)<h4>
</div>
<div class="visible-print">
<div class="fancy-header">
<div class="squad-name"></div>
<div class="squad-faction"></div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle">
<span class="total-points"></span>
</div>
</div>
</div>
</div>
<div class="fancy-under-header"></div>
</div>
</div>
<div class="modal-body">
<div class="fancy-list hidden-phone"></div>
<div class="simple-list"></div>
<div class="bbcode-list">
<p>Copy the BBCode below and paste it into your forum post.</p>
<textarea></textarea><button class="btn btn-copy">Copy</button>
</div>
<div class="html-list">
<textarea></textarea><button class="btn btn-copy">Copy</button>
</div>
</div>
<div class="modal-footer hidden-print">
<label class="vertical-space-checkbox">
Add space for damage/upgrade cards when printing <input type="checkbox" class="toggle-vertical-space" />
</label>
<label class="color-print-checkbox">
Print color <input type="checkbox" class="toggle-color-print" />
</label>
<label class="qrcode-checkbox hidden-phone">
Include QR codes <input type="checkbox" class="toggle-juggler-qrcode" checked="checked" />
</label>
<label class="qrcode-checkbox hidden-phone">
Include obstacle/damage deck choices <input type="checkbox" class="toggle-obstacles" />
</label>
<div class="btn-group list-display-mode">
<button class="btn select-simple-view">Simple</button>
<button class="btn select-fancy-view hidden-phone">Fancy</button>
<button class="btn select-bbcode-view">BBCode</button>
<button class="btn select-html-view">HTML</button>
</div>
<button class="btn print-list hidden-phone"><i class="fa fa-print"></i> Print</button>
<button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@fancy_container = $ @list_modal.find('div.modal-body .fancy-list')
@fancy_total_points_container = $ @list_modal.find('div.modal-header .total-points')
@simple_container = $ @list_modal.find('div.modal-body .simple-list')
@bbcode_container = $ @list_modal.find('div.modal-body .bbcode-list')
@bbcode_textarea = $ @bbcode_container.find('textarea')
@bbcode_textarea.attr 'readonly', 'readonly'
@htmlview_container = $ @list_modal.find('div.modal-body .html-list')
@html_textarea = $ @htmlview_container.find('textarea')
@html_textarea.attr 'readonly', 'readonly'
@toggle_vertical_space_container = $ @list_modal.find('.vertical-space-checkbox')
@toggle_color_print_container = $ @list_modal.find('.color-print-checkbox')
@list_modal.on 'click', 'button.btn-copy', (e) =>
@self = $(e.currentTarget)
@self.siblings('textarea').select()
@success = document.execCommand('copy')
if @success
@self.addClass 'btn-success'
setTimeout ( =>
@self.removeClass 'btn-success'
), 1000
@select_simple_view_button = $ @list_modal.find('.select-simple-view')
@select_simple_view_button.click (e) =>
@select_simple_view_button.blur()
unless @list_display_mode == 'simple'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_simple_view_button.addClass 'btn-inverse'
@list_display_mode = 'simple'
@simple_container.show()
@fancy_container.hide()
@bbcode_container.hide()
@htmlview_container.hide()
@toggle_vertical_space_container.hide()
@toggle_color_print_container.hide()
@select_fancy_view_button = $ @list_modal.find('.select-fancy-view')
@select_fancy_view_button.click (e) =>
@select_fancy_view_button.blur()
unless @list_display_mode == 'fancy'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_fancy_view_button.addClass 'btn-inverse'
@list_display_mode = 'fancy'
@fancy_container.show()
@simple_container.hide()
@bbcode_container.hide()
@htmlview_container.hide()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
@select_bbcode_view_button = $ @list_modal.find('.select-bbcode-view')
@select_bbcode_view_button.click (e) =>
@select_bbcode_view_button.blur()
unless @list_display_mode == 'bbcode'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_bbcode_view_button.addClass 'btn-inverse'
@list_display_mode = 'bbcode'
@bbcode_container.show()
@htmlview_container.hide()
@simple_container.hide()
@fancy_container.hide()
@bbcode_textarea.select()
@bbcode_textarea.focus()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
@select_html_view_button = $ @list_modal.find('.select-html-view')
@select_html_view_button.click (e) =>
@select_html_view_button.blur()
unless @list_display_mode == 'html'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_html_view_button.addClass 'btn-inverse'
@list_display_mode = 'html'
@bbcode_container.hide()
@htmlview_container.show()
@simple_container.hide()
@fancy_container.hide()
@html_textarea.select()
@html_textarea.focus()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
if $(window).width() >= 768
@simple_container.hide()
@select_fancy_view_button.click()
else
@select_simple_view_button.click()
@clear_squad_button = $ @status_container.find('.clear-squad')
@clear_squad_button.click (e) =>
if @current_squad.dirty and @backend?
@backend.warnUnsaved this, () =>
@newSquadFromScratch()
else
@newSquadFromScratch()
@squad_name_container = $ @status_container.find('div.squad-name-container')
@squad_name_display = $ @container.find('.display-name')
@squad_name_placeholder = $ @container.find('.squad-name')
@squad_name_input = $ @squad_name_container.find('input')
@squad_name_save_button = $ @squad_name_container.find('button.save')
@squad_name_input.closest('div').hide()
@points_container = $ @status_container.find('div.points-display-container')
@total_points_span = $ @points_container.find('.total-points')
@game_type_selector = $ @status_container.find('.game-type-selector')
@game_type_selector.change (e) =>
@onGameTypeChanged @game_type_selector.val()
@desired_points_input = $ @points_container.find('.desired-points')
@desired_points_input.change (e) =>
@game_type_selector.val 'custom'
@onGameTypeChanged 'custom'
@points_remaining_span = $ @points_container.find('.points-remaining')
@points_remaining_container = $ @points_container.find('.points-remaining-container')
@unreleased_content_used_container = $ @points_container.find('.unreleased-content-used')
@epic_content_used_container = $ @points_container.find('.epic-content-used')
@illegal_epic_upgrades_container = $ @points_container.find('.illegal-epic-upgrades')
@too_many_small_ships_container = $ @points_container.find('.illegal-epic-too-many-small-ships')
@too_many_large_ships_container = $ @points_container.find('.illegal-epic-too-many-large-ships')
@collection_invalid_container = $ @points_container.find('.collection-invalid')
@total_epic_points_container = $ @points_container.find('.total-epic-points-container')
@total_epic_points_span = $ @total_epic_points_container.find('.total-epic-points')
@max_epic_points_span = $ @points_container.find('.max-epic-points')
@view_list_button = $ @status_container.find('div.button-container button.view-as-text')
@randomize_button = $ @status_container.find('div.button-container button.randomize')
@customize_randomizer = $ @status_container.find('div.button-container a.randomize-options')
@backend_status = $ @status_container.find('.backend-status')
@backend_status.hide()
@collection_button = $ @status_container.find('div.button-container a.collection')
@collection_button.click (e) =>
e.preventDefault()
unless @collection_button.prop('disabled')
@collection.modal.modal 'show'
@squad_name_input.keypress (e) =>
if e.which == 13
@squad_name_save_button.click()
false
@squad_name_input.change (e) =>
@backend_status.fadeOut 'slow'
@squad_name_input.blur (e) =>
@squad_name_input.change()
@squad_name_save_button.click()
@squad_name_display.click (e) =>
e.preventDefault()
@squad_name_display.hide()
@squad_name_input.val $.trim(@current_squad.name)
# Because Firefox handles this badly
window.setTimeout () =>
@squad_name_input.focus()
@squad_name_input.select()
, 100
@squad_name_input.closest('div').show()
@squad_name_save_button.click (e) =>
e.preventDefault()
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
name = @current_squad.name = $.trim(@squad_name_input.val())
if name.length > 0
@squad_name_display.show()
@container.trigger 'xwing-backend:squadNameChanged'
@squad_name_input.closest('div').hide()
@randomizer_options_modal = $ document.createElement('DIV')
@randomizer_options_modal.addClass 'modal hide fade'
$('body').append @randomizer_options_modal
@randomizer_options_modal.append $.trim """
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Random Squad Builder Options</h3>
</div>
<div class="modal-body">
<form>
<label>
Desired Points
<input type="number" class="randomizer-points" value="#{DEFAULT_RANDOMIZER_POINTS}" placeholder="#{DEFAULT_RANDOMIZER_POINTS}" />
</label>
<label>
Sets and Expansions (default all)
<select class="randomizer-sources" multiple="1" data-placeholder="Use all sets and expansions">
</select>
</label>
<label>
Maximum Seconds to Spend Randomizing
<input type="number" class="randomizer-timeout" value="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" placeholder="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" />
</label>
<label>
Maximum Randomization Iterations
<input type="number" class="randomizer-iterations" value="#{DEFAULT_RANDOMIZER_ITERATIONS}" placeholder="#{DEFAULT_RANDOMIZER_ITERATIONS}" />
</label>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary do-randomize" aria-hidden="true">Randomize!</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@randomizer_source_selector = $ @randomizer_options_modal.find('select.randomizer-sources')
for expansion in exportObj.expansions
opt = $ document.createElement('OPTION')
opt.text expansion
@randomizer_source_selector.append opt
@randomizer_source_selector.select2
width: "100%"
minimumResultsForSearch: if $.isMobile() then -1 else 0
@randomize_button.click (e) =>
e.preventDefault()
if @current_squad.dirty and @backend?
@backend.warnUnsaved this, () =>
@randomize_button.click()
else
points = parseInt $(@randomizer_options_modal.find('.randomizer-points')).val()
points = DEFAULT_RANDOMIZER_POINTS if (isNaN(points) or points <= 0)
timeout_sec = parseInt $(@randomizer_options_modal.find('.randomizer-timeout')).val()
timeout_sec = DEFAULT_RANDOMIZER_TIMEOUT_SEC if (isNaN(timeout_sec) or timeout_sec <= 0)
iterations = parseInt $(@randomizer_options_modal.find('.randomizer-iterations')).val()
iterations = DEFAULT_RANDOMIZER_ITERATIONS if (isNaN(iterations) or iterations <= 0)
#console.log "points=#{points}, sources=#{@randomizer_source_selector.val()}, timeout=#{timeout_sec}, iterations=#{iterations}"
@randomSquad(points, @randomizer_source_selector.val(), DEFAULT_RANDOMIZER_TIMEOUT_SEC * 1000, iterations)
@randomizer_options_modal.find('button.do-randomize').click (e) =>
e.preventDefault()
@randomizer_options_modal.modal('hide')
@randomize_button.click()
@customize_randomizer.click (e) =>
e.preventDefault()
@randomizer_options_modal.modal()
@choose_obstacles_modal = $ document.createElement 'DIV'
@choose_obstacles_modal.addClass 'modal hide fade choose-obstacles-modal'
@container.append @choose_obstacles_modal
@choose_obstacles_modal.append $.trim """
<div class="modal-header">
<label class='choose-obstacles-description'>Choose up to three obstacles, to include in the permalink for use in external programs</label>
</div>
<div class="modal-body">
<div class="obstacle-select-container" style="float:left">
<select multiple class='obstacle-select' size="18">
<option class="coreasteroid0-select" value="coreasteroid0">Core Asteroid 0</option>
<option class="coreasteroid1-select" value="coreasteroid1">Core Asteroid 1</option>
<option class="coreasteroid2-select" value="coreasteroid2">Core Asteroid 2</option>
<option class="coreasteroid3-select" value="coreasteroid3">Core Asteroid 3</option>
<option class="coreasteroid4-select" value="coreasteroid4">Core Asteroid 4</option>
<option class="coreasteroid5-select" value="coreasteroid5">Core Asteroid 5</option>
<option class="yt2400debris0-select" value="yt2400debris0">YT2400 Debris 0</option>
<option class="yt2400debris1-select" value="yt2400debris1">YT2400 Debris 1</option>
<option class="yt2400debris2-select" value="yt2400debris2">YT2400 Debris 2</option>
<option class="vt49decimatordebris0-select" value="vt49decimatordebris0">VT49 Debris 0</option>
<option class="vt49decimatordebris1-select" value="vt49decimatordebris1">VT49 Debris 1</option>
<option class="vt49decimatordebris2-select" value="vt49decimatordebris2">VT49 Debris 2</option>
<option class="core2asteroid0-select" value="core2asteroid0">Force Awakens Asteroid 0</option>
<option class="core2asteroid1-select" value="core2asteroid1">Force Awakens Asteroid 1</option>
<option class="core2asteroid2-select" value="core2asteroid2">Force Awakens Asteroid 2</option>
<option class="core2asteroid3-select" value="core2asteroid3">Force Awakens Asteroid 3</option>
<option class="core2asteroid4-select" value="core2asteroid4">Force Awakens Asteroid 4</option>
<option class="core2asteroid5-select" value="core2asteroid5">Force Awakens Asteroid 5</option>
</select>
</div>
<div class="obstacle-image-container" style="display:none;">
<img class="obstacle-image" src="images/core2asteroid0.png" />
</div>
</div>
<div class="modal-footer hidden-print">
<button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@obstacles_select = @choose_obstacles_modal.find('.obstacle-select')
@obstacles_select_image = @choose_obstacles_modal.find('.obstacle-image-container')
# Backend
@backend_list_squads_button = $ @container.find('button.backend-list-my-squads')
@backend_list_squads_button.click (e) =>
e.preventDefault()
if @backend?
@backend.list this
#@backend_list_all_squads_button = $ @container.find('button.backend-list-all-squads')
#@backend_list_all_squads_button.click (e) =>
# e.preventDefault()
# if @backend?
# @backend.list this, true
@backend_save_list_button = $ @container.find('button.save-list')
@backend_save_list_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_save_list_button.hasClass('disabled')
additional_data =
points: @total_points
description: @describeSquad()
cards: @listCards()
notes: @notes.val().substr(0, 1024)
obstacles: @getObstacles()
@backend_status.html $.trim """
<i class="fa fa-refresh fa-spin"></i> Saving squad...
"""
@backend_status.show()
@backend_save_list_button.addClass 'disabled'
await @backend.save @serialize(), @current_squad.id, @current_squad.name, @faction, additional_data, defer(results)
if results.success
@current_squad.dirty = false
if @current_squad.id?
@backend_status.html $.trim """
<i class="fa fa-check"></i> Squad updated successfully.
"""
else
@backend_status.html $.trim """
<i class="fa fa-check"></i> New squad saved successfully.
"""
@current_squad.id = results.id
@container.trigger 'xwing-backend:squadDirtinessChanged'
else
@backend_status.html $.trim """
<i class="fa fa-exclamation-circle"></i> #{results.error}
"""
@backend_save_list_button.removeClass 'disabled'
@backend_save_list_as_button = $ @container.find('button.save-list-as')
@backend_save_list_as_button.addClass 'disabled'
@backend_save_list_as_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_save_list_as_button.hasClass('disabled')
@backend.showSaveAsModal this
@backend_delete_list_button = $ @container.find('button.delete-list')
@backend_delete_list_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_delete_list_button.hasClass('disabled')
@backend.showDeleteModal this
content_container = $ document.createElement 'DIV'
content_container.addClass 'container-fluid'
@container.append content_container
content_container.append $.trim """
<div class="row-fluid">
<div class="span9 ship-container">
<label class="notes-container show-authenticated">
<span>Squad Notes:</span>
<br />
<textarea class="squad-notes"></textarea>
</label>
<span class="obstacles-container">
<button class="btn btn-primary choose-obstacles">Choose Obstacles</button>
</span>
</div>
<div class="span3 info-container" />
</div>
"""
@ship_container = $ content_container.find('div.ship-container')
@info_container = $ content_container.find('div.info-container')
@obstacles_container = content_container.find('.obstacles-container')
@notes_container = $ content_container.find('.notes-container')
@notes = $ @notes_container.find('textarea.squad-notes')
@info_container.append $.trim """
<div class="well well-small info-well">
<span class="info-name"></span>
<br />
<span class="info-sources"></span>
<br />
<span class="info-collection"></span>
<table>
<tbody>
<tr class="info-ship">
<td class="info-header">Ship</td>
<td class="info-data"></td>
</tr>
<tr class="info-skill">
<td class="info-header">Initiative</td>
<td class="info-data info-skill"></td>
</tr>
<tr class="info-energy">
<td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td>
<td class="info-data info-energy"></td>
</tr>
<tr class="info-attack">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-fullfront">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-bullseye">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-back">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-turret">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-doubleturret">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-agility">
<td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td>
<td class="info-data info-agility"></td>
</tr>
<tr class="info-hull">
<td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td>
<td class="info-data info-hull"></td>
</tr>
<tr class="info-shields">
<td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td>
<td class="info-data info-shields"></td>
</tr>
<tr class="info-force">
<td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td>
<td class="info-data info-force"></td>
</tr>
<tr class="info-charge">
<td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td>
<td class="info-data info-charge"></td>
</tr>
<tr class="info-range">
<td class="info-header">Range</td>
<td class="info-data info-range"></td>
</tr>
<tr class="info-actions">
<td class="info-header">Actions</td>
<td class="info-data"></td>
</tr>
<tr class="info-actions-red">
<td></td>
<td class="info-data-red"></td>
</tr>
<tr class="info-upgrades">
<td class="info-header">Upgrades</td>
<td class="info-data"></td>
</tr>
</tbody>
</table>
<p class="info-text" />
<p class="info-maneuvers" />
</div>
"""
@info_container.hide()
@print_list_button = $ @container.find('button.print-list')
@container.find('[rel=tooltip]').tooltip()
# obstacles
@obstacles_button = $ @container.find('button.choose-obstacles')
@obstacles_button.click (e) =>
e.preventDefault()
@showChooseObstaclesModal()
# conditions
@condition_container = $ document.createElement('div')
@condition_container.addClass 'conditions-container'
@container.append @condition_container
setupEventHandlers: ->
@container.on 'xwing:claimUnique', (e, unique, type, cb) =>
@claimUnique unique, type, cb
.on 'xwing:releaseUnique', (e, unique, type, cb) =>
@releaseUnique unique, type, cb
.on 'xwing:pointsUpdated', (e, cb=$.noop) =>
if @isUpdatingPoints
cb()
else
@isUpdatingPoints = true
@onPointsUpdated () =>
@isUpdatingPoints = false
cb()
.on 'xwing-backend:squadLoadRequested', (e, squad) =>
@onSquadLoadRequested squad
.on 'xwing-backend:squadDirtinessChanged', (e) =>
@onSquadDirtinessChanged()
.on 'xwing-backend:squadNameChanged', (e) =>
@onSquadNameChanged()
.on 'xwing:beforeLanguageLoad', (e, cb=$.noop) =>
@pretranslation_serialized = @serialize()
# Need to remove ships here because the cards will change when the
# new language is loaded, and we don't want to have problems with
# unclaiming uniques.
# Preserve squad dirtiness
old_dirty = @current_squad.dirty
@removeAllShips()
@current_squad.dirty = old_dirty
cb()
.on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) =>
@language = language
old_dirty = @current_squad.dirty
@loadFromSerialized @pretranslation_serialized
for ship in @ships
ship.updateSelections()
@current_squad.dirty = old_dirty
@pretranslation_serialized = undefined
cb()
# Recently moved this here. Did this ever work?
.on 'xwing:shipUpdated', (e, cb=$.noop) =>
all_allocated = true
for ship in @ships
ship.updateSelections()
if ship.ship_selector.val() == ''
all_allocated = false
#console.log "all_allocated is #{all_allocated}, suppress_automatic_new_ship is #{@suppress_automatic_new_ship}"
#console.log "should we add ship: #{all_allocated and not @suppress_automatic_new_ship}"
@addShip() if all_allocated and not @suppress_automatic_new_ship
$(window).on 'xwing-backend:authenticationChanged', (e) =>
@resetCurrentSquad()
.on 'xwing-collection:created', (e, collection) =>
# console.log "#{@faction}: collection was created"
@collection = collection
# console.log "#{@faction}: Collection created, checking squad"
@collection.onLanguageChange null, @language
@checkCollection()
@collection_button.removeClass 'hidden'
.on 'xwing-collection:changed', (e, collection) =>
# console.log "#{@faction}: Collection changed, checking squad"
@checkCollection()
.on 'xwing-collection:destroyed', (e, collection) =>
@collection = null
@collection_button.addClass 'hidden'
.on 'xwing:pingActiveBuilder', (e, cb) =>
cb(this) if @container.is(':visible')
.on 'xwing:activateBuilder', (e, faction, cb) =>
if faction == @faction
@tab.tab('show')
cb this
@obstacles_select.change (e) =>
if @obstacles_select.val().length > 3
@obstacles_select.val(@current_squad.additional_data.obstacles)
else
previous_obstacles = @current_squad.additional_data.obstacles
@current_obstacles = (o for o in @obstacles_select.val())
if (previous_obstacles?)
new_selection = @current_obstacles.filter((element) => return previous_obstacles.indexOf(element) == -1)
else
new_selection = @current_obstacles
if new_selection.length > 0
@showChooseObstaclesSelectImage(new_selection[0])
@current_squad.additional_data.obstacles = @current_obstacles
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
@view_list_button.click (e) =>
e.preventDefault()
@showTextListModal()
@print_list_button.click (e) =>
e.preventDefault()
# Copy text list to printable
@printable_container.find('.printable-header').html @list_modal.find('.modal-header').html()
@printable_container.find('.printable-body').text ''
switch @list_display_mode
when 'simple'
@printable_container.find('.printable-body').html @simple_container.html()
else
for ship in @ships
@printable_container.find('.printable-body').append ship.toHTML() if ship.pilot?
@printable_container.find('.fancy-ship').toggleClass 'tall', @list_modal.find('.toggle-vertical-space').prop('checked')
@printable_container.find('.printable-body').toggleClass 'bw', not @list_modal.find('.toggle-color-print').prop('checked')
faction = switch @faction
when 'Rebel Alliance'
'rebel'
when 'Galactic Empire'
'empire'
when 'Scum and Villainy'
'scum'
@printable_container.find('.squad-faction').html """<i class="xwing-miniatures-font xwing-miniatures-font-#{faction}"></i>"""
# Conditions
@printable_container.find('.printable-body').append $.trim """
<div class="print-conditions"></div>
"""
@printable_container.find('.printable-body .print-conditions').html @condition_container.html()
# Notes, if present
if $.trim(@notes.val()) != ''
@printable_container.find('.printable-body').append $.trim """
<h5 class="print-notes">Notes:</h5>
<pre class="print-notes"></pre>
"""
@printable_container.find('.printable-body pre.print-notes').text @notes.val()
# Obstacles
if @list_modal.find('.toggle-obstacles').prop('checked')
@printable_container.find('.printable-body').append $.trim """
<div class="obstacles">
<div>Mark the three obstacles you are using.</div>
<img class="obstacle-silhouettes" src="images/xws-obstacles.png" />
<div>Mark which damage deck you are using.</div>
<div><i class="fa fa-square-o"></i>Original Core Set   <i class="fa fa-square-o"></i>The Force Awakens Core Set</div>
</div>
"""
# Add List Juggler QR code
query = @getPermaLinkParams(['sn', 'obs'])
if query? and @list_modal.find('.toggle-juggler-qrcode').prop('checked')
@printable_container.find('.printable-body').append $.trim """
<div class="qrcode-container">
<div class="permalink-container">
<div class="qrcode"></div>
<div class="qrcode-text">Scan to open this list in the builder</div>
</div>
<div class="juggler-container">
<div class="qrcode"></div>
<div class="qrcode-text">TOs: Scan to load this squad into List Juggler</div>
</div>
</div>
"""
text = "https://yasb-xws.herokuapp.com/juggler#{query}"
@printable_container.find('.juggler-container .qrcode').qrcode
render: 'div'
ec: 'M'
size: if text.length < 144 then 144 else 160
text: text
text = "https://geordanr.github.io/xwing/#{query}"
@printable_container.find('.permalink-container .qrcode').qrcode
render: 'div'
ec: 'M'
size: if text.length < 144 then 144 else 160
text: text
window.print()
$(window).resize =>
@select_simple_view_button.click() if $(window).width() < 768 and @list_display_mode != 'simple'
@notes.change @onNotesUpdated
@notes.on 'keyup', @onNotesUpdated
getPermaLinkParams: (ignored_params=[]) =>
params = {}
params.f = encodeURI(@faction) unless 'f' in ignored_params
params.d = encodeURI(@serialize()) unless 'd' in ignored_params
params.sn = encodeURIComponent(@current_squad.name) unless 'sn' in ignored_params
params.obs = encodeURI(@current_squad.additional_data.obstacles || '') unless 'obs' in ignored_params
return "?" + ("#{k}=#{v}" for k, v of params).join("&")
getPermaLink: (params=@getPermaLinkParams()) => "#{URL_BASE}#{params}"
updatePermaLink: () =>
return unless @container.is(':visible') # gross but couldn't make clearInterval work
next_params = @getPermaLinkParams()
if window.location.search != next_params
window.history.replaceState(next_params, '', @getPermaLink(next_params))
onNotesUpdated: =>
if @total_points > 0
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
onGameTypeChanged: (gametype, cb=$.noop) =>
switch gametype
when 'standard'
@isEpic = false
@isCustom = false
@desired_points_input.val 200
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
when 'custom'
@isEpic = false
@isCustom = true
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
@max_epic_points_span.text @maxEpicPointsAllowed
@onPointsUpdated cb
onPointsUpdated: (cb=$.noop) =>
@total_points = 0
@total_epic_points = 0
unreleased_content_used = false
epic_content_used = false
for ship, i in @ships
ship.validate()
@total_points += ship.getPoints()
@total_epic_points += ship.getEpicPoints()
ship_uses_unreleased_content = ship.checkUnreleasedContent()
unreleased_content_used = ship_uses_unreleased_content if ship_uses_unreleased_content
ship_uses_epic_content = ship.checkEpicContent()
epic_content_used = ship_uses_epic_content if ship_uses_epic_content
@total_points_span.text @total_points
points_left = parseInt(@desired_points_input.val()) - @total_points
@points_remaining_span.text points_left
@points_remaining_container.toggleClass 'red', (points_left < 0)
@unreleased_content_used_container.toggleClass 'hidden', not unreleased_content_used
@epic_content_used_container.toggleClass 'hidden', (@isEpic or not epic_content_used)
# Check against Epic restrictions if applicable
@illegal_epic_upgrades_container.toggleClass 'hidden', true
@too_many_small_ships_container.toggleClass 'hidden', true
@too_many_large_ships_container.toggleClass 'hidden', true
@total_epic_points_container.toggleClass 'hidden', true
if @isEpic
@total_epic_points_container.toggleClass 'hidden', false
@total_epic_points_span.text @total_epic_points
@total_epic_points_span.toggleClass 'red', (@total_epic_points > @maxEpicPointsAllowed)
shipCountsByType = {}
illegal_for_epic = false
for ship, i in @ships
if ship?.data?
shipCountsByType[ship.data.name] ?= 0
shipCountsByType[ship.data.name] += 1
if ship.data.huge?
for upgrade in ship.upgrades
if upgrade?.data?.epic_restriction_func?
unless upgrade.data.epic_restriction_func(ship.data, upgrade)
illegal_for_epic = true
break
break if illegal_for_epic
@illegal_epic_upgrades_container.toggleClass 'hidden', not illegal_for_epic
if @maxLargeShipsOfOneType? and @maxSmallShipsOfOneType?
for ship_name, count of shipCountsByType
ship_data = exportObj.ships[ship_name]
if ship_data.large? and count > @maxLargeShipsOfOneType
@too_many_large_ships_container.toggleClass 'hidden', false
else if not ship.huge? and count > @maxSmallShipsOfOneType
@too_many_small_ships_container.toggleClass 'hidden', false
@fancy_total_points_container.text @total_points
# update text list
@fancy_container.text ''
@simple_container.html '<table class="simple-table"></table>'
bbcode_ships = []
htmlview_ships = []
for ship in @ships
if ship.pilot?
@fancy_container.append ship.toHTML()
@simple_container.find('table').append ship.toTableRow()
bbcode_ships.push ship.toBBCode()
htmlview_ships.push ship.toSimpleHTML()
@htmlview_container.find('textarea').val $.trim """#{htmlview_ships.join '<br />'}
<br />
<b><i>Total: #{@total_points}</i></b>
<br />
<a href="#{@getPermaLink()}">View in Yet Another Squad Builder</a>
"""
@bbcode_container.find('textarea').val $.trim """#{bbcode_ships.join "\n\n"}
[b][i]Total: #{@total_points}[/i][/b]
[url=#{@getPermaLink()}]View in Yet Another Squad Builder[/url]
"""
# console.log "#{@faction}: Squad updated, checking collection"
@checkCollection()
# update conditions used
# this old version of phantomjs i'm using doesn't support Set
if Set?
conditions_set = new Set()
for ship in @ships
# shouldn't there be a set union
ship.getConditions().forEach (condition) ->
conditions_set.add(condition)
conditions = []
conditions_set.forEach (condition) ->
conditions.push(condition)
conditions.sort (a, b) ->
if a.name.canonicalize() < b.name.canonicalize()
-1
else if b.name.canonicalize() > a.name.canonicalize()
1
else
0
@condition_container.text ''
conditions.forEach (condition) =>
@condition_container.append conditionToHTML(condition)
cb @total_points
onSquadLoadRequested: (squad) =>
console.log(squad.additional_data.obstacles)
@current_squad = squad
@backend_delete_list_button.removeClass 'disabled'
@squad_name_input.val @current_squad.name
@squad_name_placeholder.text @current_squad.name
@current_obstacles = @current_squad.additional_data.obstacles
@updateObstacleSelect(@current_squad.additional_data.obstacles)
@loadFromSerialized squad.serialized
@notes.val(squad.additional_data.notes ? '')
@backend_status.fadeOut 'slow'
@current_squad.dirty = false
@container.trigger 'xwing-backend:squadDirtinessChanged'
onSquadDirtinessChanged: () =>
@backend_save_list_button.toggleClass 'disabled', not (@current_squad.dirty and @total_points > 0)
@backend_save_list_as_button.toggleClass 'disabled', @total_points == 0
@backend_delete_list_button.toggleClass 'disabled', not @current_squad.id?
onSquadNameChanged: () =>
if @current_squad.name.length > SQUAD_DISPLAY_NAME_MAX_LENGTH
short_name = "#{@current_squad.name.substr(0, SQUAD_DISPLAY_NAME_MAX_LENGTH)}…"
else
short_name = @current_squad.name
@squad_name_placeholder.text ''
@squad_name_placeholder.append short_name
@squad_name_input.val @current_squad.name
removeAllShips: ->
while @ships.length > 0
@removeShip @ships[0]
throw new Error("Ships not emptied") if @ships.length > 0
showTextListModal: ->
# Display modal
@list_modal.modal 'show'
showChooseObstaclesModal: ->
@obstacles_select.val(@current_squad.additional_data.obstacles)
@choose_obstacles_modal.modal 'show'
showChooseObstaclesSelectImage: (obstacle) ->
@image_name = 'images/' + obstacle + '.png'
@obstacles_select_image.find('.obstacle-image').attr 'src', @image_name
@obstacles_select_image.show()
updateObstacleSelect: (obstacles) ->
@current_obstacles = obstacles
@obstacles_select.val(obstacles)
serialize: ->
#( "#{ship.pilot.id}:#{ship.upgrades[i].data?.id ? -1 for slot, i in ship.pilot.slots}:#{ship.title?.data?.id ? -1}:#{upgrade.data?.id ? -1 for upgrade in ship.title?.conferredUpgrades ? []}:#{ship.modification?.data?.id ? -1}" for ship in @ships when ship.pilot? ).join ';'
serialization_version = 4
game_type_abbrev = switch @game_type_selector.val()
when 'standard'
's'
when 'custom'
"c=#{$.trim @desired_points_input.val()}"
"""v#{serialization_version}!#{game_type_abbrev}!#{( ship.toSerialized() for ship in @ships when ship.pilot? ).join ';'}"""
loadFromSerialized: (serialized) ->
@suppress_automatic_new_ship = true
# Clear all existing ships
@removeAllShips()
re = /^v(\d+)!(.*)/
matches = re.exec serialized
if matches?
# versioned
version = parseInt matches[1]
switch version
when 3, 4
# parse out game type
[ game_type_abbrev, serialized_ships ] = matches[2].split('!')
switch game_type_abbrev
when 's'
@game_type_selector.val 'standard'
@game_type_selector.change()
else
@game_type_selector.val 'custom'
@desired_points_input.val parseInt(game_type_abbrev.split('=')[1])
@desired_points_input.change()
for serialized_ship in serialized_ships.split(';')
unless serialized_ship == ''
new_ship = @addShip()
new_ship.fromSerialized version, serialized_ship
when 2
for serialized_ship in matches[2].split(';')
unless serialized_ship == ''
new_ship = @addShip()
new_ship.fromSerialized version, serialized_ship
else
# v1 (unversioned)
for serialized_ship in serialized.split(';')
unless serialized == ''
new_ship = @addShip()
new_ship.fromSerialized 1, serialized_ship
@suppress_automatic_new_ship = false
# Finally, the unassigned ship
@addShip()
uniqueIndex: (unique, type) ->
if type not of @uniques_in_use
throw new Error("Invalid unique type '#{type}'")
@uniques_in_use[type].indexOf unique
claimUnique: (unique, type, cb) =>
if @uniqueIndex(unique, type) < 0
# Claim pilots with the same canonical name
for other in (exportObj.pilotsByUniqueName[unique.canonical_name.getXWSBaseName()] or [])
if unique != other
if @uniqueIndex(other, 'Pilot') < 0
# console.log "Also claiming unique pilot #{other.canonical_name} in use"
@uniques_in_use['Pilot'].push other
else
throw new Error("Unique #{type} '#{unique.name}' already claimed as pilot")
# Claim other upgrades with the same canonical name
for otherslot, bycanonical of exportObj.upgradesBySlotUniqueName
for canonical, other of bycanonical
if canonical.getXWSBaseName() == unique.canonical_name.getXWSBaseName() and unique != other
if @uniqueIndex(other, 'Upgrade') < 0
# console.log "Also claiming unique #{other.canonical_name} (#{otherslot}) in use"
@uniques_in_use['Upgrade'].push other
# else
# throw new Error("Unique #{type} '#{unique.name}' already claimed as #{otherslot}")
@uniques_in_use[type].push unique
else
throw new Error("Unique #{type} '#{unique.name}' already claimed")
cb()
releaseUnique: (unique, type, cb) =>
idx = @uniqueIndex(unique, type)
if idx >= 0
# Release all uniques with the same canonical name and base name
for type, uniques of @uniques_in_use
# Removing stuff in a loop sucks, so we'll construct a new list
@uniques_in_use[type] = []
for u in uniques
if u.canonical_name.getXWSBaseName() != unique.canonical_name.getXWSBaseName()
# Keep this one
@uniques_in_use[type].push u
# else
# console.log "Releasing #{u.name} (#{type}) with canonical name #{unique.canonical_name}"
else
throw new Error("Unique #{type} '#{unique.name}' not in use")
cb()
addShip: ->
new_ship = new Ship
builder: this
container: @ship_container
@ships.push new_ship
new_ship
removeShip: (ship) ->
await ship.destroy defer()
await @container.trigger 'xwing:pointsUpdated', defer()
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
matcher: (item, term) ->
item.toUpperCase().indexOf(term.toUpperCase()) >= 0
isOurFaction: (faction) ->
if faction instanceof Array
for f in faction
if getPrimaryFaction(f) == @faction
return true
false
else
getPrimaryFaction(faction) == @faction
getAvailableShipsMatching: (term='') ->
ships = []
for ship_name, ship_data of exportObj.ships
if @isOurFaction(ship_data.factions) and @matcher(ship_data.name, term)
if not ship_data.huge or (@isEpic or @isCustom)
ships.push
id: ship_data.name
text: ship_data.name
english_name: ship_data.english_name
canonical_name: ship_data.canonical_name
ships.sort exportObj.sortHelper
getAvailablePilotsForShipIncluding: (ship, include_pilot, term='') ->
# Returns data formatted for Select2
available_faction_pilots = (pilot for pilot_name, pilot of exportObj.pilotsByLocalizedName when (not ship? or pilot.ship == ship) and @isOurFaction(pilot.faction) and @matcher(pilot_name, term))
eligible_faction_pilots = (pilot for pilot_name, pilot of available_faction_pilots when (not pilot.unique? or pilot not in @uniques_in_use['Pilot'] or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()))
# Re-add selected pilot
if include_pilot? and include_pilot.unique? and @matcher(include_pilot.name, term)
eligible_faction_pilots.push include_pilot
({ id: pilot.id, text: "#{pilot.name} (#{pilot.points})", points: pilot.points, ship: pilot.ship, english_name: pilot.english_name, disabled: pilot not in eligible_faction_pilots } for pilot in available_faction_pilots).sort exportObj.sortHelper
dfl_filter_func = ->
true
countUpgrades: (canonical_name) ->
# returns number of upgrades with given canonical name equipped
count = 0
for ship in @ships
for upgrade in ship.upgrades
if upgrade?.data?.canonical_name == canonical_name
count++
count
getAvailableUpgradesIncluding: (slot, include_upgrade, ship, this_upgrade_obj, term='', filter_func=@dfl_filter_func) ->
# Returns data formatted for Select2
limited_upgrades_in_use = (upgrade.data for upgrade in ship.upgrades when upgrade?.data?.limited?)
available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgradesByLocalizedName when upgrade.slot == slot and @matcher(upgrade_name, term) and (not upgrade.ship? or upgrade.ship == ship.data.name) and (not upgrade.faction? or @isOurFaction(upgrade.faction)))
if filter_func != @dfl_filter_func
available_upgrades = (upgrade for upgrade in available_upgrades when filter_func(upgrade))
# Special case #3
eligible_upgrades = (upgrade for upgrade_name, upgrade of available_upgrades when (not upgrade.unique? or upgrade not in @uniques_in_use['Upgrade']) and (not (ship? and upgrade.restriction_func?) or upgrade.restriction_func(ship, this_upgrade_obj)) and upgrade not in limited_upgrades_in_use and ((not upgrade.max_per_squad?) or ship.builder.countUpgrades(upgrade.canonical_name) < upgrade.max_per_squad))
# Special case #2 :(
# current_upgrade_forcibly_removed = false
#for title in ship?.titles ? []
# if title?.data?.special_case == 'A-Wing Test Pilot'
# for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?)
# eligible_upgrades.removeItem equipped_upgrade
# current_upgrade_forcibly_removed = true if equipped_upgrade == include_upgrade
for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?)
eligible_upgrades.removeItem equipped_upgrade
# Re-enable selected upgrade
if include_upgrade? and (((include_upgrade.unique? or include_upgrade.limited? or include_upgrade.max_per_squad?) and @matcher(include_upgrade.name, term)))# or current_upgrade_forcibly_removed)
# available_upgrades.push include_upgrade
eligible_upgrades.push include_upgrade
retval = ({ id: upgrade.id, text: "#{upgrade.name} (#{upgrade.points})", points: upgrade.points, english_name: upgrade.english_name, disabled: upgrade not in eligible_upgrades } for upgrade in available_upgrades).sort exportObj.sortHelper
# Possibly adjust the upgrade
if this_upgrade_obj.adjustment_func?
(this_upgrade_obj.adjustment_func(upgrade) for upgrade in retval)
else
retval
getAvailableModificationsIncluding: (include_modification, ship, term='', filter_func=@dfl_filter_func) ->
# Returns data formatted for Select2
limited_modifications_in_use = (modification.data for modification in ship.modifications when modification?.data?.limited?)
available_modifications = (modification for modification_name, modification of exportObj.modificationsByLocalizedName when @matcher(modification_name, term) and (not modification.ship? or modification.ship == ship.data.name))
if filter_func != @dfl_filter_func
available_modifications = (modification for modification in available_modifications when filter_func(modification))
if ship? and exportObj.hugeOnly(ship) > 0
# Only show allowed mods for Epic ships
available_modifications = (modification for modification in available_modifications when modification.ship? or not modification.restriction_func? or modification.restriction_func ship)
eligible_modifications = (modification for modification_name, modification of available_modifications when (not modification.unique? or modification not in @uniques_in_use['Modification']) and (not modification.faction? or @isOurFaction(modification.faction)) and (not (ship? and modification.restriction_func?) or modification.restriction_func ship) and modification not in limited_modifications_in_use)
# I finally had to add a special case :( If something else demands it
# then I will try to make this more systematic, but I haven't come up
# with a good solution... yet.
# current_mod_forcibly_removed = false
for thing in (ship?.titles ? []).concat(ship?.upgrades ? [])
if thing?.data?.special_case == 'Royal Guard TIE'
# Need to refetch by ID because Vaksai may have modified its cost
for equipped_modification in (modificationsById[modification.data.id] for modification in ship.modifications when modification?.data?)
eligible_modifications.removeItem equipped_modification
# current_mod_forcibly_removed = true if equipped_modification == include_modification
# Re-add selected modification
if include_modification? and (((include_modification.unique? or include_modification.limited?) and @matcher(include_modification.name, term)))# or current_mod_forcibly_removed)
eligible_modifications.push include_modification
({ id: modification.id, text: "#{modification.name} (#{modification.points})", points: modification.points, english_name: modification.english_name, disabled: modification not in eligible_modifications } for modification in available_modifications).sort exportObj.sortHelper
getAvailableTitlesIncluding: (ship, include_title, term='') ->
# Returns data formatted for Select2
# Titles are no longer unique!
limited_titles_in_use = (title.data for title in ship.titles when title?.data?.limited?)
available_titles = (title for title_name, title of exportObj.titlesByLocalizedName when (not title.ship? or title.ship == ship.data.name) and @matcher(title_name, term))
eligible_titles = (title for title_name, title of available_titles when (not title.unique? or (title not in @uniques_in_use['Title'] and title.canonical_name.getXWSBaseName() not in (t.canonical_name.getXWSBaseName() for t in @uniques_in_use['Title'])) or title.canonical_name.getXWSBaseName() == include_title?.canonical_name.getXWSBaseName()) and (not title.faction? or @isOurFaction(title.faction)) and (not (ship? and title.restriction_func?) or title.restriction_func ship) and title not in limited_titles_in_use)
# Re-add selected title
if include_title? and (((include_title.unique? or include_title.limited?) and @matcher(include_title.name, term)))
eligible_titles.push include_title
({ id: title.id, text: "#{title.name} (#{title.points})", points: title.points, english_name: title.english_name, disabled: title not in eligible_titles } for title in available_titles).sort exportObj.sortHelper
# Converts a maneuver table for into an HTML table.
getManeuverTableHTML: (maneuvers, baseManeuvers) ->
if not maneuvers? or maneuvers.length == 0
return "Missing maneuver info."
# Preprocess maneuvers to see which bearings are never used so we
# don't render them.
bearings_without_maneuvers = [0...maneuvers[0].length]
for bearings in maneuvers
for difficulty, bearing in bearings
if difficulty > 0
bearings_without_maneuvers.removeItem bearing
# console.log "bearings without maneuvers:"
# console.dir bearings_without_maneuvers
outTable = "<table><tbody>"
for speed in [maneuvers.length - 1 .. 0]
haveManeuver = false
for v in maneuvers[speed]
if v > 0
haveManeuver = true
break
continue if not haveManeuver
outTable += "<tr><td>#{speed}</td>"
for turn in [0 ... maneuvers[speed].length]
continue if turn in bearings_without_maneuvers
outTable += "<td>"
if maneuvers[speed][turn] > 0
color = switch maneuvers[speed][turn]
when 1 then "white"
when 2 then "dodgerblue"
when 3 then "red"
outTable += """<svg xmlns="http://www.w3.org/2000/svg" width="30px" height="30px" viewBox="0 0 200 200">"""
if speed == 0
outTable += """<rect x="50" y="50" width="100" height="100" style="fill:#{color}" />"""
else
outlineColor = "black"
if maneuvers[speed][turn] != baseManeuvers[speed][turn]
outlineColor = "mediumblue" # highlight manuevers modified by another card (e.g. R2 Astromech makes all 1 & 2 speed maneuvers green)
transform = ""
className = ""
switch turn
when 0
# turn left
linePath = "M160,180 L160,70 80,70"
trianglePath = "M80,100 V40 L30,70 Z"
when 1
# bank left
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(-5 -15) rotate(45 70 90)' "
when 2
# straight
linePath = "M100,180 L100,100 100,80"
trianglePath = "M70,80 H130 L100,30 Z"
when 3
# bank right
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(5 -15) rotate(-45 130 90)' "
when 4
# turn right
linePath = "M40,180 L40,70 120,70"
trianglePath = "M120,100 V40 L170,70 Z"
when 5
# k-turn/u-turn
linePath = "M50,180 L50,100 C50,10 140,10 140,100 L140,120"
trianglePath = "M170,120 H110 L140,180 Z"
when 6
# segnor's loop left
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(0 50)'"
when 7
# segnor's loop right
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(0 50)'"
when 8
# tallon roll left
linePath = "M160,180 L160,70 80,70"
trianglePath = "M60,100 H100 L80,140 Z"
when 9
# tallon roll right
linePath = "M40,180 L40,70 120,70"
trianglePath = "M100,100 H140 L120,140 Z"
when 10
# backward left
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(5 -15) rotate(-45 130 90)' "
className = 'backwards'
when 11
# backward straight
linePath = "M100,180 L100,100 100,80"
trianglePath = "M70,80 H130 L100,30 Z"
className = 'backwards'
when 12
# backward right
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(-5 -15) rotate(45 70 90)' "
className = 'backwards'
outTable += $.trim """
<g class="maneuver #{className}">
<path d='#{trianglePath}' fill='#{color}' stroke-width='5' stroke='#{outlineColor}' #{transform}/>
<path stroke-width='25' fill='none' stroke='#{outlineColor}' d='#{linePath}' />
<path stroke-width='15' fill='none' stroke='#{color}' d='#{linePath}' />
</g>
"""
outTable += "</svg>"
outTable += "</td>"
outTable += "</tr>"
outTable += "</tbody></table>"
outTable
showTooltip: (type, data, additional_opts) ->
if data != @tooltip_currently_displaying
switch type
when 'Ship'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.pilot.sources).sort().join(', ')
if @collection?.counts?
ship_count = @collection.counts?.ship?[data.data.english_name] ? 0
pilot_count = @collection.counts?.pilot?[data.pilot.english_name] ? 0
@info_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection."""
else
@info_container.find('.info-collection').text ''
effective_stats = data.effectiveStats()
extra_actions = $.grep effective_stats.actions, (el, i) ->
el not in (data.pilot.ship_override?.actions ? data.data.actions)
extra_actions_red = $.grep effective_stats.actionsred, (el, i) ->
el not in (data.pilot.ship_override?.actionsred ? data.data.actionsred)
@info_container.find('.info-name').html """#{if data.pilot.unique then "· " else ""}#{data.pilot.name}#{if data.pilot.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data.pilot) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.pilot.text ? ''
@info_container.find('tr.info-ship td.info-data').text data.pilot.ship
@info_container.find('tr.info-ship').show()
@info_container.find('tr.info-skill td.info-data').text statAndEffectiveStat(data.pilot.skill, effective_stats, 'skill')
@info_container.find('tr.info-skill').show()
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack')
@info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(data.data.attack_icon ? 'xwing-miniatures-font-attack')
@info_container.find('tr.info-attack td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attack ? data.data.attack), effective_stats, 'attack')
@info_container.find('tr.info-attack').toggle(data.pilot.ship_override?.attack? or data.data.attack?)
@info_container.find('tr.info-attack-fullfront td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackf ? data.data.attackf), effective_stats, 'attackf')
@info_container.find('tr.info-attack-fullfront').toggle(data.pilot.ship_override?.attackf? or data.data.attackf?)
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-back td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackb ? data.data.attackb), effective_stats, 'attackb')
@info_container.find('tr.info-attack-back').toggle(data.pilot.ship_override?.attackb? or data.data.attackb?)
@info_container.find('tr.info-attack-turret td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackt ? data.data.attackt), effective_stats, 'attackt')
@info_container.find('tr.info-attack-turret').toggle(data.pilot.ship_override?.attackt? or data.data.attackt?)
@info_container.find('tr.info-attack-doubleturret td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackdt ? data.data.attackdt), effective_stats, 'attackdt')
@info_container.find('tr.info-attack-doubleturret').toggle(data.pilot.ship_override?.attackdt? or data.data.attackdt?)
@info_container.find('tr.info-energy td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.energy ? data.data.energy), effective_stats, 'energy')
@info_container.find('tr.info-energy').toggle(data.pilot.ship_override?.energy? or data.data.energy?)
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-agility td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.agility ? data.data.agility), effective_stats, 'agility')
@info_container.find('tr.info-agility').show()
@info_container.find('tr.info-hull td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.hull ? data.data.hull), effective_stats, 'hull')
@info_container.find('tr.info-hull').show()
@info_container.find('tr.info-shields td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.shields ? data.data.shields), effective_stats, 'shields')
@info_container.find('tr.info-shields').show()
@info_container.find('tr.info-force td.info-data').html (statAndEffectiveStat((data.pilot.ship_override?.force ? data.pilot.force), effective_stats, 'force') + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
if data.pilot.ship_override?.force? or data.pilot.force?
@info_container.find('tr.info-force').show()
else
@info_container.find('tr.info-force').hide()
if data.pilot.charge?
if data.pilot.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.pilot.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
else
@info_container.find('tr.info-charge td.info-data').text data.pilot.charge
@info_container.find('tr.info-charge').show()
else
@info_container.find('tr.info-charge').hide()
@info_container.find('tr.info-actions td.info-data').html (exportObj.translate(@language, 'action', a) for a in (data.pilot.ship_override?.actions ? data.data.actions).concat( ("<strong>#{exportObj.translate @language, 'action', action}</strong>" for action in extra_actions))).join ' '
if data.data.actionsred?
@info_container.find('tr.info-actions-red td.info-data-red').html (exportObj.translate(@language, 'action', a) for a in (data.pilot.ship_override?.actionsred ? data.data.actionsred).concat( ("<strong>#{exportObj.translate @language, 'action', action}</strong>" for action in extra_actions_red))).join ' '
@info_container.find('tr.info-actions-red').toggle(data.data.actionsred?)
@info_container.find('tr.info-actions').show()
@info_container.find('tr.info-upgrades').show()
@info_container.find('tr.info-upgrades td.info-data').text((exportObj.translate(@language, 'slot', slot) for slot in data.pilot.slots).join(', ') or 'None')
@info_container.find('p.info-maneuvers').show()
@info_container.find('p.info-maneuvers').html(@getManeuverTableHTML(effective_stats.maneuvers, data.data.maneuvers))
when 'Pilot'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ')
if @collection?.counts?
pilot_count = @collection.counts?.pilot?[data.english_name] ? 0
ship_count = @collection.counts.ship?[additional_opts.ship] ? 0
@info_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection."""
else
@info_container.find('.info-collection').text ''
@info_container.find('.info-name').html """#{if data.unique then "· " else ""}#{data.name}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.text ? ''
ship = exportObj.ships[data.ship]
@info_container.find('tr.info-ship td.info-data').text data.ship
@info_container.find('tr.info-ship').show()
@info_container.find('tr.info-skill td.info-data').text data.skill
@info_container.find('tr.info-skill').show()
@info_container.find('tr.info-attack td.info-data').text(data.ship_override?.attack ? ship.attack)
@info_container.find('tr.info-attack').toggle(data.ship_override?.attack? or ship.attack?)
@info_container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf)
@info_container.find('tr.info-attack-fullfront').toggle(ship.attackf?)
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-back td.info-data').text(ship.attackb)
@info_container.find('tr.info-attack-back').toggle(ship.attackb?)
@info_container.find('tr.info-attack-turret td.info-data').text(ship.attackt)
@info_container.find('tr.info-attack-turret').toggle(ship.attackt?)
@info_container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt)
@info_container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?)
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc')
@info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-frontarc')
@info_container.find('tr.info-energy td.info-data').text(data.ship_override?.energy ? ship.energy)
@info_container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?)
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-agility td.info-data').text(data.ship_override?.agility ? ship.agility)
@info_container.find('tr.info-agility').show()
@info_container.find('tr.info-hull td.info-data').text(data.ship_override?.hull ? ship.hull)
@info_container.find('tr.info-hull').show()
@info_container.find('tr.info-shields td.info-data').text(data.ship_override?.shields ? ship.shields)
@info_container.find('tr.info-shields').show()
if data.ship_override?.force or data.force?
@info_container.find('tr.info-force td.info-data').html ((data.ship_override?.force ? data.force)+ '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
@info_container.find('tr.info-force').show()
else
@info_container.find('tr.info-force').hide()
if data.charge?
if data.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
else
@info_container.find('tr.info-charge td.info-data').text data.charge
@info_container.find('tr.info-charge').show()
else
@info_container.find('tr.info-charge').hide()
@info_container.find('tr.info-actions td.info-data').html (exportObj.translate(@language, 'action', action) for action in (data.ship_override?.actions ? exportObj.ships[data.ship].actions)).join(' ')
if ships[data.ship].actionsred?
@info_container.find('tr.info-actions-red td.info-data-red').html (exportObj.translate(@language, 'action', action) for action in (data.ship_override?.actionsred ? exportObj.ships[data.ship].actionsred)).join(' ')
@info_container.find('tr.info-actions-red').show()
else
@info_container.find('tr.info-actions-red').hide()
@info_container.find('tr.info-actions').show()
@info_container.find('tr.info-upgrades').show()
@info_container.find('tr.info-upgrades td.info-data').text((exportObj.translate(@language, 'slot', slot) for slot in data.slots).join(', ') or 'None')
@info_container.find('p.info-maneuvers').show()
@info_container.find('p.info-maneuvers').html(@getManeuverTableHTML(ship.maneuvers, ship.maneuvers))
when 'Addon'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ')
if @collection?.counts?
addon_count = @collection.counts?[additional_opts.addon_type.toLowerCase()]?[data.english_name] ? 0
@info_container.find('.info-collection').text """You have #{addon_count} in your collection."""
else
@info_container.find('.info-collection').text ''
@info_container.find('.info-name').html """#{if data.unique then "· " else ""}#{data.name}#{if data.limited? then " (#{exportObj.translate(@language, 'ui', 'limited')})" else ""}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.text ? ''
@info_container.find('tr.info-ship').hide()
@info_container.find('tr.info-skill').hide()
if data.energy?
@info_container.find('tr.info-energy td.info-data').text data.energy
@info_container.find('tr.info-energy').show()
else
@info_container.find('tr.info-energy').hide()
if data.attack?
# Attack icons on upgrade cards don't get special icons
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc')
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass('xwing-miniatures-font-frontarc')
@info_container.find('tr.info-attack td.info-data').text data.attack
@info_container.find('tr.info-attack').show()
else
@info_container.find('tr.info-attack').hide()
if data.attackt?
@info_container.find('tr.info-attack-turret td.info-data').text data.attackt
@info_container.find('tr.info-attack-turret').show()
else
@info_container.find('tr.info-attack-turret').hide()
if data.attackbull?
@info_container.find('tr.info-attack-bullseye td.info-data').text data.attackbull
@info_container.find('tr.info-attack-bullseye').show()
else
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-fullfront').hide()
@info_container.find('tr.info-attack-back').hide()
@info_container.find('tr.info-attack-doubleturret').hide()
if data.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.charge + """<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>""")
else
@info_container.find('tr.info-charge td.info-data').text data.charge
@info_container.find('tr.info-charge').toggle(data.charge?)
if data.range?
@info_container.find('tr.info-range td.info-data').text data.range
@info_container.find('tr.info-range').show()
else
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
@info_container.find('tr.info-force').toggle(data.force?)
@info_container.find('tr.info-agility').hide()
@info_container.find('tr.info-hull').hide()
@info_container.find('tr.info-shields').hide()
@info_container.find('tr.info-actions').hide()
@info_container.find('tr.info-actions-red').hide()
@info_container.find('tr.info-upgrades').hide()
@info_container.find('p.info-maneuvers').hide()
@info_container.show()
@tooltip_currently_displaying = data
_randomizerLoopBody: (data) =>
if data.keep_running and data.iterations < data.max_iterations
data.iterations++
#console.log "Current points: #{@total_points} of #{data.max_points}, iteration=#{data.iterations} of #{data.max_iterations}, keep_running=#{data.keep_running}"
if @total_points == data.max_points
# Exact hit!
#console.log "Points reached exactly"
data.keep_running = false
else if @total_points < data.max_points
#console.log "Need to add something"
# Add something
# Possible options: ship or empty addon slot
unused_addons = []
for ship in @ships
for upgrade in ship.upgrades
unused_addons.push upgrade unless upgrade.data?
unused_addons.push ship.title if ship.title? and not ship.title.data?
for modification in ship.modifications
unused_addons.push modification unless modification.data?
# 0 is ship, otherwise addon
idx = $.randomInt(1 + unused_addons.length)
if idx == 0
# Add random ship
#console.log "Add ship"
available_ships = @getAvailableShipsMatching()
ship_type = available_ships[$.randomInt available_ships.length].text
available_pilots = @getAvailablePilotsForShipIncluding(ship_type)
pilot = available_pilots[$.randomInt available_pilots.length]
if exportObj.pilotsById[pilot.id].sources.intersects(data.allowed_sources)
new_ship = @addShip()
new_ship.setPilotById pilot.id
else
# Add upgrade/title/modification
#console.log "Add addon"
addon = unused_addons[idx - 1]
switch addon.type
when 'Upgrade'
available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship) when exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources))
addon.setById available_upgrades[$.randomInt available_upgrades.length].id if available_upgrades.length > 0
when 'Title'
available_titles = (title for title in @getAvailableTitlesIncluding(addon.ship) when exportObj.titlesById[title.id].sources.intersects(data.allowed_sources))
addon.setById available_titles[$.randomInt available_titles.length].id if available_titles.length > 0
when 'Modification'
available_modifications = (modification for modification in @getAvailableModificationsIncluding(null, addon.ship) when exportObj.modificationsById[modification.id].sources.intersects(data.allowed_sources))
addon.setById available_modifications[$.randomInt available_modifications.length].id if available_modifications.length > 0
else
throw new Error("Invalid addon type #{addon.type}")
else
#console.log "Need to remove something"
# Remove something
removable_things = []
for ship in @ships
removable_things.push ship
for upgrade in ship.upgrades
removable_things.push upgrade if upgrade.data?
removable_things.push ship.title if ship.title?.data?
removable_things.push ship.modification if ship.modification?.data?
if removable_things.length > 0
thing_to_remove = removable_things[$.randomInt removable_things.length]
#console.log "Removing #{thing_to_remove}"
if thing_to_remove instanceof Ship
@removeShip thing_to_remove
else if thing_to_remove instanceof GenericAddon
thing_to_remove.setData null
else
throw new Error("Unknown thing to remove #{thing_to_remove}")
# continue the "loop"
window.setTimeout @_makeRandomizerLoopFunc(data), 0
else
#console.log "Clearing timer #{data.timer}, iterations=#{data.iterations}, keep_running=#{data.keep_running}"
window.clearTimeout data.timer
# Update all selectors
for ship in @ships
ship.updateSelections()
@suppress_automatic_new_ship = false
@addShip()
_makeRandomizerLoopFunc: (data) =>
() =>
@_randomizerLoopBody(data)
randomSquad: (max_points=100, allowed_sources=null, timeout_ms=1000, max_iterations=1000) ->
@backend_status.fadeOut 'slow'
@suppress_automatic_new_ship = true
# Clear all existing ships
while @ships.length > 0
@removeShip @ships[0]
throw new Error("Ships not emptied") if @ships.length > 0
data =
iterations: 0
max_points: max_points
max_iterations: max_iterations
keep_running: true
allowed_sources: allowed_sources ? exportObj.expansions
stopHandler = () =>
#console.log "*** TIMEOUT *** TIMEOUT *** TIMEOUT ***"
data.keep_running = false
data.timer = window.setTimeout stopHandler , timeout_ms
#console.log "Timer set for #{timeout_ms}ms, timer is #{data.timer}"
window.setTimeout @_makeRandomizerLoopFunc(data), 0
@resetCurrentSquad()
@current_squad.name = 'Random Squad'
@container.trigger 'xwing-backend:squadNameChanged'
setBackend: (backend) ->
@backend = backend
describeSquad: ->
(ship.pilot.name for ship in @ships when ship.pilot?).join ', '
listCards: ->
card_obj = {}
for ship in @ships
if ship.pilot?
card_obj[ship.pilot.name] = null
for upgrade in ship.upgrades
card_obj[upgrade.data.name] = null if upgrade.data?
card_obj[ship.title.data.name] = null if ship.title?.data?
card_obj[ship.modification.data.name] = null if ship.modification?.data?
return Object.keys(card_obj).sort()
getNotes: ->
@notes.val()
getObstacles: ->
@current_obstacles
isSquadPossibleWithCollection: ->
# console.log "#{@faction}: isSquadPossibleWithCollection()"
# If the collection is uninitialized or empty, don't actually check it.
if Object.keys(@collection?.expansions ? {}).length == 0
# console.log "collection not ready or is empty"
return true
@collection.reset()
validity = true
for ship in @ships
if ship.pilot?
# Try to get both the physical model and the pilot card.
ship_is_available = @collection.use('ship', ship.pilot.english_ship)
pilot_is_available = @collection.use('pilot', ship.pilot.english_name)
# console.log "#{@faction}: Ship #{ship.pilot.english_ship} available: #{ship_is_available}"
# console.log "#{@faction}: Pilot #{ship.pilot.english_name} available: #{pilot_is_available}"
validity = false unless ship_is_available and pilot_is_available
for upgrade in ship.upgrades
if upgrade.data?
upgrade_is_available = @collection.use('upgrade', upgrade.data.english_name)
# console.log "#{@faction}: Upgrade #{upgrade.data.english_name} available: #{upgrade_is_available}"
validity = false unless upgrade_is_available
for modification in ship.modifications
if modification.data?
modification_is_available = @collection.use('modification', modification.data.english_name)
# console.log "#{@faction}: Modification #{modification.data.english_name} available: #{modification_is_available}"
validity = false unless modification_is_available
for title in ship.titles
if title?.data?
title_is_available = @collection.use('title', title.data.english_name)
# console.log "#{@faction}: Title #{title.data.english_name} available: #{title_is_available}"
validity = false unless title_is_available
validity
checkCollection: ->
# console.log "#{@faction}: Checking validity of squad against collection..."
if @collection?
@collection_invalid_container.toggleClass 'hidden', @isSquadPossibleWithCollection()
toXWS: ->
# Often you will want JSON.stringify(builder.toXWS())
xws =
description: @getNotes()
faction: exportObj.toXWSFaction[@faction]
name: @current_squad.name
pilots: []
points: @total_points
vendor:
yasb:
builder: '(Yet Another) X-Wing Miniatures Squad Builder'
builder_url: window.location.href.split('?')[0]
link: @getPermaLink()
version: '0.3.0'
for ship in @ships
if ship.pilot?
xws.pilots.push ship.toXWS()
# Associate multisection ships
# This maps id to list of pilots it comprises
multisection_id_to_pilots = {}
last_id = 0
unmatched = (pilot for pilot in xws.pilots when pilot.multisection?)
for _ in [0...(unmatched.length ** 2)]
break if unmatched.length == 0
# console.log "Top of loop, unmatched: #{m.name for m in unmatched}"
unmatched_pilot = unmatched.shift()
unmatched_pilot.multisection_id ?= last_id++
multisection_id_to_pilots[unmatched_pilot.multisection_id] ?= [unmatched_pilot]
break if unmatched.length == 0
# console.log "Finding matches for #{unmatched_pilot.name} (assigned id=#{unmatched_pilot.multisection_id})"
matches = []
for candidate in unmatched
# console.log "-> examine #{candidate.name}"
if unmatched_pilot.name in candidate.multisection
matches.push candidate
unmatched_pilot.multisection.removeItem candidate.name
candidate.multisection.removeItem unmatched_pilot.name
candidate.multisection_id = unmatched_pilot.multisection_id
# console.log "-> MATCH FOUND #{candidate.name}, assigned id=#{candidate.multisection_id}"
multisection_id_to_pilots[candidate.multisection_id].push candidate
if unmatched_pilot.multisection.length == 0
# console.log "-> No more sections to match for #{unmatched_pilot.name}"
break
for match in matches
if match.multisection.length == 0
# console.log "Dequeue #{match.name} since it has no more sections to match"
unmatched.removeItem match
for pilot in xws.pilots
delete pilot.multisection if pilot.multisection?
obstacles = @getObstacles()
if obstacles? and obstacles.length > 0
xws.obstacles = obstacles
xws
toMinimalXWS: ->
# Just what's necessary
xws = @toXWS()
# Keep mandatory stuff only
for own k, v of xws
delete xws[k] unless k in ['faction', 'pilots', 'version']
for own k, v of xws.pilots
delete xws[k] unless k in ['name', 'ship', 'upgrades', 'multisection_id']
xws
loadFromXWS: (xws, cb) ->
success = null
error = null
version_list = (parseInt x for x in xws.version.split('.'))
switch
# Not doing backward compatibility pre-1.x
when version_list > [0, 1]
xws_faction = exportObj.fromXWSFaction[xws.faction]
if @faction != xws_faction
throw new Error("Attempted to load XWS for #{xws.faction} but builder is #{@faction}")
if xws.name?
@current_squad.name = xws.name
if xws.description?
@notes.val xws.description
if xws.obstacles?
@current_squad.additional_data.obstacles = xws.obstacles
@suppress_automatic_new_ship = true
@removeAllShips()
for pilot in xws.pilots
new_ship = @addShip()
for ship_name, ship_data of exportObj.ships
if @matcher(ship_data.xws, pilot.ship)
shipnameXWS =
id: ship_data.name
xws: ship_data.xws
console.log "#{pilot.xws}"
try
new_ship.setPilot (p for p in (exportObj.pilotsByFactionXWS[@faction][pilot.id] ?= exportObj.pilotsByFactionCanonicalName[@faction][pilot.id]) when p.ship == shipnameXWS.id)[0]
catch err
console.error err.message
continue
# Turn all the upgrades into a flat list so we can keep trying to add them
addons = []
for upgrade_type, upgrade_canonicals of pilot.upgrades ? {}
for upgrade_canonical in upgrade_canonicals
# console.log upgrade_type, upgrade_canonical
slot = null
slot = exportObj.fromXWSUpgrade[upgrade_type] ? upgrade_type.capitalize()
addon = exportObj.upgradesBySlotXWSName[slot][upgrade_canonical] ?= exportObj.upgradesBySlotCanonicalName[slot][upgrade_canonical]
if addon?
# console.log "-> #{upgrade_type} #{addon.name} #{slot}"
addons.push
type: slot
data: addon
slot: slot
if addons.length > 0
for _ in [0...1000]
# Try to add an addon. If it's not eligible, requeue it and
# try it again later, as another addon might allow it.
addon = addons.shift()
# console.log "Adding #{addon.data.name} to #{new_ship}..."
addon_added = false
switch addon.type
when 'Modification'
for modification in new_ship.modifications
continue if modification.data?
modification.setData addon.data
addon_added = true
break
when 'Title'
for title in new_ship.titles
continue if title.data?
# Special cases :(
if addon.data instanceof Array
# Right now, the only time this happens is because of
# Heavy Scyk. Check the rest of the pending addons for torp,
# cannon, or missiles. Otherwise, it doesn't really matter.
slot_guesses = (a.data.slot for a in addons when a.data.slot in ['Cannon', 'Missile', 'Torpedo'])
# console.log slot_guesses
if slot_guesses.length > 0
# console.log "Guessing #{slot_guesses[0]}"
title.setData exportObj.titlesByLocalizedName[""""Heavy Scyk" Interceptor (#{slot_guesses[0]})"""]
else
# console.log "No idea, setting to #{addon.data[0].name}"
title.setData addon.data[0]
else
title.setData addon.data
addon_added = true
else
# console.log "Looking for unused #{addon.slot} in #{new_ship}..."
for upgrade, i in new_ship.upgrades
continue if upgrade.slot != addon.slot or upgrade.data?
upgrade.setData addon.data
addon_added = true
break
if addon_added
# console.log "Successfully added #{addon.data.name} to #{new_ship}"
if addons.length == 0
# console.log "Done with addons for #{new_ship}"
break
else
# Can't add it, requeue unless there are no other addons to add
# in which case this isn't valid
if addons.length == 0
success = false
error = "Could not add #{addon.data.name} to #{new_ship}"
break
else
# console.log "Could not add #{addon.data.name} to #{new_ship}, trying later"
addons.push addon
if addons.length > 0
success = false
error = "Could not add all upgrades"
break
@suppress_automatic_new_ship = false
# Finally, the unassigned ship
@addShip()
success = true
else
success = false
error = "Invalid or unsupported XWS version"
if success
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadNameChanged'
@container.trigger 'xwing-backend:squadDirtinessChanged'
# console.log "success: #{success}, error: #{error}"
cb
success: success
error: error
class Ship
constructor: (args) ->
# args
@builder = args.builder
@container = args.container
# internal state
@pilot = null
@data = null # ship data
@upgrades = []
@modifications = []
@titles = []
@setupUI()
destroy: (cb) ->
@resetPilot()
@resetAddons()
@teardownUI()
idx = @builder.ships.indexOf this
if idx < 0
throw new Error("Ship not registered with builder")
@builder.ships.splice idx, 1
cb()
copyFrom: (other) ->
throw new Error("Cannot copy from self") if other is this
#console.log "Attempt to copy #{other?.pilot?.name}"
return unless other.pilot? and other.data?
#console.log "Setting pilot to ID=#{other.pilot.id}"
if other.pilot.unique
# Look for cheapest generic or available unique, otherwise do nothing
available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled)
if available_pilots.length > 0
@setPilotById available_pilots[0].id
# Can't just copy upgrades since slots may be different
# Similar to setPilot() when ship is the same
other_upgrades = {}
for upgrade in other.upgrades
if upgrade?.data? and not upgrade.data.unique and ((not upgrade.data.max_per_squad?) or @builder.countUpgrades(upgrade.data.canonical_name) < upgrade.data.max_per_squad)
other_upgrades[upgrade.slot] ?= []
other_upgrades[upgrade.slot].push upgrade
other_modifications = []
for modification in other.modifications
if modification?.data? and not modification.data.unique
other_modifications.push modification
other_titles = []
for title in other.titles
if title?.data? and not title.data.unique
other_titles.push title
for title in @titles
other_title = other_titles.shift()
if other_title?
title.setById other_title.data.id
for modification in @modifications
other_modification = other_modifications.shift()
if other_modification?
modification.setById other_modification.data.id
for upgrade in @upgrades
other_upgrade = (other_upgrades[upgrade.slot] ? []).shift()
if other_upgrade?
upgrade.setById other_upgrade.data.id
else
return
else
# Exact clone, so we can copy things over directly
@setPilotById other.pilot.id
# set up non-conferred addons
other_conferred_addons = []
other_conferred_addons = other_conferred_addons.concat(other.titles[0].conferredAddons) if other.titles[0]?.data? # and other.titles.conferredAddons.length > 0
other_conferred_addons = other_conferred_addons.concat(other.modifications[0].conferredAddons) if other.modifications[0]?.data?
#console.log "Looking for conferred upgrades..."
for other_upgrade, i in other.upgrades
# console.log "Examining upgrade #{other_upgrade}"
if other_upgrade.data? and other_upgrade not in other_conferred_addons and not other_upgrade.data.unique and i < @upgrades.length and ((not other_upgrade.data.max_per_squad?) or @builder.countUpgrades(other_upgrade.data.canonical_name) < other_upgrade.data.max_per_squad)
#console.log "Copying non-unique upgrade #{other_upgrade} into slot #{i}"
@upgrades[i].setById other_upgrade.data.id
#console.log "Checking other ship base title #{other.title ? null}"
@titles[0].setById other.titles[0].data.id if other.titles[0]?.data? and not other.titles[0].data.unique
#console.log "Checking other ship base modification #{other.modifications[0] ? null}"
@modifications[0].setById other.modifications[0].data.id if other.modifications[0]?.data and not other.modifications[0].data.unique
# set up conferred non-unique addons
#console.log "Attempt to copy conferred addons..."
if other.titles[0]? and other.titles[0].conferredAddons.length > 0
#console.log "Other ship title #{other.titles[0]} confers addons"
for other_conferred_addon, i in other.titles[0].conferredAddons
@titles[0].conferredAddons[i].setById other_conferred_addon.data.id if other_conferred_addon.data? and not other_conferred_addon.data?.unique
if other.modifications[0]? and other.modifications[0].conferredAddons.length > 0
#console.log "Other ship base modification #{other.modifications[0]} confers addons"
for other_conferred_addon, i in other.modifications[0].conferredAddons
@modifications[0].conferredAddons[i].setById other_conferred_addon.data.id if other_conferred_addon.data? and not other_conferred_addon.data?.unique
@updateSelections()
@builder.container.trigger 'xwing:pointsUpdated'
@builder.current_squad.dirty = true
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
setShipType: (ship_type) ->
@pilot_selector.data('select2').container.show()
if ship_type != @pilot?.ship
# Ship changed; select first non-unique
@setPilot (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not exportObj.pilotsById[result.id].unique)[0]
# Clear ship background class
for cls in @row.attr('class').split(/\s+/)
if cls.indexOf('ship-') == 0
@row.removeClass cls
# Show delete button
@remove_button.fadeIn 'fast'
# Ship background
@row.addClass "ship-#{ship_type.toLowerCase().replace(/[^a-z0-9]/gi, '')}0"
@builder.container.trigger 'xwing:shipUpdated'
setPilotById: (id) ->
@setPilot exportObj.pilotsById[parseInt id]
setPilotByName: (name) ->
@setPilot exportObj.pilotsByLocalizedName[$.trim name]
setPilot: (new_pilot) ->
if new_pilot != @pilot
@builder.current_squad.dirty = true
same_ship = @pilot? and new_pilot?.ship == @pilot.ship
old_upgrades = {}
old_titles = []
old_modifications = []
if same_ship
# track addons and try to reassign them
for upgrade in @upgrades
if upgrade?.data?
old_upgrades[upgrade.slot] ?= []
old_upgrades[upgrade.slot].push upgrade
for title in @titles
if title?.data?
old_titles.push title
for modification in @modifications
if modification?.data?
old_modifications.push modification
@resetPilot()
@resetAddons()
if new_pilot?
@data = exportObj.ships[new_pilot?.ship]
if new_pilot?.unique?
await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ]
@pilot = new_pilot
@setupAddons() if @pilot?
@copy_button.show()
@setShipType @pilot.ship
if same_ship
# Hopefully this order is correct
for title in @titles
old_title = old_titles.shift()
if old_title?
title.setById old_title.data.id
for modification in @modifications
old_modification = old_modifications.shift()
if old_modification?
modification.setById old_modification.data.id
for upgrade in @upgrades
old_upgrade = (old_upgrades[upgrade.slot] ? []).shift()
if old_upgrade?
upgrade.setById old_upgrade.data.id
else
@copy_button.hide()
@builder.container.trigger 'xwing:pointsUpdated'
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
resetPilot: ->
if @pilot?.unique?
await @builder.container.trigger 'xwing:releaseUnique', [ @pilot, 'Pilot', defer() ]
@pilot = null
setupAddons: ->
# Upgrades from pilot
for slot in @pilot.slots ? []
@upgrades.push new exportObj.Upgrade
ship: this
container: @addon_container
slot: slot
# Title
#if @pilot.ship of exportObj.titlesByShip
# @titles.push new exportObj.Title
# ship: this
# container: @addon_container
# Modifications
#@modifications.push new exportObj.Modification
# ship: this
# container: @addon_container
resetAddons: ->
await
for title in @titles
title.destroy defer() if title?
for upgrade in @upgrades
upgrade.destroy defer() if upgrade?
for modification in @modifications
modification.destroy defer() if modification?
@upgrades = []
@modifications = []
@titles = []
getPoints: ->
points = @pilot?.points ? 0
for title in @titles
points += (title?.getPoints() ? 0)
for upgrade in @upgrades
points += upgrade.getPoints()
for modification in @modifications
points += (modification?.getPoints() ? 0)
@points_container.find('span').text points
if points > 0
@points_container.fadeTo 'fast', 1
else
@points_container.fadeTo 0, 0
points
getEpicPoints: ->
@data?.epic_points ? 0
updateSelections: ->
if @pilot?
@ship_selector.select2 'data',
id: @pilot.ship
text: @pilot.ship
canonical_name: exportObj.ships[@pilot.ship].canonical_name
@pilot_selector.select2 'data',
id: @pilot.id
text: "#{@pilot.name} (#{@pilot.points})"
@pilot_selector.data('select2').container.show()
for upgrade in @upgrades
upgrade.updateSelection()
for title in @titles
title.updateSelection() if title?
for modification in @modifications
modification.updateSelection() if modification?
else
@pilot_selector.select2 'data', null
@pilot_selector.data('select2').container.toggle(@ship_selector.val() != '')
setupUI: ->
@row = $ document.createElement 'DIV'
@row.addClass 'row-fluid ship'
@row.insertBefore @builder.notes_container
@row.append $.trim '''
<div class="span3">
<input class="ship-selector-container" type="hidden" />
<br />
<input type="hidden" class="pilot-selector-container" />
</div>
<div class="span1 points-display-container">
<span></span>
</div>
<div class="span6 addon-container" />
<div class="span2 button-container">
<button class="btn btn-danger remove-pilot"><span class="visible-desktop visible-tablet hidden-phone" data-toggle="tooltip" title="Remove Pilot"><i class="fa fa-times"></i></span><span class="hidden-desktop hidden-tablet visible-phone">Remove Pilot</span></button>
<button class="btn copy-pilot"><span class="visible-desktop visible-tablet hidden-phone" data-toggle="tooltip" title="Clone Pilot"><i class="fa fa-files-o"></i></span><span class="hidden-desktop hidden-tablet visible-phone">Clone Pilot</span></button>
</div>
'''
@row.find('.button-container span').tooltip()
@ship_selector = $ @row.find('input.ship-selector-container')
@pilot_selector = $ @row.find('input.pilot-selector-container')
shipResultFormatter = (object, container, query) ->
# Append directly so we don't have to disable markup escaping
$(container).append """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.canonical_name}"></i> #{object.text}"""
# If you return a string, Select2 will render it
undefined
@ship_selector.select2
width: '100%'
placeholder: exportObj.translate @builder.language, 'ui', 'shipSelectorPlaceholder'
query: (query) =>
@builder.checkCollection()
query.callback
more: false
results: @builder.getAvailableShipsMatching(query.term)
minimumResultsForSearch: if $.isMobile() then -1 else 0
formatResultCssClass: (obj) =>
if @builder.collection?
not_in_collection = false
if @pilot? and obj.id == exportObj.ships[@pilot.ship].id
# Currently selected ship; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@builder.collection.checkShelf('ship', obj.english_name) or @builder.collection.checkTable('pilot', obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @builder.collection.checkShelf('ship', obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
formatResult: shipResultFormatter
formatSelection: shipResultFormatter
@ship_selector.on 'change', (e) =>
@setShipType @ship_selector.val()
# assign ship row an id for testing purposes
@row.attr 'id', "row-#{@ship_selector.data('select2').container.attr('id')}"
@pilot_selector.select2
width: '100%'
placeholder: exportObj.translate @builder.language, 'ui', 'pilotSelectorPlaceholder'
query: (query) =>
@builder.checkCollection()
query.callback
more: false
results: @builder.getAvailablePilotsForShipIncluding(@ship_selector.val(), @pilot, query.term)
minimumResultsForSearch: if $.isMobile() then -1 else 0
formatResultCssClass: (obj) =>
if @builder.collection?
not_in_collection = false
if obj.id == @pilot?.id
# Currently selected pilot; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@builder.collection.checkShelf('pilot', obj.english_name) or @builder.collection.checkTable('pilot', obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @builder.collection.checkShelf('pilot', obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
@pilot_selector.on 'change', (e) =>
@setPilotById @pilot_selector.select2('val')
@builder.current_squad.dirty = true
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
@builder.backend_status.fadeOut 'slow'
@pilot_selector.data('select2').results.on 'mousemove-filtered', (e) =>
select2_data = $(e.target).closest('.select2-result').data 'select2-data'
@builder.showTooltip 'Pilot', exportObj.pilotsById[select2_data.id], {ship: @data?.english_name} if select2_data?.id?
@pilot_selector.data('select2').container.on 'mouseover', (e) =>
@builder.showTooltip 'Ship', this if @data?
@pilot_selector.data('select2').container.hide()
@points_container = $ @row.find('.points-display-container')
@points_container.fadeTo 0, 0
@addon_container = $ @row.find('div.addon-container')
@remove_button = $ @row.find('button.remove-pilot')
@remove_button.click (e) =>
e.preventDefault()
@row.slideUp 'fast', () =>
@builder.removeShip this
@backend_status?.fadeOut 'slow'
@remove_button.hide()
@copy_button = $ @row.find('button.copy-pilot')
@copy_button.click (e) =>
clone = @builder.ships[@builder.ships.length - 1]
clone.copyFrom(this)
@copy_button.hide()
teardownUI: ->
@row.text ''
@row.remove()
toString: ->
if @pilot?
"Pilot #{@pilot.name} flying #{@data.name}"
else
"Ship without pilot"
toHTML: ->
effective_stats = @effectiveStats()
action_icons = []
action_icons_red = []
for action in effective_stats.actions
action_icons.push switch action
when 'Focus'
"""<i class="xwing-miniatures-font xwing-miniatures-font-focus"></i>"""
when 'Evade'
"""<i class="xwing-miniatures-font xwing-miniatures-font-evade"></i>"""
when 'Barrel Roll'
"""<i class="xwing-miniatures-font xwing-miniatures-font-barrelroll"></i>"""
when 'Target Lock'
"""<i class="xwing-miniatures-font xwing-miniatures-font-lock"></i>"""
when 'Boost'
"""<i class="xwing-miniatures-font xwing-miniatures-font-boost"></i>"""
when 'Coordinate'
"""<i class="xwing-miniatures-font xwing-miniatures-font-coordinate"></i>"""
when 'Jam'
"""<i class="xwing-miniatures-font xwing-miniatures-font-jam"></i>"""
when 'Recover'
"""<i class="xwing-miniatures-font xwing-miniatures-font-recover"></i>"""
when 'Reinforce'
"""<i class="xwing-miniatures-font xwing-miniatures-font-reinforce"></i>"""
when 'Cloak'
"""<i class="xwing-miniatures-font xwing-miniatures-font-cloak"></i>"""
when 'Slam'
"""<i class="xwing-miniatures-font xwing-miniatures-font-slam"></i>"""
when 'Rotate Arc'
"""<i class="xwing-miniatures-font xwing-miniatures-font-rotatearc"></i>"""
when 'Reload'
"""<i class="xwing-miniatures-font xwing-miniatures-font-reload"></i>"""
when 'Calculate'
"""<i class="xwing-miniatures-font xwing-miniatures-font-calculate"></i>"""
when "<r>> Target Lock</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-lock"></i></r>"""
when "<r>> Barrel Roll</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-barrelroll"></i></r>"""
when "<r>> Focus</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-focus"></i></r>"""
when "<r>> Rotate Arc</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-rotatearc"></i></r>"""
when "<r>> Evade</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-evade"></i></r>"""
when "<r>> Calculate</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-calculate"></i></r>"""
else
"""<span> #{action}<span>"""
for actionred in effective_stats.actionsred
action_icons_red.push switch actionred
when 'Focus'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-focus"></i>"""
when 'Evade'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-evade"></i>"""
when 'Barrel Roll'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-barrelroll"></i>"""
when 'Target Lock'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-lock"></i>"""
when 'Boost'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-boost"></i>"""
when 'Coordinate'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-coordinate"></i>"""
when 'Jam'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-jam"></i>"""
when 'Recover'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-recover"></i>"""
when 'Reinforce'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-reinforce"></i>"""
when 'Cloak'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-cloak"></i>"""
when 'Slam'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-slam"></i>"""
when 'Rotate Arc'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-rotatearc"></i>"""
when 'Reload'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-reload"></i>"""
when 'Calculate'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-calculate"></i>"""
else
"""<span> #{action}<span>"""
action_bar = action_icons.join ' '
action_bar_red = action_icons_red.join ' '
attack_icon = @data.attack_icon ? 'xwing-miniatures-font-frontarc'
attackHTML = if (@pilot.ship_override?.attack? or @data.attack?) then $.trim """
<i class="xwing-miniatures-font #{attack_icon}"></i>
<span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attack ? @data.attack), effective_stats, 'attack')}</span>
""" else ''
energyHTML = if (@pilot.ship_override?.energy? or @data.energy?) then $.trim """
<i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>
<span class="info-data info-energy">#{statAndEffectiveStat((@pilot.ship_override?.energy ? @data.energy), effective_stats, 'energy')}</span>
""" else ''
forceHTML = if (@pilot.force?) then $.trim """
<i class="xwing-miniatures-font xwing-miniatures-font-force"></i>
<span class="info-data info-force">#{statAndEffectiveStat((@pilot.ship_override?.force ? @pilot.force), effective_stats, 'force')}</span>
""" else ''
html = $.trim """
<div class="fancy-pilot-header">
<div class="pilot-header-text">#{@pilot.name} <i class="xwing-miniatures-ship xwing-miniatures-ship-#{@data.canonical_name}"></i><span class="fancy-ship-type"> #{@data.name}</span></div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle pilot-points">#{@pilot.points}</div>
</div>
</div>
</div>
<div class="fancy-pilot-stats">
<div class="pilot-stats-content">
<span class="info-data info-skill">PS #{statAndEffectiveStat(@pilot.skill, effective_stats, 'skill')}</span>
#{attackHTML}
#{energyHTML}
<i class="xwing-miniatures-font xwing-miniatures-font-agility"></i>
<span class="info-data info-agility">#{statAndEffectiveStat((@pilot.ship_override?.agility ? @data.agility), effective_stats, 'agility')}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-hull"></i>
<span class="info-data info-hull">#{statAndEffectiveStat((@pilot.ship_override?.hull ? @data.hull), effective_stats, 'hull')}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-shield"></i>
<span class="info-data info-shields">#{statAndEffectiveStat((@pilot.ship_override?.shields ? @data.shields), effective_stats, 'shields')}</span>
#{forceHTML}
#{action_bar}
#{action_bar_red}
</div>
</div>
"""
if @pilot.text
html += $.trim """
<div class="fancy-pilot-text">#{@pilot.text}</div>
"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
html += $.trim """
<div class="fancy-upgrade-container">
"""
for upgrade in slotted_upgrades
html += upgrade.toHTML()
html += $.trim """
</div>
"""
# if @getPoints() != @pilot.points
html += $.trim """
<div class="ship-points-total">
<strong>Ship Total: #{@getPoints()}</strong>
</div>
"""
"""<div class="fancy-ship">#{html}</div>"""
toTableRow: ->
table_html = $.trim """
<tr class="simple-pilot">
<td class="name">#{@pilot.name} — #{@data.name}</td>
<td class="points">#{@pilot.points}</td>
</tr>
"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
for upgrade in slotted_upgrades
table_html += upgrade.toTableRow()
# if @getPoints() != @pilot.points
table_html += """<tr class="simple-ship-total"><td colspan="2">Ship Total: #{@getPoints()}</td></tr>"""
table_html += '<tr><td> </td><td></td></tr>'
table_html
toBBCode: ->
bbcode = """[b]#{@pilot.name} (#{@pilot.points})[/b]"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
bbcode +="\n"
bbcode_upgrades= []
for upgrade in slotted_upgrades
upgrade_bbcode = upgrade.toBBCode()
bbcode_upgrades.push upgrade_bbcode if upgrade_bbcode?
bbcode += bbcode_upgrades.join "\n"
bbcode
toSimpleHTML: ->
html = """<b>#{@pilot.name} (#{@pilot.points})</b><br />"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
for upgrade in slotted_upgrades
upgrade_html = upgrade.toSimpleHTML()
html += upgrade_html if upgrade_html?
html
toSerialized: ->
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
# Skip conferred upgrades
conferred_addons = []
for title in @titles
conferred_addons = conferred_addons.concat(title?.conferredAddons ? [])
for modification in @modifications
conferred_addons = conferred_addons.concat(modification?.conferredAddons ? [])
for upgrade in @upgrades
conferred_addons = conferred_addons.concat(upgrade?.conferredAddons ? [])
upgrades = """#{upgrade?.data?.id ? -1 for upgrade, i in @upgrades when upgrade not in conferred_addons}"""
serialized_conferred_addons = []
for addon in conferred_addons
serialized_conferred_addons.push addon.toSerialized()
[
@pilot.id,
upgrades,
@titles[0]?.data?.id ? -1,
@modifications[0]?.data?.id ? -1,
serialized_conferred_addons.join(','),
].join ':'
fromSerialized: (version, serialized) ->
switch version
when 1
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:TITLEUPGRADE1,TITLEUPGRADE2:MODIFICATIONID
[ pilot_id, upgrade_ids, title_id, title_conferred_upgrade_ids, modification_id ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
@upgrades[i].setById upgrade_id if upgrade_id >= 0
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
if @titles[0]? and @titles[0].conferredAddons.length > 0
for upgrade_id, i in title_conferred_upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
@titles[0].conferredAddons[i].setById upgrade_id if upgrade_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
when 2, 3
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
[ pilot_id, upgrade_ids, title_id, modification_id, conferredaddon_pairs ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
deferred_ids = []
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
continue if upgrade_id < 0 or isNaN(upgrade_id)
if @upgrades[i].isOccupied()
deferred_ids.push upgrade_id
else
@upgrades[i].setById upgrade_id
for deferred_id in deferred_ids
for upgrade, i in @upgrades
continue if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot
upgrade.setById deferred_id
break
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
# We confer title addons before modification addons, to pick an arbitrary ordering.
if conferredaddon_pairs?
conferredaddon_pairs = conferredaddon_pairs.split ','
else
conferredaddon_pairs = []
if @titles[0]? and @titles[0].conferredAddons.length > 0
title_conferred_addon_pairs = conferredaddon_pairs.splice 0, @titles[0].conferredAddons.length
for conferredaddon_pair, i in title_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = @titles[0].conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for modification in @modifications
if modification?.data? and modification.conferredAddons.length > 0
modification_conferred_addon_pairs = conferredaddon_pairs.splice 0, modification.conferredAddons.length
for conferredaddon_pair, i in modification_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = modification.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
when 4
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
[ pilot_id, upgrade_ids, title_id, modification_id, conferredaddon_pairs ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
deferred_ids = []
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
continue if upgrade_id < 0 or isNaN(upgrade_id)
# Defer fat upgrades
if @upgrades[i].isOccupied() or @upgrades[i].dataById[upgrade_id].also_occupies_upgrades?
deferred_ids.push upgrade_id
else
@upgrades[i].setById upgrade_id
for deferred_id in deferred_ids
for upgrade, i in @upgrades
continue if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot
upgrade.setById deferred_id
break
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
# We confer title addons before modification addons, to pick an arbitrary ordering.
if conferredaddon_pairs?
conferredaddon_pairs = conferredaddon_pairs.split ','
else
conferredaddon_pairs = []
for title, i in @titles
if title?.data? and title.conferredAddons.length > 0
# console.log "Confer title #{title.data.name} at #{i}"
title_conferred_addon_pairs = conferredaddon_pairs.splice 0, title.conferredAddons.length
for conferredaddon_pair, i in title_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = title.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for modification in @modifications
if modification?.data? and modification.conferredAddons.length > 0
modification_conferred_addon_pairs = conferredaddon_pairs.splice 0, modification.conferredAddons.length
for conferredaddon_pair, i in modification_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = modification.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for upgrade in @upgrades
if upgrade?.data? and upgrade.conferredAddons.length > 0
upgrade_conferred_addon_pairs = conferredaddon_pairs.splice 0, upgrade.conferredAddons.length
for conferredaddon_pair, i in upgrade_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = upgrade.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
@updateSelections()
effectiveStats: ->
stats =
skill: @pilot.skill
attack: @pilot.ship_override?.attack ? @data.attack
attackf: @pilot.ship_override?.attackf ? @data.attackf
attackb: @pilot.ship_override?.attackb ? @data.attackb
attackt: @pilot.ship_override?.attackt ? @data.attackt
attackdt: @pilot.ship_override?.attackdt ? @data.attackdt
energy: @pilot.ship_override?.energy ? @data.energy
agility: @pilot.ship_override?.agility ? @data.agility
hull: @pilot.ship_override?.hull ? @data.hull
shields: @pilot.ship_override?.shields ? @data.shields
force: @pilot.ship_override?.force ? @pilot.force
charge: @pilot.ship_override?.charge ? @pilot.charge
actions: (@pilot.ship_override?.actions ? @data.actions).slice 0
actionsred: ((@pilot.ship_override?.actionsred ? @data.actionsred) ? []).slice 0
# need a deep copy of maneuvers array
stats.maneuvers = []
for s in [0 ... (@data.maneuvers ? []).length]
stats.maneuvers[s] = @data.maneuvers[s].slice 0
for upgrade in @upgrades
upgrade.data.modifier_func(stats) if upgrade?.data?.modifier_func?
for title in @titles
title.data.modifier_func(stats) if title?.data?.modifier_func?
for modification in @modifications
modification.data.modifier_func(stats) if modification?.data?.modifier_func?
@pilot.modifier_func(stats) if @pilot?.modifier_func?
stats
validate: ->
# Remove addons that violate their validation functions (if any) one by one
# until everything checks out
# If there is no explicit validation_func, use restriction_func
max_checks = 128 # that's a lot of addons (Epic?)
for i in [0...max_checks]
valid = true
for upgrade in @upgrades
func = upgrade?.data?.validation_func ? upgrade?.data?.restriction_func ? undefined
if func? and not func(this, upgrade)
#console.log "Invalid upgrade: #{upgrade?.data?.name}"
upgrade.setById null
valid = false
break
for title in @titles
func = title?.data?.validation_func ? title?.data?.restriction_func ? undefined
if func? and not func this
#console.log "Invalid title: #{title?.data?.name}"
title.setById null
valid = false
break
for modification in @modifications
func = modification?.data?.validation_func ? modification?.data?.restriction_func ? undefined
if func? and not func(this, modification)
#console.log "Invalid modification: #{modification?.data?.name}"
modification.setById null
valid = false
break
break if valid
@updateSelections()
checkUnreleasedContent: ->
if @pilot? and not exportObj.isReleased @pilot
#console.log "#{@pilot.name} is unreleased"
return true
for title in @titles
if title?.data? and not exportObj.isReleased title.data
#console.log "#{title.data.name} is unreleased"
return true
for modification in @modifications
if modification?.data? and not exportObj.isReleased modification.data
#console.log "#{modification.data.name} is unreleased"
return true
for upgrade in @upgrades
if upgrade?.data? and not exportObj.isReleased upgrade.data
#console.log "#{upgrade.data.name} is unreleased"
return true
false
checkEpicContent: ->
if @pilot? and @pilot.epic?
return true
for title in @titles
if title?.data?.epic?
return true
for modification in @modifications
if modification?.data?.epic?
return true
for upgrade in @upgrades
if upgrade?.data?.epic?
return true
false
hasAnotherUnoccupiedSlotLike: (upgrade_obj) ->
for upgrade in @upgrades
continue if upgrade == upgrade_obj or upgrade.slot != upgrade_obj.slot
return true unless upgrade.isOccupied()
false
toXWS: ->
xws =
id: (@pilot.xws ? @pilot.canonical_name)
points: @getPoints()
#ship: @data.canonical_name
ship: @data.xws.canonicalize()
if @data.multisection
xws.multisection = @data.multisection.slice 0
upgrade_obj = {}
for upgrade in @upgrades
if upgrade?.data?
upgrade.toXWS upgrade_obj
for modification in @modifications
if modification?.data?
modification.toXWS upgrade_obj
for title in @titles
if title?.data?
title.toXWS upgrade_obj
if Object.keys(upgrade_obj).length > 0
xws.upgrades = upgrade_obj
xws
getConditions: ->
if Set?
conditions = new Set()
if @pilot?.applies_condition?
if @pilot.applies_condition instanceof Array
for condition in @pilot.applies_condition
conditions.add(exportObj.conditionsByCanonicalName[condition])
else
conditions.add(exportObj.conditionsByCanonicalName[@pilot.applies_condition])
for upgrade in @upgrades
if upgrade?.data?.applies_condition?
if upgrade.data.applies_condition instanceof Array
for condition in upgrade.data.applies_condition
conditions.add(exportObj.conditionsByCanonicalName[condition])
else
conditions.add(exportObj.conditionsByCanonicalName[upgrade.data.applies_condition])
conditions
else
console.warn 'Set not supported in this JS implementation, not implementing conditions'
[]
class GenericAddon
constructor: (args) ->
# args
@ship = args.ship
@container = $ args.container
# internal state
@data = null
@unadjusted_data = null
@conferredAddons = []
@serialization_code = 'X'
@occupied_by = null
@occupying = []
@destroyed = false
# Overridden by children
@type = null
@dataByName = null
@dataById = null
@adjustment_func = args.adjustment_func if args.adjustment_func?
@filter_func = args.filter_func if args.filter_func?
@placeholderMod_func = if args.placeholderMod_func? then args.placeholderMod_func else (x) => x
destroy: (cb, args...) ->
return cb(args) if @destroyed
if @data?.unique?
await @ship.builder.container.trigger 'xwing:releaseUnique', [ @data, @type, defer() ]
@destroyed = true
@rescindAddons()
@deoccupyOtherUpgrades()
@selector.select2 'destroy'
cb args
setupSelector: (args) ->
@selector = $ document.createElement 'INPUT'
@selector.attr 'type', 'hidden'
@container.append @selector
args.minimumResultsForSearch = -1 if $.isMobile()
args.formatResultCssClass = (obj) =>
if @ship.builder.collection?
not_in_collection = false
if obj.id == @data?.id
# Currently selected card; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@ship.builder.collection.checkShelf(@type.toLowerCase(), obj.english_name) or @ship.builder.collection.checkTable(@type.toLowerCase(), obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @ship.builder.collection.checkShelf(@type.toLowerCase(), obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
args.formatSelection = (obj, container) =>
icon = switch @type
when 'Upgrade'
@slot.toLowerCase().replace(/[^0-9a-z]/gi, '')
else
@type.toLowerCase().replace(/[^0-9a-z]/gi, '')
icon = icon.replace("configuration", "config")
.replace("force", "forcepower")
# Append directly so we don't have to disable markup escaping
$(container).append """<i class="xwing-miniatures-font xwing-miniatures-font-#{icon}"></i> #{obj.text}"""
# If you return a string, Select2 will render it
undefined
@selector.select2 args
@selector.on 'change', (e) =>
@setById @selector.select2('val')
@ship.builder.current_squad.dirty = true
@ship.builder.container.trigger 'xwing-backend:squadDirtinessChanged'
@ship.builder.backend_status.fadeOut 'slow'
@selector.data('select2').results.on 'mousemove-filtered', (e) =>
select2_data = $(e.target).closest('.select2-result').data 'select2-data'
@ship.builder.showTooltip 'Addon', @dataById[select2_data.id], {addon_type: @type} if select2_data?.id?
@selector.data('select2').container.on 'mouseover', (e) =>
@ship.builder.showTooltip 'Addon', @data, {addon_type: @type} if @data?
setById: (id) ->
@setData @dataById[parseInt id]
setByName: (name) ->
@setData @dataByName[$.trim name]
setData: (new_data) ->
if new_data?.id != @data?.id
if @data?.unique?
await @ship.builder.container.trigger 'xwing:releaseUnique', [ @unadjusted_data, @type, defer() ]
@rescindAddons()
@deoccupyOtherUpgrades()
if new_data?.unique?
await @ship.builder.container.trigger 'xwing:claimUnique', [ new_data, @type, defer() ]
# Need to make a copy of the data, but that means I can't just check equality
@data = @unadjusted_data = new_data
if @data?
if @data.superseded_by_id
return @setById @data.superseded_by_id
if @adjustment_func?
@data = @adjustment_func(@data)
@unequipOtherUpgrades()
@occupyOtherUpgrades()
@conferAddons()
else
@deoccupyOtherUpgrades()
@ship.builder.container.trigger 'xwing:pointsUpdated'
conferAddons: ->
if @data.confersAddons? and @data.confersAddons.length > 0
for addon in @data.confersAddons
cls = addon.type
args =
ship: @ship
container: @container
args.slot = addon.slot if addon.slot?
args.adjustment_func = addon.adjustment_func if addon.adjustment_func?
args.filter_func = addon.filter_func if addon.filter_func?
args.auto_equip = addon.auto_equip if addon.auto_equip?
args.placeholderMod_func = addon.placeholderMod_func if addon.placeholderMod_func?
addon = new cls args
if addon instanceof exportObj.Upgrade
@ship.upgrades.push addon
else if addon instanceof exportObj.Modification
@ship.modifications.push addon
else if addon instanceof exportObj.Title
@ship.titles.push addon
else
throw new Error("Unexpected addon type for addon #{addon}")
@conferredAddons.push addon
rescindAddons: ->
await
for addon in @conferredAddons
addon.destroy defer()
for addon in @conferredAddons
if addon instanceof exportObj.Upgrade
@ship.upgrades.removeItem addon
else if addon instanceof exportObj.Modification
@ship.modifications.removeItem addon
else if addon instanceof exportObj.Title
@ship.titles.removeItem addon
else
throw new Error("Unexpected addon type for addon #{addon}")
@conferredAddons = []
getPoints: ->
# Moar special case jankiness
if @data?.variableagility? and @ship?
Math.max(@data?.basepoints ? 0, (@data?.basepoints ? 0) + ((@ship?.data.agility - 1)*2) + 1)
else if @data?.variablebase? and not (@ship.data.medium? or @ship.data.large?)
Math.max(0, @data?.basepoints)
else if @data?.variablebase? and @ship?.data.medium?
Math.max(0, (@data?.basepoints ? 0) + (@data?.basepoints))
else if @data?.variablebase? and @ship?.data.large?
Math.max(0, (@data?.basepoints ? 0) + (@data?.basepoints * 2))
else
@data?.points ? 0
updateSelection: ->
if @data?
@selector.select2 'data',
id: @data.id
text: "#{@data.name} (#{@data.points})"
else
@selector.select2 'data', null
toString: ->
if @data?
"#{@data.name} (#{@data.points})"
else
"No #{@type}"
toHTML: ->
if @data?
upgrade_slot_font = (@data.slot ? @type).toLowerCase().replace(/[^0-9a-z]/gi, '')
match_array = @data.text.match(/(<span.*<\/span>)<br \/><br \/>(.*)/)
if match_array
restriction_html = '<div class="card-restriction-container">' + match_array[1] + '</div>'
text_str = match_array[2]
else
restriction_html = ''
text_str = @data.text
attackHTML = if (@data.attack?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attack}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-frontarc"></i>
</div>
""" else if (@data.attackt?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attackt}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-singleturretarc"></i>
</div>
""" else if (@data.attackbull?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attackbull}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-bullseyearc"></i>
</div>
""" else ''
energyHTML = if (@data.energy?) then $.trim """
<div class="upgrade-energy">
<span class="info-data info-energy">#{@data.energy}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>
</div>
""" else ''
$.trim """
<div class="upgrade-container">
<div class="upgrade-stats">
<div class="upgrade-name"><i class="xwing-miniatures-font xwing-miniatures-font-#{upgrade_slot_font}"></i>#{@data.name}</div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle upgrade-points">#{@data.points}</div>
</div>
</div>
#{restriction_html}
</div>
#{attackHTML}
#{energyHTML}
<div class="upgrade-text">#{text_str}</div>
<div style="clear: both;"></div>
</div>
"""
else
''
toTableRow: ->
if @data?
$.trim """
<tr class="simple-addon">
<td class="name">#{@data.name}</td>
<td class="points">#{@data.points}</td>
</tr>
"""
else
''
toBBCode: ->
if @data?
"""[i]#{@data.name} (#{@data.points})[/i]"""
else
null
toSimpleHTML: ->
if @data?
"""<i>#{@data.name} (#{@data.points})</i><br />"""
else
''
toSerialized: ->
"""#{@serialization_code}.#{@data?.id ? -1}"""
unequipOtherUpgrades: ->
for slot in @data?.unequips_upgrades ? []
for upgrade in @ship.upgrades
continue if upgrade.slot != slot or upgrade == this or not upgrade.isOccupied()
upgrade.setData null
break
if @data?.unequips_modifications
for modification in @ship.modifications
continue unless modification == this or modification.isOccupied()
modification.setData null
isOccupied: ->
@data? or @occupied_by?
occupyOtherUpgrades: ->
for slot in @data?.also_occupies_upgrades ? []
for upgrade in @ship.upgrades
continue if upgrade.slot != slot or upgrade == this or upgrade.isOccupied()
@occupy upgrade
break
if @data?.also_occupies_modifications
for modification in @ship.modifications
continue if modification == this or modification.isOccupied()
@occupy modification
deoccupyOtherUpgrades: ->
for upgrade in @occupying
@deoccupy upgrade
occupy: (upgrade) ->
upgrade.occupied_by = this
upgrade.selector.select2 'enable', false
@occupying.push upgrade
deoccupy: (upgrade) ->
upgrade.occupied_by = null
upgrade.selector.select2 'enable', true
occupiesAnotherUpgradeSlot: ->
for upgrade in @ship.upgrades
continue if upgrade.slot != @slot or upgrade == this or upgrade.data?
if upgrade.occupied_by? and upgrade.occupied_by == this
return true
false
toXWS: (upgrade_dict) ->
upgrade_type = switch @type
when 'Upgrade'
exportObj.toXWSUpgrade[@slot] ? @slot.canonicalize()
else
exportObj.toXWSUpgrade[@type] ? @type.canonicalize()
(upgrade_dict[upgrade_type] ?= []).push (@data.xws ? @data.canonical_name)
class exportObj.Upgrade extends GenericAddon
constructor: (args) ->
# args
super args
@slot = args.slot
@type = 'Upgrade'
@dataById = exportObj.upgradesById
@dataByName = exportObj.upgradesByLocalizedName
@serialization_code = 'U'
@setupSelector()
setupSelector: ->
super
width: '50%'
placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'upgradePlaceholder', @slot)
allowClear: true
query: (query) =>
@ship.builder.checkCollection()
query.callback
more: false
results: @ship.builder.getAvailableUpgradesIncluding(@slot, @data, @ship, this, query.term, @filter_func)
#Temporarily removed modifications as they are now upgrades
#class exportObj.Modification extends GenericAddon
# constructor: (args) ->
# super args
# @type = 'Modification'
# @dataById = exportObj.modificationsById
# @dataByName = exportObj.modificationsByLocalizedName
# @serialization_code = 'M'
# @setupSelector()
# setupSelector: ->
# super
# width: '50%'
# placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'modificationPlaceholder')
# allowClear: true
# query: (query) =>
# @ship.builder.checkCollection()
# query.callback
# more: false
# results: @ship.builder.getAvailableModificationsIncluding(@data, @ship, query.term, @filter_func)
class exportObj.Title extends GenericAddon
constructor: (args) ->
super args
@type = 'Title'
@dataById = exportObj.titlesById
@dataByName = exportObj.titlesByLocalizedName
@serialization_code = 'T'
@setupSelector()
setupSelector: ->
super
width: '50%'
placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'titlePlaceholder')
allowClear: true
query: (query) =>
@ship.builder.checkCollection()
query.callback
more: false
results: @ship.builder.getAvailableTitlesIncluding(@ship, @data, query.term)
class exportObj.RestrictedUpgrade extends exportObj.Upgrade
constructor: (args) ->
@filter_func = args.filter_func
super args
@serialization_code = 'u'
if args.auto_equip?
@setById args.auto_equip
#class exportObj.RestrictedModification extends exportObj.Modification
# constructor: (args) ->
# @filter_func = args.filter_func
# super args
# @serialization_code = 'm'
# if args.auto_equip?
# @setById args.auto_equip
SERIALIZATION_CODE_TO_CLASS =
'M': exportObj.Modification
'T': exportObj.Title
'U': exportObj.Upgrade
'u': exportObj.RestrictedUpgrade
'm': exportObj.RestrictedModification
| 201517 | ###
X-Wing Squad Builder
<NAME> <<EMAIL>>
https://github.com/geordanr/xwing
###
exportObj = exports ? this
exportObj.sortHelper = (a, b) ->
if a.points == b.points
a_name = a.text.replace(/[^a-z0-9]/ig, '')
b_name = b.text.replace(/[^a-z0-9]/ig, '')
if a_name == b_name
0
else
if a_name > b_name then 1 else -1
else
if a.points > b.points then 1 else -1
$.isMobile = ->
navigator.userAgent.match /(iPhone|iPod|iPad|Android)/i
$.randomInt = (n) ->
Math.floor(Math.random() * n)
# ripped from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
$.getParameterByName = (name) ->
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
regexS = "[\\?&]" + name + "=([^&#]*)"
regex = new RegExp(regexS)
results = regex.exec(window.location.search)
if results == null
return ""
else
return decodeURIComponent(results[1].replace(/\+/g, " "))
Array::intersects = (other) ->
for item in this
if item in other
return true
return false
Array::removeItem = (item) ->
idx = @indexOf item
@splice(idx, 1) unless idx == -1
this
String::capitalize = ->
@charAt(0).toUpperCase() + @slice(1)
String::getXWSBaseName = ->
@split('-')[0]
URL_BASE = "#{window.location.protocol}//#{window.location.host}#{window.location.pathname}"
SQUAD_DISPLAY_NAME_MAX_LENGTH = 24
statAndEffectiveStat = (base_stat, effective_stats, key) ->
"""#{base_stat}#{if effective_stats[key] != base_stat then " (#{effective_stats[key]})" else ""}"""
getPrimaryFaction = (faction) ->
switch faction
when 'Rebel Alliance'
'Rebel Alliance'
when 'Galactic Empire'
'Galactic Empire'
else
faction
conditionToHTML = (condition) ->
html = $.trim """
<div class="condition">
<div class="name">#{if condition.unique then "· " else ""}#{condition.name}</div>
<div class="text">#{condition.text}</div>
</div>
"""
# Assumes cards.js will be loaded
class exportObj.SquadBuilder
constructor: (args) ->
# args
@container = $ args.container
@faction = $.trim args.faction
@printable_container = $ args.printable_container
@tab = $ args.tab
# internal state
@ships = []
@uniques_in_use =
Pilot:
[]
Upgrade:
[]
Modification:
[]
Title:
[]
@suppress_automatic_new_ship = false
@tooltip_currently_displaying = null
@randomizer_options =
sources: null
points: 100
@total_points = 0
@isCustom = false
@isEpic = false
@maxEpicPointsAllowed = 0
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
@backend = null
@current_squad = {}
@language = 'English'
@collection = null
@current_obstacles = []
@setupUI()
@setupEventHandlers()
window.setInterval @updatePermaLink, 250
@isUpdatingPoints = false
if $.getParameterByName('f') == @faction
@resetCurrentSquad(true)
@loadFromSerialized $.getParameterByName('d')
else
@resetCurrentSquad()
@addShip()
resetCurrentSquad: (initial_load=false) ->
default_squad_name = 'Unnamed Squadron'
squad_name = $.trim(@squad_name_input.val()) or default_squad_name
if initial_load and $.trim $.getParameterByName('sn')
squad_name = $.trim $.getParameterByName('sn')
squad_obstacles = []
if initial_load and $.trim $.getParameterByName('obs')
squad_obstacles = ($.trim $.getParameterByName('obs')).split(",").slice(0, 3)
@current_obstacles = squad_obstacles
else if @current_obstacles
squad_obstacles = @current_obstacles
@current_squad =
id: null
name: squad_name
dirty: false
additional_data:
points: @total_points
description: ''
cards: []
notes: ''
obstacles: squad_obstacles
faction: @faction
if @total_points > 0
if squad_name == default_squad_name
@current_squad.name = 'Unsaved Squadron'
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadNameChanged'
@container.trigger 'xwing-backend:squadDirtinessChanged'
newSquadFromScratch: ->
@squad_name_input.val '<NAME> Squadron'
@removeAllShips()
@addShip()
@current_obstacles = []
@resetCurrentSquad()
@notes.val ''
setupUI: ->
DEFAULT_RANDOMIZER_POINTS = 100
DEFAULT_RANDOMIZER_TIMEOUT_SEC = 2
DEFAULT_RANDOMIZER_ITERATIONS = 1000
@status_container = $ document.createElement 'DIV'
@status_container.addClass 'container-fluid'
@status_container.append $.trim '''
<div class="row-fluid">
<div class="span3 squad-name-container">
<div class="display-name">
<span class="squad-name"></span>
<i class="fa fa-pencil"></i>
</div>
<div class="input-append">
<input type="text" maxlength="64" placeholder="Name your squad..." />
<button class="btn save"><i class="fa fa-pencil-square-o"></i></button>
</div>
</div>
<div class="span4 points-display-container">
Points: <span class="total-points">0</span> / <input type="number" class="desired-points" value="100">
<select class="game-type-selector">
<option value="standard">Standard</option>
<option value="custom">Custom</option>
</select>
<span class="points-remaining-container">(<span class="points-remaining"></span> left)</span>
<span class="total-epic-points-container hidden"><br /><span class="total-epic-points">0</span> / <span class="max-epic-points">5</span> Epic Points</span>
<span class="content-warning unreleased-content-used hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning epic-content-used hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning illegal-epic-upgrades hidden"><br /><i class="fa fa-exclamation-circle"></i> Navigator cannot be equipped onto Huge ships in Epic tournament play!</span>
<span class="content-warning illegal-epic-too-many-small-ships hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning illegal-epic-too-many-large-ships hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning collection-invalid hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
</div>
<div class="span5 pull-right button-container">
<div class="btn-group pull-right">
<button class="btn btn-primary view-as-text"><span class="hidden-phone"><i class="fa fa-print"></i> Print/View as </span>Text</button>
<!-- <button class="btn btn-primary print-list hidden-phone hidden-tablet"><i class="fa fa-print"></i> Print</button> -->
<a class="btn btn-primary hidden collection"><i class="fa fa-folder-open hidden-phone hidden-tabler"></i> Your Collection</a>
<!--
<button class="btn btn-primary randomize" ><i class="fa fa-random hidden-phone hidden-tablet"></i> Random!</button>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a class="randomize-options">Randomizer Options...</a></li>
</ul>
-->
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<button class="show-authenticated btn btn-primary save-list"><i class="fa fa-floppy-o"></i> Save</button>
<button class="show-authenticated btn btn-primary save-list-as"><i class="fa fa-files-o"></i> Save As...</button>
<button class="show-authenticated btn btn-primary delete-list disabled"><i class="fa fa-trash-o"></i> Delete</button>
<button class="show-authenticated btn btn-primary backend-list-my-squads show-authenticated">Load Squad</button>
<button class="btn btn-danger clear-squad">New Squad</button>
<span class="show-authenticated backend-status"></span>
</div>
</div>
'''
@container.append @status_container
@list_modal = $ document.createElement 'DIV'
@list_modal.addClass 'modal hide fade text-list-modal'
@container.append @list_modal
@list_modal.append $.trim """
<div class="modal-header">
<button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">×</button>
<div class="hidden-phone hidden-print">
<h3><span class="squad-name"></span> (<span class="total-points"></span>)<h3>
</div>
<div class="visible-phone hidden-print">
<h4><span class="squad-name"></span> (<span class="total-points"></span>)<h4>
</div>
<div class="visible-print">
<div class="fancy-header">
<div class="squad-name"></div>
<div class="squad-faction"></div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle">
<span class="total-points"></span>
</div>
</div>
</div>
</div>
<div class="fancy-under-header"></div>
</div>
</div>
<div class="modal-body">
<div class="fancy-list hidden-phone"></div>
<div class="simple-list"></div>
<div class="bbcode-list">
<p>Copy the BBCode below and paste it into your forum post.</p>
<textarea></textarea><button class="btn btn-copy">Copy</button>
</div>
<div class="html-list">
<textarea></textarea><button class="btn btn-copy">Copy</button>
</div>
</div>
<div class="modal-footer hidden-print">
<label class="vertical-space-checkbox">
Add space for damage/upgrade cards when printing <input type="checkbox" class="toggle-vertical-space" />
</label>
<label class="color-print-checkbox">
Print color <input type="checkbox" class="toggle-color-print" />
</label>
<label class="qrcode-checkbox hidden-phone">
Include QR codes <input type="checkbox" class="toggle-juggler-qrcode" checked="checked" />
</label>
<label class="qrcode-checkbox hidden-phone">
Include obstacle/damage deck choices <input type="checkbox" class="toggle-obstacles" />
</label>
<div class="btn-group list-display-mode">
<button class="btn select-simple-view">Simple</button>
<button class="btn select-fancy-view hidden-phone">Fancy</button>
<button class="btn select-bbcode-view">BBCode</button>
<button class="btn select-html-view">HTML</button>
</div>
<button class="btn print-list hidden-phone"><i class="fa fa-print"></i> Print</button>
<button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@fancy_container = $ @list_modal.find('div.modal-body .fancy-list')
@fancy_total_points_container = $ @list_modal.find('div.modal-header .total-points')
@simple_container = $ @list_modal.find('div.modal-body .simple-list')
@bbcode_container = $ @list_modal.find('div.modal-body .bbcode-list')
@bbcode_textarea = $ @bbcode_container.find('textarea')
@bbcode_textarea.attr 'readonly', 'readonly'
@htmlview_container = $ @list_modal.find('div.modal-body .html-list')
@html_textarea = $ @htmlview_container.find('textarea')
@html_textarea.attr 'readonly', 'readonly'
@toggle_vertical_space_container = $ @list_modal.find('.vertical-space-checkbox')
@toggle_color_print_container = $ @list_modal.find('.color-print-checkbox')
@list_modal.on 'click', 'button.btn-copy', (e) =>
@self = $(e.currentTarget)
@self.siblings('textarea').select()
@success = document.execCommand('copy')
if @success
@self.addClass 'btn-success'
setTimeout ( =>
@self.removeClass 'btn-success'
), 1000
@select_simple_view_button = $ @list_modal.find('.select-simple-view')
@select_simple_view_button.click (e) =>
@select_simple_view_button.blur()
unless @list_display_mode == 'simple'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_simple_view_button.addClass 'btn-inverse'
@list_display_mode = 'simple'
@simple_container.show()
@fancy_container.hide()
@bbcode_container.hide()
@htmlview_container.hide()
@toggle_vertical_space_container.hide()
@toggle_color_print_container.hide()
@select_fancy_view_button = $ @list_modal.find('.select-fancy-view')
@select_fancy_view_button.click (e) =>
@select_fancy_view_button.blur()
unless @list_display_mode == 'fancy'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_fancy_view_button.addClass 'btn-inverse'
@list_display_mode = 'fancy'
@fancy_container.show()
@simple_container.hide()
@bbcode_container.hide()
@htmlview_container.hide()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
@select_bbcode_view_button = $ @list_modal.find('.select-bbcode-view')
@select_bbcode_view_button.click (e) =>
@select_bbcode_view_button.blur()
unless @list_display_mode == 'bbcode'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_bbcode_view_button.addClass 'btn-inverse'
@list_display_mode = 'bbcode'
@bbcode_container.show()
@htmlview_container.hide()
@simple_container.hide()
@fancy_container.hide()
@bbcode_textarea.select()
@bbcode_textarea.focus()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
@select_html_view_button = $ @list_modal.find('.select-html-view')
@select_html_view_button.click (e) =>
@select_html_view_button.blur()
unless @list_display_mode == 'html'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_html_view_button.addClass 'btn-inverse'
@list_display_mode = 'html'
@bbcode_container.hide()
@htmlview_container.show()
@simple_container.hide()
@fancy_container.hide()
@html_textarea.select()
@html_textarea.focus()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
if $(window).width() >= 768
@simple_container.hide()
@select_fancy_view_button.click()
else
@select_simple_view_button.click()
@clear_squad_button = $ @status_container.find('.clear-squad')
@clear_squad_button.click (e) =>
if @current_squad.dirty and @backend?
@backend.warnUnsaved this, () =>
@newSquadFromScratch()
else
@newSquadFromScratch()
@squad_name_container = $ @status_container.find('div.squad-name-container')
@squad_name_display = $ @container.find('.display-name')
@squad_name_placeholder = $ @container.find('.squad-name')
@squad_name_input = $ @squad_name_container.find('input')
@squad_name_save_button = $ @squad_name_container.find('button.save')
@squad_name_input.closest('div').hide()
@points_container = $ @status_container.find('div.points-display-container')
@total_points_span = $ @points_container.find('.total-points')
@game_type_selector = $ @status_container.find('.game-type-selector')
@game_type_selector.change (e) =>
@onGameTypeChanged @game_type_selector.val()
@desired_points_input = $ @points_container.find('.desired-points')
@desired_points_input.change (e) =>
@game_type_selector.val 'custom'
@onGameTypeChanged 'custom'
@points_remaining_span = $ @points_container.find('.points-remaining')
@points_remaining_container = $ @points_container.find('.points-remaining-container')
@unreleased_content_used_container = $ @points_container.find('.unreleased-content-used')
@epic_content_used_container = $ @points_container.find('.epic-content-used')
@illegal_epic_upgrades_container = $ @points_container.find('.illegal-epic-upgrades')
@too_many_small_ships_container = $ @points_container.find('.illegal-epic-too-many-small-ships')
@too_many_large_ships_container = $ @points_container.find('.illegal-epic-too-many-large-ships')
@collection_invalid_container = $ @points_container.find('.collection-invalid')
@total_epic_points_container = $ @points_container.find('.total-epic-points-container')
@total_epic_points_span = $ @total_epic_points_container.find('.total-epic-points')
@max_epic_points_span = $ @points_container.find('.max-epic-points')
@view_list_button = $ @status_container.find('div.button-container button.view-as-text')
@randomize_button = $ @status_container.find('div.button-container button.randomize')
@customize_randomizer = $ @status_container.find('div.button-container a.randomize-options')
@backend_status = $ @status_container.find('.backend-status')
@backend_status.hide()
@collection_button = $ @status_container.find('div.button-container a.collection')
@collection_button.click (e) =>
e.preventDefault()
unless @collection_button.prop('disabled')
@collection.modal.modal 'show'
@squad_name_input.keypress (e) =>
if e.which == 13
@squad_name_save_button.click()
false
@squad_name_input.change (e) =>
@backend_status.fadeOut 'slow'
@squad_name_input.blur (e) =>
@squad_name_input.change()
@squad_name_save_button.click()
@squad_name_display.click (e) =>
e.preventDefault()
@squad_name_display.hide()
@squad_name_input.val $.trim(@current_squad.name)
# Because Firefox handles this badly
window.setTimeout () =>
@squad_name_input.focus()
@squad_name_input.select()
, 100
@squad_name_input.closest('div').show()
@squad_name_save_button.click (e) =>
e.preventDefault()
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
name = @current_squad.name = $.trim(@squad_name_input.val())
if name.length > 0
@squad_name_display.show()
@container.trigger 'xwing-backend:squadNameChanged'
@squad_name_input.closest('div').hide()
@randomizer_options_modal = $ document.createElement('DIV')
@randomizer_options_modal.addClass 'modal hide fade'
$('body').append @randomizer_options_modal
@randomizer_options_modal.append $.trim """
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Random Squad Builder Options</h3>
</div>
<div class="modal-body">
<form>
<label>
Desired Points
<input type="number" class="randomizer-points" value="#{DEFAULT_RANDOMIZER_POINTS}" placeholder="#{DEFAULT_RANDOMIZER_POINTS}" />
</label>
<label>
Sets and Expansions (default all)
<select class="randomizer-sources" multiple="1" data-placeholder="Use all sets and expansions">
</select>
</label>
<label>
Maximum Seconds to Spend Randomizing
<input type="number" class="randomizer-timeout" value="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" placeholder="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" />
</label>
<label>
Maximum Randomization Iterations
<input type="number" class="randomizer-iterations" value="#{DEFAULT_RANDOMIZER_ITERATIONS}" placeholder="#{DEFAULT_RANDOMIZER_ITERATIONS}" />
</label>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary do-randomize" aria-hidden="true">Randomize!</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@randomizer_source_selector = $ @randomizer_options_modal.find('select.randomizer-sources')
for expansion in exportObj.expansions
opt = $ document.createElement('OPTION')
opt.text expansion
@randomizer_source_selector.append opt
@randomizer_source_selector.select2
width: "100%"
minimumResultsForSearch: if $.isMobile() then -1 else 0
@randomize_button.click (e) =>
e.preventDefault()
if @current_squad.dirty and @backend?
@backend.warnUnsaved this, () =>
@randomize_button.click()
else
points = parseInt $(@randomizer_options_modal.find('.randomizer-points')).val()
points = DEFAULT_RANDOMIZER_POINTS if (isNaN(points) or points <= 0)
timeout_sec = parseInt $(@randomizer_options_modal.find('.randomizer-timeout')).val()
timeout_sec = DEFAULT_RANDOMIZER_TIMEOUT_SEC if (isNaN(timeout_sec) or timeout_sec <= 0)
iterations = parseInt $(@randomizer_options_modal.find('.randomizer-iterations')).val()
iterations = DEFAULT_RANDOMIZER_ITERATIONS if (isNaN(iterations) or iterations <= 0)
#console.log "points=#{points}, sources=#{@randomizer_source_selector.val()}, timeout=#{timeout_sec}, iterations=#{iterations}"
@randomSquad(points, @randomizer_source_selector.val(), DEFAULT_RANDOMIZER_TIMEOUT_SEC * 1000, iterations)
@randomizer_options_modal.find('button.do-randomize').click (e) =>
e.preventDefault()
@randomizer_options_modal.modal('hide')
@randomize_button.click()
@customize_randomizer.click (e) =>
e.preventDefault()
@randomizer_options_modal.modal()
@choose_obstacles_modal = $ document.createElement 'DIV'
@choose_obstacles_modal.addClass 'modal hide fade choose-obstacles-modal'
@container.append @choose_obstacles_modal
@choose_obstacles_modal.append $.trim """
<div class="modal-header">
<label class='choose-obstacles-description'>Choose up to three obstacles, to include in the permalink for use in external programs</label>
</div>
<div class="modal-body">
<div class="obstacle-select-container" style="float:left">
<select multiple class='obstacle-select' size="18">
<option class="coreasteroid0-select" value="coreasteroid0">Core Asteroid 0</option>
<option class="coreasteroid1-select" value="coreasteroid1">Core Asteroid 1</option>
<option class="coreasteroid2-select" value="coreasteroid2">Core Asteroid 2</option>
<option class="coreasteroid3-select" value="coreasteroid3">Core Asteroid 3</option>
<option class="coreasteroid4-select" value="coreasteroid4">Core Asteroid 4</option>
<option class="coreasteroid5-select" value="coreasteroid5">Core Asteroid 5</option>
<option class="yt2400debris0-select" value="yt2400debris0">YT2400 Debris 0</option>
<option class="yt2400debris1-select" value="yt2400debris1">YT2400 Debris 1</option>
<option class="yt2400debris2-select" value="yt2400debris2">YT2400 Debris 2</option>
<option class="vt49decimatordebris0-select" value="vt49decimatordebris0">VT49 Debris 0</option>
<option class="vt49decimatordebris1-select" value="vt49decimatordebris1">VT49 Debris 1</option>
<option class="vt49decimatordebris2-select" value="vt49decimatordebris2">VT49 Debris 2</option>
<option class="core2asteroid0-select" value="core2asteroid0">Force Awakens Asteroid 0</option>
<option class="core2asteroid1-select" value="core2asteroid1">Force Awakens Asteroid 1</option>
<option class="core2asteroid2-select" value="core2asteroid2">Force Awakens Asteroid 2</option>
<option class="core2asteroid3-select" value="core2asteroid3">Force Awakens Asteroid 3</option>
<option class="core2asteroid4-select" value="core2asteroid4">Force Awakens Asteroid 4</option>
<option class="core2asteroid5-select" value="core2asteroid5">Force Awakens Asteroid 5</option>
</select>
</div>
<div class="obstacle-image-container" style="display:none;">
<img class="obstacle-image" src="images/core2asteroid0.png" />
</div>
</div>
<div class="modal-footer hidden-print">
<button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@obstacles_select = @choose_obstacles_modal.find('.obstacle-select')
@obstacles_select_image = @choose_obstacles_modal.find('.obstacle-image-container')
# Backend
@backend_list_squads_button = $ @container.find('button.backend-list-my-squads')
@backend_list_squads_button.click (e) =>
e.preventDefault()
if @backend?
@backend.list this
#@backend_list_all_squads_button = $ @container.find('button.backend-list-all-squads')
#@backend_list_all_squads_button.click (e) =>
# e.preventDefault()
# if @backend?
# @backend.list this, true
@backend_save_list_button = $ @container.find('button.save-list')
@backend_save_list_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_save_list_button.hasClass('disabled')
additional_data =
points: @total_points
description: @describeSquad()
cards: @listCards()
notes: @notes.val().substr(0, 1024)
obstacles: @getObstacles()
@backend_status.html $.trim """
<i class="fa fa-refresh fa-spin"></i> Saving squad...
"""
@backend_status.show()
@backend_save_list_button.addClass 'disabled'
await @backend.save @serialize(), @current_squad.id, @current_squad.name, @faction, additional_data, defer(results)
if results.success
@current_squad.dirty = false
if @current_squad.id?
@backend_status.html $.trim """
<i class="fa fa-check"></i> Squad updated successfully.
"""
else
@backend_status.html $.trim """
<i class="fa fa-check"></i> New squad saved successfully.
"""
@current_squad.id = results.id
@container.trigger 'xwing-backend:squadDirtinessChanged'
else
@backend_status.html $.trim """
<i class="fa fa-exclamation-circle"></i> #{results.error}
"""
@backend_save_list_button.removeClass 'disabled'
@backend_save_list_as_button = $ @container.find('button.save-list-as')
@backend_save_list_as_button.addClass 'disabled'
@backend_save_list_as_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_save_list_as_button.hasClass('disabled')
@backend.showSaveAsModal this
@backend_delete_list_button = $ @container.find('button.delete-list')
@backend_delete_list_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_delete_list_button.hasClass('disabled')
@backend.showDeleteModal this
content_container = $ document.createElement 'DIV'
content_container.addClass 'container-fluid'
@container.append content_container
content_container.append $.trim """
<div class="row-fluid">
<div class="span9 ship-container">
<label class="notes-container show-authenticated">
<span>Squad Notes:</span>
<br />
<textarea class="squad-notes"></textarea>
</label>
<span class="obstacles-container">
<button class="btn btn-primary choose-obstacles">Choose Obstacles</button>
</span>
</div>
<div class="span3 info-container" />
</div>
"""
@ship_container = $ content_container.find('div.ship-container')
@info_container = $ content_container.find('div.info-container')
@obstacles_container = content_container.find('.obstacles-container')
@notes_container = $ content_container.find('.notes-container')
@notes = $ @notes_container.find('textarea.squad-notes')
@info_container.append $.trim """
<div class="well well-small info-well">
<span class="info-name"></span>
<br />
<span class="info-sources"></span>
<br />
<span class="info-collection"></span>
<table>
<tbody>
<tr class="info-ship">
<td class="info-header">Ship</td>
<td class="info-data"></td>
</tr>
<tr class="info-skill">
<td class="info-header">Initiative</td>
<td class="info-data info-skill"></td>
</tr>
<tr class="info-energy">
<td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td>
<td class="info-data info-energy"></td>
</tr>
<tr class="info-attack">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-fullfront">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-bullseye">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-back">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-turret">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-doubleturret">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-agility">
<td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td>
<td class="info-data info-agility"></td>
</tr>
<tr class="info-hull">
<td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td>
<td class="info-data info-hull"></td>
</tr>
<tr class="info-shields">
<td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td>
<td class="info-data info-shields"></td>
</tr>
<tr class="info-force">
<td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td>
<td class="info-data info-force"></td>
</tr>
<tr class="info-charge">
<td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td>
<td class="info-data info-charge"></td>
</tr>
<tr class="info-range">
<td class="info-header">Range</td>
<td class="info-data info-range"></td>
</tr>
<tr class="info-actions">
<td class="info-header">Actions</td>
<td class="info-data"></td>
</tr>
<tr class="info-actions-red">
<td></td>
<td class="info-data-red"></td>
</tr>
<tr class="info-upgrades">
<td class="info-header">Upgrades</td>
<td class="info-data"></td>
</tr>
</tbody>
</table>
<p class="info-text" />
<p class="info-maneuvers" />
</div>
"""
@info_container.hide()
@print_list_button = $ @container.find('button.print-list')
@container.find('[rel=tooltip]').tooltip()
# obstacles
@obstacles_button = $ @container.find('button.choose-obstacles')
@obstacles_button.click (e) =>
e.preventDefault()
@showChooseObstaclesModal()
# conditions
@condition_container = $ document.createElement('div')
@condition_container.addClass 'conditions-container'
@container.append @condition_container
setupEventHandlers: ->
@container.on 'xwing:claimUnique', (e, unique, type, cb) =>
@claimUnique unique, type, cb
.on 'xwing:releaseUnique', (e, unique, type, cb) =>
@releaseUnique unique, type, cb
.on 'xwing:pointsUpdated', (e, cb=$.noop) =>
if @isUpdatingPoints
cb()
else
@isUpdatingPoints = true
@onPointsUpdated () =>
@isUpdatingPoints = false
cb()
.on 'xwing-backend:squadLoadRequested', (e, squad) =>
@onSquadLoadRequested squad
.on 'xwing-backend:squadDirtinessChanged', (e) =>
@onSquadDirtinessChanged()
.on 'xwing-backend:squadNameChanged', (e) =>
@onSquadNameChanged()
.on 'xwing:beforeLanguageLoad', (e, cb=$.noop) =>
@pretranslation_serialized = @serialize()
# Need to remove ships here because the cards will change when the
# new language is loaded, and we don't want to have problems with
# unclaiming uniques.
# Preserve squad dirtiness
old_dirty = @current_squad.dirty
@removeAllShips()
@current_squad.dirty = old_dirty
cb()
.on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) =>
@language = language
old_dirty = @current_squad.dirty
@loadFromSerialized @pretranslation_serialized
for ship in @ships
ship.updateSelections()
@current_squad.dirty = old_dirty
@pretranslation_serialized = undefined
cb()
# Recently moved this here. Did this ever work?
.on 'xwing:shipUpdated', (e, cb=$.noop) =>
all_allocated = true
for ship in @ships
ship.updateSelections()
if ship.ship_selector.val() == ''
all_allocated = false
#console.log "all_allocated is #{all_allocated}, suppress_automatic_new_ship is #{@suppress_automatic_new_ship}"
#console.log "should we add ship: #{all_allocated and not @suppress_automatic_new_ship}"
@addShip() if all_allocated and not @suppress_automatic_new_ship
$(window).on 'xwing-backend:authenticationChanged', (e) =>
@resetCurrentSquad()
.on 'xwing-collection:created', (e, collection) =>
# console.log "#{@faction}: collection was created"
@collection = collection
# console.log "#{@faction}: Collection created, checking squad"
@collection.onLanguageChange null, @language
@checkCollection()
@collection_button.removeClass 'hidden'
.on 'xwing-collection:changed', (e, collection) =>
# console.log "#{@faction}: Collection changed, checking squad"
@checkCollection()
.on 'xwing-collection:destroyed', (e, collection) =>
@collection = null
@collection_button.addClass 'hidden'
.on 'xwing:pingActiveBuilder', (e, cb) =>
cb(this) if @container.is(':visible')
.on 'xwing:activateBuilder', (e, faction, cb) =>
if faction == @faction
@tab.tab('show')
cb this
@obstacles_select.change (e) =>
if @obstacles_select.val().length > 3
@obstacles_select.val(@current_squad.additional_data.obstacles)
else
previous_obstacles = @current_squad.additional_data.obstacles
@current_obstacles = (o for o in @obstacles_select.val())
if (previous_obstacles?)
new_selection = @current_obstacles.filter((element) => return previous_obstacles.indexOf(element) == -1)
else
new_selection = @current_obstacles
if new_selection.length > 0
@showChooseObstaclesSelectImage(new_selection[0])
@current_squad.additional_data.obstacles = @current_obstacles
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
@view_list_button.click (e) =>
e.preventDefault()
@showTextListModal()
@print_list_button.click (e) =>
e.preventDefault()
# Copy text list to printable
@printable_container.find('.printable-header').html @list_modal.find('.modal-header').html()
@printable_container.find('.printable-body').text ''
switch @list_display_mode
when 'simple'
@printable_container.find('.printable-body').html @simple_container.html()
else
for ship in @ships
@printable_container.find('.printable-body').append ship.toHTML() if ship.pilot?
@printable_container.find('.fancy-ship').toggleClass 'tall', @list_modal.find('.toggle-vertical-space').prop('checked')
@printable_container.find('.printable-body').toggleClass 'bw', not @list_modal.find('.toggle-color-print').prop('checked')
faction = switch @faction
when 'Rebel Alliance'
'rebel'
when 'Galactic Empire'
'empire'
when 'Scum and Villainy'
'scum'
@printable_container.find('.squad-faction').html """<i class="xwing-miniatures-font xwing-miniatures-font-#{faction}"></i>"""
# Conditions
@printable_container.find('.printable-body').append $.trim """
<div class="print-conditions"></div>
"""
@printable_container.find('.printable-body .print-conditions').html @condition_container.html()
# Notes, if present
if $.trim(@notes.val()) != ''
@printable_container.find('.printable-body').append $.trim """
<h5 class="print-notes">Notes:</h5>
<pre class="print-notes"></pre>
"""
@printable_container.find('.printable-body pre.print-notes').text @notes.val()
# Obstacles
if @list_modal.find('.toggle-obstacles').prop('checked')
@printable_container.find('.printable-body').append $.trim """
<div class="obstacles">
<div>Mark the three obstacles you are using.</div>
<img class="obstacle-silhouettes" src="images/xws-obstacles.png" />
<div>Mark which damage deck you are using.</div>
<div><i class="fa fa-square-o"></i>Original Core Set   <i class="fa fa-square-o"></i>The Force Awakens Core Set</div>
</div>
"""
# Add List Juggler QR code
query = @getPermaLinkParams(['sn', 'obs'])
if query? and @list_modal.find('.toggle-juggler-qrcode').prop('checked')
@printable_container.find('.printable-body').append $.trim """
<div class="qrcode-container">
<div class="permalink-container">
<div class="qrcode"></div>
<div class="qrcode-text">Scan to open this list in the builder</div>
</div>
<div class="juggler-container">
<div class="qrcode"></div>
<div class="qrcode-text">TOs: Scan to load this squad into List Juggler</div>
</div>
</div>
"""
text = "https://yasb-xws.herokuapp.com/juggler#{query}"
@printable_container.find('.juggler-container .qrcode').qrcode
render: 'div'
ec: 'M'
size: if text.length < 144 then 144 else 160
text: text
text = "https://geordanr.github.io/xwing/#{query}"
@printable_container.find('.permalink-container .qrcode').qrcode
render: 'div'
ec: 'M'
size: if text.length < 144 then 144 else 160
text: text
window.print()
$(window).resize =>
@select_simple_view_button.click() if $(window).width() < 768 and @list_display_mode != 'simple'
@notes.change @onNotesUpdated
@notes.on 'keyup', @onNotesUpdated
getPermaLinkParams: (ignored_params=[]) =>
params = {}
params.f = encodeURI(@faction) unless 'f' in ignored_params
params.d = encodeURI(@serialize()) unless 'd' in ignored_params
params.sn = encodeURIComponent(@current_squad.name) unless 'sn' in ignored_params
params.obs = encodeURI(@current_squad.additional_data.obstacles || '') unless 'obs' in ignored_params
return "?" + ("#{k}=#{v}" for k, v of params).join("&")
getPermaLink: (params=@getPermaLinkParams()) => "#{URL_BASE}#{params}"
updatePermaLink: () =>
return unless @container.is(':visible') # gross but couldn't make clearInterval work
next_params = @getPermaLinkParams()
if window.location.search != next_params
window.history.replaceState(next_params, '', @getPermaLink(next_params))
onNotesUpdated: =>
if @total_points > 0
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
onGameTypeChanged: (gametype, cb=$.noop) =>
switch gametype
when 'standard'
@isEpic = false
@isCustom = false
@desired_points_input.val 200
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
when 'custom'
@isEpic = false
@isCustom = true
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
@max_epic_points_span.text @maxEpicPointsAllowed
@onPointsUpdated cb
onPointsUpdated: (cb=$.noop) =>
@total_points = 0
@total_epic_points = 0
unreleased_content_used = false
epic_content_used = false
for ship, i in @ships
ship.validate()
@total_points += ship.getPoints()
@total_epic_points += ship.getEpicPoints()
ship_uses_unreleased_content = ship.checkUnreleasedContent()
unreleased_content_used = ship_uses_unreleased_content if ship_uses_unreleased_content
ship_uses_epic_content = ship.checkEpicContent()
epic_content_used = ship_uses_epic_content if ship_uses_epic_content
@total_points_span.text @total_points
points_left = parseInt(@desired_points_input.val()) - @total_points
@points_remaining_span.text points_left
@points_remaining_container.toggleClass 'red', (points_left < 0)
@unreleased_content_used_container.toggleClass 'hidden', not unreleased_content_used
@epic_content_used_container.toggleClass 'hidden', (@isEpic or not epic_content_used)
# Check against Epic restrictions if applicable
@illegal_epic_upgrades_container.toggleClass 'hidden', true
@too_many_small_ships_container.toggleClass 'hidden', true
@too_many_large_ships_container.toggleClass 'hidden', true
@total_epic_points_container.toggleClass 'hidden', true
if @isEpic
@total_epic_points_container.toggleClass 'hidden', false
@total_epic_points_span.text @total_epic_points
@total_epic_points_span.toggleClass 'red', (@total_epic_points > @maxEpicPointsAllowed)
shipCountsByType = {}
illegal_for_epic = false
for ship, i in @ships
if ship?.data?
shipCountsByType[ship.data.name] ?= 0
shipCountsByType[ship.data.name] += 1
if ship.data.huge?
for upgrade in ship.upgrades
if upgrade?.data?.epic_restriction_func?
unless upgrade.data.epic_restriction_func(ship.data, upgrade)
illegal_for_epic = true
break
break if illegal_for_epic
@illegal_epic_upgrades_container.toggleClass 'hidden', not illegal_for_epic
if @maxLargeShipsOfOneType? and @maxSmallShipsOfOneType?
for ship_name, count of shipCountsByType
ship_data = exportObj.ships[ship_name]
if ship_data.large? and count > @maxLargeShipsOfOneType
@too_many_large_ships_container.toggleClass 'hidden', false
else if not ship.huge? and count > @maxSmallShipsOfOneType
@too_many_small_ships_container.toggleClass 'hidden', false
@fancy_total_points_container.text @total_points
# update text list
@fancy_container.text ''
@simple_container.html '<table class="simple-table"></table>'
bbcode_ships = []
htmlview_ships = []
for ship in @ships
if ship.pilot?
@fancy_container.append ship.toHTML()
@simple_container.find('table').append ship.toTableRow()
bbcode_ships.push ship.toBBCode()
htmlview_ships.push ship.toSimpleHTML()
@htmlview_container.find('textarea').val $.trim """#{htmlview_ships.join '<br />'}
<br />
<b><i>Total: #{@total_points}</i></b>
<br />
<a href="#{@getPermaLink()}">View in Yet Another Squad Builder</a>
"""
@bbcode_container.find('textarea').val $.trim """#{bbcode_ships.join "\n\n"}
[b][i]Total: #{@total_points}[/i][/b]
[url=#{@getPermaLink()}]View in Yet Another Squad Builder[/url]
"""
# console.log "#{@faction}: Squad updated, checking collection"
@checkCollection()
# update conditions used
# this old version of phantomjs i'm using doesn't support Set
if Set?
conditions_set = new Set()
for ship in @ships
# shouldn't there be a set union
ship.getConditions().forEach (condition) ->
conditions_set.add(condition)
conditions = []
conditions_set.forEach (condition) ->
conditions.push(condition)
conditions.sort (a, b) ->
if a.name.canonicalize() < b.name.canonicalize()
-1
else if b.name.canonicalize() > a.name.canonicalize()
1
else
0
@condition_container.text ''
conditions.forEach (condition) =>
@condition_container.append conditionToHTML(condition)
cb @total_points
onSquadLoadRequested: (squad) =>
console.log(squad.additional_data.obstacles)
@current_squad = squad
@backend_delete_list_button.removeClass 'disabled'
@squad_name_input.val @current_squad.name
@squad_name_placeholder.text @current_squad.name
@current_obstacles = @current_squad.additional_data.obstacles
@updateObstacleSelect(@current_squad.additional_data.obstacles)
@loadFromSerialized squad.serialized
@notes.val(squad.additional_data.notes ? '')
@backend_status.fadeOut 'slow'
@current_squad.dirty = false
@container.trigger 'xwing-backend:squadDirtinessChanged'
onSquadDirtinessChanged: () =>
@backend_save_list_button.toggleClass 'disabled', not (@current_squad.dirty and @total_points > 0)
@backend_save_list_as_button.toggleClass 'disabled', @total_points == 0
@backend_delete_list_button.toggleClass 'disabled', not @current_squad.id?
onSquadNameChanged: () =>
if @current_squad.name.length > SQUAD_DISPLAY_NAME_MAX_LENGTH
short_name = "#{@current_squad.name.substr(0, SQUAD_DISPLAY_NAME_MAX_LENGTH)}…"
else
short_name = @current_squad.name
@squad_name_placeholder.text ''
@squad_name_placeholder.append short_name
@squad_name_input.val @current_squad.name
removeAllShips: ->
while @ships.length > 0
@removeShip @ships[0]
throw new Error("Ships not emptied") if @ships.length > 0
showTextListModal: ->
# Display modal
@list_modal.modal 'show'
showChooseObstaclesModal: ->
@obstacles_select.val(@current_squad.additional_data.obstacles)
@choose_obstacles_modal.modal 'show'
showChooseObstaclesSelectImage: (obstacle) ->
@image_name = 'images/' + obstacle + '.png'
@obstacles_select_image.find('.obstacle-image').attr 'src', @image_name
@obstacles_select_image.show()
updateObstacleSelect: (obstacles) ->
@current_obstacles = obstacles
@obstacles_select.val(obstacles)
serialize: ->
#( "#{ship.pilot.id}:#{ship.upgrades[i].data?.id ? -1 for slot, i in ship.pilot.slots}:#{ship.title?.data?.id ? -1}:#{upgrade.data?.id ? -1 for upgrade in ship.title?.conferredUpgrades ? []}:#{ship.modification?.data?.id ? -1}" for ship in @ships when ship.pilot? ).join ';'
serialization_version = 4
game_type_abbrev = switch @game_type_selector.val()
when 'standard'
's'
when 'custom'
"c=#{$.trim @desired_points_input.val()}"
"""v#{serialization_version}!#{game_type_abbrev}!#{( ship.toSerialized() for ship in @ships when ship.pilot? ).join ';'}"""
loadFromSerialized: (serialized) ->
@suppress_automatic_new_ship = true
# Clear all existing ships
@removeAllShips()
re = /^v(\d+)!(.*)/
matches = re.exec serialized
if matches?
# versioned
version = parseInt matches[1]
switch version
when 3, 4
# parse out game type
[ game_type_abbrev, serialized_ships ] = matches[2].split('!')
switch game_type_abbrev
when 's'
@game_type_selector.val 'standard'
@game_type_selector.change()
else
@game_type_selector.val 'custom'
@desired_points_input.val parseInt(game_type_abbrev.split('=')[1])
@desired_points_input.change()
for serialized_ship in serialized_ships.split(';')
unless serialized_ship == ''
new_ship = @addShip()
new_ship.fromSerialized version, serialized_ship
when 2
for serialized_ship in matches[2].split(';')
unless serialized_ship == ''
new_ship = @addShip()
new_ship.fromSerialized version, serialized_ship
else
# v1 (unversioned)
for serialized_ship in serialized.split(';')
unless serialized == ''
new_ship = @addShip()
new_ship.fromSerialized 1, serialized_ship
@suppress_automatic_new_ship = false
# Finally, the unassigned ship
@addShip()
uniqueIndex: (unique, type) ->
if type not of @uniques_in_use
throw new Error("Invalid unique type '#{type}'")
@uniques_in_use[type].indexOf unique
claimUnique: (unique, type, cb) =>
if @uniqueIndex(unique, type) < 0
# Claim pilots with the same canonical name
for other in (exportObj.pilotsByUniqueName[unique.canonical_name.getXWSBaseName()] or [])
if unique != other
if @uniqueIndex(other, 'Pilot') < 0
# console.log "Also claiming unique pilot #{other.canonical_name} in use"
@uniques_in_use['Pilot'].push other
else
throw new Error("Unique #{type} '#{unique.name}' already claimed as pilot")
# Claim other upgrades with the same canonical name
for otherslot, bycanonical of exportObj.upgradesBySlotUniqueName
for canonical, other of bycanonical
if canonical.getXWSBaseName() == unique.canonical_name.getXWSBaseName() and unique != other
if @uniqueIndex(other, 'Upgrade') < 0
# console.log "Also claiming unique #{other.canonical_name} (#{otherslot}) in use"
@uniques_in_use['Upgrade'].push other
# else
# throw new Error("Unique #{type} '#{unique.name}' already claimed as #{otherslot}")
@uniques_in_use[type].push unique
else
throw new Error("Unique #{type} '#{unique.name}' already claimed")
cb()
releaseUnique: (unique, type, cb) =>
idx = @uniqueIndex(unique, type)
if idx >= 0
# Release all uniques with the same canonical name and base name
for type, uniques of @uniques_in_use
# Removing stuff in a loop sucks, so we'll construct a new list
@uniques_in_use[type] = []
for u in uniques
if u.canonical_name.getXWSBaseName() != unique.canonical_name.getXWSBaseName()
# Keep this one
@uniques_in_use[type].push u
# else
# console.log "Releasing #{u.name} (#{type}) with canonical name #{unique.canonical_name}"
else
throw new Error("Unique #{type} '#{unique.name}' not in use")
cb()
addShip: ->
new_ship = new Ship
builder: this
container: @ship_container
@ships.push new_ship
new_ship
removeShip: (ship) ->
await ship.destroy defer()
await @container.trigger 'xwing:pointsUpdated', defer()
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
matcher: (item, term) ->
item.toUpperCase().indexOf(term.toUpperCase()) >= 0
isOurFaction: (faction) ->
if faction instanceof Array
for f in faction
if getPrimaryFaction(f) == @faction
return true
false
else
getPrimaryFaction(faction) == @faction
getAvailableShipsMatching: (term='') ->
ships = []
for ship_name, ship_data of exportObj.ships
if @isOurFaction(ship_data.factions) and @matcher(ship_data.name, term)
if not ship_data.huge or (@isEpic or @isCustom)
ships.push
id: ship_data.name
text: ship_data.name
english_name: ship_data.english_name
canonical_name: ship_data.canonical_name
ships.sort exportObj.sortHelper
getAvailablePilotsForShipIncluding: (ship, include_pilot, term='') ->
# Returns data formatted for Select2
available_faction_pilots = (pilot for pilot_name, pilot of exportObj.pilotsByLocalizedName when (not ship? or pilot.ship == ship) and @isOurFaction(pilot.faction) and @matcher(pilot_name, term))
eligible_faction_pilots = (pilot for pilot_name, pilot of available_faction_pilots when (not pilot.unique? or pilot not in @uniques_in_use['Pilot'] or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()))
# Re-add selected pilot
if include_pilot? and include_pilot.unique? and @matcher(include_pilot.name, term)
eligible_faction_pilots.push include_pilot
({ id: pilot.id, text: "#{pilot.name} (#{pilot.points})", points: pilot.points, ship: pilot.ship, english_name: pilot.english_name, disabled: pilot not in eligible_faction_pilots } for pilot in available_faction_pilots).sort exportObj.sortHelper
dfl_filter_func = ->
true
countUpgrades: (canonical_name) ->
# returns number of upgrades with given canonical name equipped
count = 0
for ship in @ships
for upgrade in ship.upgrades
if upgrade?.data?.canonical_name == canonical_name
count++
count
getAvailableUpgradesIncluding: (slot, include_upgrade, ship, this_upgrade_obj, term='', filter_func=@dfl_filter_func) ->
# Returns data formatted for Select2
limited_upgrades_in_use = (upgrade.data for upgrade in ship.upgrades when upgrade?.data?.limited?)
available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgradesByLocalizedName when upgrade.slot == slot and @matcher(upgrade_name, term) and (not upgrade.ship? or upgrade.ship == ship.data.name) and (not upgrade.faction? or @isOurFaction(upgrade.faction)))
if filter_func != @dfl_filter_func
available_upgrades = (upgrade for upgrade in available_upgrades when filter_func(upgrade))
# Special case #3
eligible_upgrades = (upgrade for upgrade_name, upgrade of available_upgrades when (not upgrade.unique? or upgrade not in @uniques_in_use['Upgrade']) and (not (ship? and upgrade.restriction_func?) or upgrade.restriction_func(ship, this_upgrade_obj)) and upgrade not in limited_upgrades_in_use and ((not upgrade.max_per_squad?) or ship.builder.countUpgrades(upgrade.canonical_name) < upgrade.max_per_squad))
# Special case #2 :(
# current_upgrade_forcibly_removed = false
#for title in ship?.titles ? []
# if title?.data?.special_case == 'A-Wing Test Pilot'
# for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?)
# eligible_upgrades.removeItem equipped_upgrade
# current_upgrade_forcibly_removed = true if equipped_upgrade == include_upgrade
for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?)
eligible_upgrades.removeItem equipped_upgrade
# Re-enable selected upgrade
if include_upgrade? and (((include_upgrade.unique? or include_upgrade.limited? or include_upgrade.max_per_squad?) and @matcher(include_upgrade.name, term)))# or current_upgrade_forcibly_removed)
# available_upgrades.push include_upgrade
eligible_upgrades.push include_upgrade
retval = ({ id: upgrade.id, text: "#{upgrade.name} (#{upgrade.points})", points: upgrade.points, english_name: upgrade.english_name, disabled: upgrade not in eligible_upgrades } for upgrade in available_upgrades).sort exportObj.sortHelper
# Possibly adjust the upgrade
if this_upgrade_obj.adjustment_func?
(this_upgrade_obj.adjustment_func(upgrade) for upgrade in retval)
else
retval
getAvailableModificationsIncluding: (include_modification, ship, term='', filter_func=@dfl_filter_func) ->
# Returns data formatted for Select2
limited_modifications_in_use = (modification.data for modification in ship.modifications when modification?.data?.limited?)
available_modifications = (modification for modification_name, modification of exportObj.modificationsByLocalizedName when @matcher(modification_name, term) and (not modification.ship? or modification.ship == ship.data.name))
if filter_func != @dfl_filter_func
available_modifications = (modification for modification in available_modifications when filter_func(modification))
if ship? and exportObj.hugeOnly(ship) > 0
# Only show allowed mods for Epic ships
available_modifications = (modification for modification in available_modifications when modification.ship? or not modification.restriction_func? or modification.restriction_func ship)
eligible_modifications = (modification for modification_name, modification of available_modifications when (not modification.unique? or modification not in @uniques_in_use['Modification']) and (not modification.faction? or @isOurFaction(modification.faction)) and (not (ship? and modification.restriction_func?) or modification.restriction_func ship) and modification not in limited_modifications_in_use)
# I finally had to add a special case :( If something else demands it
# then I will try to make this more systematic, but I haven't come up
# with a good solution... yet.
# current_mod_forcibly_removed = false
for thing in (ship?.titles ? []).concat(ship?.upgrades ? [])
if thing?.data?.special_case == 'Royal Guard TIE'
# Need to refetch by ID because Vaksai may have modified its cost
for equipped_modification in (modificationsById[modification.data.id] for modification in ship.modifications when modification?.data?)
eligible_modifications.removeItem equipped_modification
# current_mod_forcibly_removed = true if equipped_modification == include_modification
# Re-add selected modification
if include_modification? and (((include_modification.unique? or include_modification.limited?) and @matcher(include_modification.name, term)))# or current_mod_forcibly_removed)
eligible_modifications.push include_modification
({ id: modification.id, text: "#{modification.name} (#{modification.points})", points: modification.points, english_name: modification.english_name, disabled: modification not in eligible_modifications } for modification in available_modifications).sort exportObj.sortHelper
getAvailableTitlesIncluding: (ship, include_title, term='') ->
# Returns data formatted for Select2
# Titles are no longer unique!
limited_titles_in_use = (title.data for title in ship.titles when title?.data?.limited?)
available_titles = (title for title_name, title of exportObj.titlesByLocalizedName when (not title.ship? or title.ship == ship.data.name) and @matcher(title_name, term))
eligible_titles = (title for title_name, title of available_titles when (not title.unique? or (title not in @uniques_in_use['Title'] and title.canonical_name.getXWSBaseName() not in (t.canonical_name.getXWSBaseName() for t in @uniques_in_use['Title'])) or title.canonical_name.getXWSBaseName() == include_title?.canonical_name.getXWSBaseName()) and (not title.faction? or @isOurFaction(title.faction)) and (not (ship? and title.restriction_func?) or title.restriction_func ship) and title not in limited_titles_in_use)
# Re-add selected title
if include_title? and (((include_title.unique? or include_title.limited?) and @matcher(include_title.name, term)))
eligible_titles.push include_title
({ id: title.id, text: "#{title.name} (#{title.points})", points: title.points, english_name: title.english_name, disabled: title not in eligible_titles } for title in available_titles).sort exportObj.sortHelper
# Converts a maneuver table for into an HTML table.
getManeuverTableHTML: (maneuvers, baseManeuvers) ->
if not maneuvers? or maneuvers.length == 0
return "Missing maneuver info."
# Preprocess maneuvers to see which bearings are never used so we
# don't render them.
bearings_without_maneuvers = [0...maneuvers[0].length]
for bearings in maneuvers
for difficulty, bearing in bearings
if difficulty > 0
bearings_without_maneuvers.removeItem bearing
# console.log "bearings without maneuvers:"
# console.dir bearings_without_maneuvers
outTable = "<table><tbody>"
for speed in [maneuvers.length - 1 .. 0]
haveManeuver = false
for v in maneuvers[speed]
if v > 0
haveManeuver = true
break
continue if not haveManeuver
outTable += "<tr><td>#{speed}</td>"
for turn in [0 ... maneuvers[speed].length]
continue if turn in bearings_without_maneuvers
outTable += "<td>"
if maneuvers[speed][turn] > 0
color = switch maneuvers[speed][turn]
when 1 then "white"
when 2 then "dodgerblue"
when 3 then "red"
outTable += """<svg xmlns="http://www.w3.org/2000/svg" width="30px" height="30px" viewBox="0 0 200 200">"""
if speed == 0
outTable += """<rect x="50" y="50" width="100" height="100" style="fill:#{color}" />"""
else
outlineColor = "black"
if maneuvers[speed][turn] != baseManeuvers[speed][turn]
outlineColor = "mediumblue" # highlight manuevers modified by another card (e.g. R2 Astromech makes all 1 & 2 speed maneuvers green)
transform = ""
className = ""
switch turn
when 0
# turn left
linePath = "M160,180 L160,70 80,70"
trianglePath = "M80,100 V40 L30,70 Z"
when 1
# bank left
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(-5 -15) rotate(45 70 90)' "
when 2
# straight
linePath = "M100,180 L100,100 100,80"
trianglePath = "M70,80 H130 L100,30 Z"
when 3
# bank right
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(5 -15) rotate(-45 130 90)' "
when 4
# turn right
linePath = "M40,180 L40,70 120,70"
trianglePath = "M120,100 V40 L170,70 Z"
when 5
# k-turn/u-turn
linePath = "M50,180 L50,100 C50,10 140,10 140,100 L140,120"
trianglePath = "M170,120 H110 L140,180 Z"
when 6
# segnor's loop left
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(0 50)'"
when 7
# segnor's loop right
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(0 50)'"
when 8
# tallon roll left
linePath = "M160,180 L160,70 80,70"
trianglePath = "M60,100 H100 L80,140 Z"
when 9
# tallon roll right
linePath = "M40,180 L40,70 120,70"
trianglePath = "M100,100 H140 L120,140 Z"
when 10
# backward left
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(5 -15) rotate(-45 130 90)' "
className = 'backwards'
when 11
# backward straight
linePath = "M100,180 L100,100 100,80"
trianglePath = "M70,80 H130 L100,30 Z"
className = 'backwards'
when 12
# backward right
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(-5 -15) rotate(45 70 90)' "
className = 'backwards'
outTable += $.trim """
<g class="maneuver #{className}">
<path d='#{trianglePath}' fill='#{color}' stroke-width='5' stroke='#{outlineColor}' #{transform}/>
<path stroke-width='25' fill='none' stroke='#{outlineColor}' d='#{linePath}' />
<path stroke-width='15' fill='none' stroke='#{color}' d='#{linePath}' />
</g>
"""
outTable += "</svg>"
outTable += "</td>"
outTable += "</tr>"
outTable += "</tbody></table>"
outTable
showTooltip: (type, data, additional_opts) ->
if data != @tooltip_currently_displaying
switch type
when 'Ship'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.pilot.sources).sort().join(', ')
if @collection?.counts?
ship_count = @collection.counts?.ship?[data.data.english_name] ? 0
pilot_count = @collection.counts?.pilot?[data.pilot.english_name] ? 0
@info_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection."""
else
@info_container.find('.info-collection').text ''
effective_stats = data.effectiveStats()
extra_actions = $.grep effective_stats.actions, (el, i) ->
el not in (data.pilot.ship_override?.actions ? data.data.actions)
extra_actions_red = $.grep effective_stats.actionsred, (el, i) ->
el not in (data.pilot.ship_override?.actionsred ? data.data.actionsred)
@info_container.find('.info-name').html """#{if data.pilot.unique then "· " else ""}#{data.pilot.name}#{if data.pilot.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data.pilot) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.pilot.text ? ''
@info_container.find('tr.info-ship td.info-data').text data.pilot.ship
@info_container.find('tr.info-ship').show()
@info_container.find('tr.info-skill td.info-data').text statAndEffectiveStat(data.pilot.skill, effective_stats, 'skill')
@info_container.find('tr.info-skill').show()
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack')
@info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(data.data.attack_icon ? 'xwing-miniatures-font-attack')
@info_container.find('tr.info-attack td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attack ? data.data.attack), effective_stats, 'attack')
@info_container.find('tr.info-attack').toggle(data.pilot.ship_override?.attack? or data.data.attack?)
@info_container.find('tr.info-attack-fullfront td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackf ? data.data.attackf), effective_stats, 'attackf')
@info_container.find('tr.info-attack-fullfront').toggle(data.pilot.ship_override?.attackf? or data.data.attackf?)
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-back td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackb ? data.data.attackb), effective_stats, 'attackb')
@info_container.find('tr.info-attack-back').toggle(data.pilot.ship_override?.attackb? or data.data.attackb?)
@info_container.find('tr.info-attack-turret td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackt ? data.data.attackt), effective_stats, 'attackt')
@info_container.find('tr.info-attack-turret').toggle(data.pilot.ship_override?.attackt? or data.data.attackt?)
@info_container.find('tr.info-attack-doubleturret td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackdt ? data.data.attackdt), effective_stats, 'attackdt')
@info_container.find('tr.info-attack-doubleturret').toggle(data.pilot.ship_override?.attackdt? or data.data.attackdt?)
@info_container.find('tr.info-energy td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.energy ? data.data.energy), effective_stats, 'energy')
@info_container.find('tr.info-energy').toggle(data.pilot.ship_override?.energy? or data.data.energy?)
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-agility td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.agility ? data.data.agility), effective_stats, 'agility')
@info_container.find('tr.info-agility').show()
@info_container.find('tr.info-hull td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.hull ? data.data.hull), effective_stats, 'hull')
@info_container.find('tr.info-hull').show()
@info_container.find('tr.info-shields td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.shields ? data.data.shields), effective_stats, 'shields')
@info_container.find('tr.info-shields').show()
@info_container.find('tr.info-force td.info-data').html (statAndEffectiveStat((data.pilot.ship_override?.force ? data.pilot.force), effective_stats, 'force') + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
if data.pilot.ship_override?.force? or data.pilot.force?
@info_container.find('tr.info-force').show()
else
@info_container.find('tr.info-force').hide()
if data.pilot.charge?
if data.pilot.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.pilot.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
else
@info_container.find('tr.info-charge td.info-data').text data.pilot.charge
@info_container.find('tr.info-charge').show()
else
@info_container.find('tr.info-charge').hide()
@info_container.find('tr.info-actions td.info-data').html (exportObj.translate(@language, 'action', a) for a in (data.pilot.ship_override?.actions ? data.data.actions).concat( ("<strong>#{exportObj.translate @language, 'action', action}</strong>" for action in extra_actions))).join ' '
if data.data.actionsred?
@info_container.find('tr.info-actions-red td.info-data-red').html (exportObj.translate(@language, 'action', a) for a in (data.pilot.ship_override?.actionsred ? data.data.actionsred).concat( ("<strong>#{exportObj.translate @language, 'action', action}</strong>" for action in extra_actions_red))).join ' '
@info_container.find('tr.info-actions-red').toggle(data.data.actionsred?)
@info_container.find('tr.info-actions').show()
@info_container.find('tr.info-upgrades').show()
@info_container.find('tr.info-upgrades td.info-data').text((exportObj.translate(@language, 'slot', slot) for slot in data.pilot.slots).join(', ') or 'None')
@info_container.find('p.info-maneuvers').show()
@info_container.find('p.info-maneuvers').html(@getManeuverTableHTML(effective_stats.maneuvers, data.data.maneuvers))
when 'Pilot'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ')
if @collection?.counts?
pilot_count = @collection.counts?.pilot?[data.english_name] ? 0
ship_count = @collection.counts.ship?[additional_opts.ship] ? 0
@info_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection."""
else
@info_container.find('.info-collection').text ''
@info_container.find('.info-name').html """#{if data.unique then "· " else ""}#{data.name}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.text ? ''
ship = exportObj.ships[data.ship]
@info_container.find('tr.info-ship td.info-data').text data.ship
@info_container.find('tr.info-ship').show()
@info_container.find('tr.info-skill td.info-data').text data.skill
@info_container.find('tr.info-skill').show()
@info_container.find('tr.info-attack td.info-data').text(data.ship_override?.attack ? ship.attack)
@info_container.find('tr.info-attack').toggle(data.ship_override?.attack? or ship.attack?)
@info_container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf)
@info_container.find('tr.info-attack-fullfront').toggle(ship.attackf?)
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-back td.info-data').text(ship.attackb)
@info_container.find('tr.info-attack-back').toggle(ship.attackb?)
@info_container.find('tr.info-attack-turret td.info-data').text(ship.attackt)
@info_container.find('tr.info-attack-turret').toggle(ship.attackt?)
@info_container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt)
@info_container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?)
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc')
@info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-frontarc')
@info_container.find('tr.info-energy td.info-data').text(data.ship_override?.energy ? ship.energy)
@info_container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?)
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-agility td.info-data').text(data.ship_override?.agility ? ship.agility)
@info_container.find('tr.info-agility').show()
@info_container.find('tr.info-hull td.info-data').text(data.ship_override?.hull ? ship.hull)
@info_container.find('tr.info-hull').show()
@info_container.find('tr.info-shields td.info-data').text(data.ship_override?.shields ? ship.shields)
@info_container.find('tr.info-shields').show()
if data.ship_override?.force or data.force?
@info_container.find('tr.info-force td.info-data').html ((data.ship_override?.force ? data.force)+ '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
@info_container.find('tr.info-force').show()
else
@info_container.find('tr.info-force').hide()
if data.charge?
if data.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
else
@info_container.find('tr.info-charge td.info-data').text data.charge
@info_container.find('tr.info-charge').show()
else
@info_container.find('tr.info-charge').hide()
@info_container.find('tr.info-actions td.info-data').html (exportObj.translate(@language, 'action', action) for action in (data.ship_override?.actions ? exportObj.ships[data.ship].actions)).join(' ')
if ships[data.ship].actionsred?
@info_container.find('tr.info-actions-red td.info-data-red').html (exportObj.translate(@language, 'action', action) for action in (data.ship_override?.actionsred ? exportObj.ships[data.ship].actionsred)).join(' ')
@info_container.find('tr.info-actions-red').show()
else
@info_container.find('tr.info-actions-red').hide()
@info_container.find('tr.info-actions').show()
@info_container.find('tr.info-upgrades').show()
@info_container.find('tr.info-upgrades td.info-data').text((exportObj.translate(@language, 'slot', slot) for slot in data.slots).join(', ') or 'None')
@info_container.find('p.info-maneuvers').show()
@info_container.find('p.info-maneuvers').html(@getManeuverTableHTML(ship.maneuvers, ship.maneuvers))
when 'Addon'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ')
if @collection?.counts?
addon_count = @collection.counts?[additional_opts.addon_type.toLowerCase()]?[data.english_name] ? 0
@info_container.find('.info-collection').text """You have #{addon_count} in your collection."""
else
@info_container.find('.info-collection').text ''
@info_container.find('.info-name').html """#{if data.unique then "· " else ""}#{data.name}#{if data.limited? then " (#{exportObj.translate(@language, 'ui', 'limited')})" else ""}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.text ? ''
@info_container.find('tr.info-ship').hide()
@info_container.find('tr.info-skill').hide()
if data.energy?
@info_container.find('tr.info-energy td.info-data').text data.energy
@info_container.find('tr.info-energy').show()
else
@info_container.find('tr.info-energy').hide()
if data.attack?
# Attack icons on upgrade cards don't get special icons
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc')
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass('xwing-miniatures-font-frontarc')
@info_container.find('tr.info-attack td.info-data').text data.attack
@info_container.find('tr.info-attack').show()
else
@info_container.find('tr.info-attack').hide()
if data.attackt?
@info_container.find('tr.info-attack-turret td.info-data').text data.attackt
@info_container.find('tr.info-attack-turret').show()
else
@info_container.find('tr.info-attack-turret').hide()
if data.attackbull?
@info_container.find('tr.info-attack-bullseye td.info-data').text data.attackbull
@info_container.find('tr.info-attack-bullseye').show()
else
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-fullfront').hide()
@info_container.find('tr.info-attack-back').hide()
@info_container.find('tr.info-attack-doubleturret').hide()
if data.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.charge + """<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>""")
else
@info_container.find('tr.info-charge td.info-data').text data.charge
@info_container.find('tr.info-charge').toggle(data.charge?)
if data.range?
@info_container.find('tr.info-range td.info-data').text data.range
@info_container.find('tr.info-range').show()
else
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
@info_container.find('tr.info-force').toggle(data.force?)
@info_container.find('tr.info-agility').hide()
@info_container.find('tr.info-hull').hide()
@info_container.find('tr.info-shields').hide()
@info_container.find('tr.info-actions').hide()
@info_container.find('tr.info-actions-red').hide()
@info_container.find('tr.info-upgrades').hide()
@info_container.find('p.info-maneuvers').hide()
@info_container.show()
@tooltip_currently_displaying = data
_randomizerLoopBody: (data) =>
if data.keep_running and data.iterations < data.max_iterations
data.iterations++
#console.log "Current points: #{@total_points} of #{data.max_points}, iteration=#{data.iterations} of #{data.max_iterations}, keep_running=#{data.keep_running}"
if @total_points == data.max_points
# Exact hit!
#console.log "Points reached exactly"
data.keep_running = false
else if @total_points < data.max_points
#console.log "Need to add something"
# Add something
# Possible options: ship or empty addon slot
unused_addons = []
for ship in @ships
for upgrade in ship.upgrades
unused_addons.push upgrade unless upgrade.data?
unused_addons.push ship.title if ship.title? and not ship.title.data?
for modification in ship.modifications
unused_addons.push modification unless modification.data?
# 0 is ship, otherwise addon
idx = $.randomInt(1 + unused_addons.length)
if idx == 0
# Add random ship
#console.log "Add ship"
available_ships = @getAvailableShipsMatching()
ship_type = available_ships[$.randomInt available_ships.length].text
available_pilots = @getAvailablePilotsForShipIncluding(ship_type)
pilot = available_pilots[$.randomInt available_pilots.length]
if exportObj.pilotsById[pilot.id].sources.intersects(data.allowed_sources)
new_ship = @addShip()
new_ship.setPilotById pilot.id
else
# Add upgrade/title/modification
#console.log "Add addon"
addon = unused_addons[idx - 1]
switch addon.type
when 'Upgrade'
available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship) when exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources))
addon.setById available_upgrades[$.randomInt available_upgrades.length].id if available_upgrades.length > 0
when 'Title'
available_titles = (title for title in @getAvailableTitlesIncluding(addon.ship) when exportObj.titlesById[title.id].sources.intersects(data.allowed_sources))
addon.setById available_titles[$.randomInt available_titles.length].id if available_titles.length > 0
when 'Modification'
available_modifications = (modification for modification in @getAvailableModificationsIncluding(null, addon.ship) when exportObj.modificationsById[modification.id].sources.intersects(data.allowed_sources))
addon.setById available_modifications[$.randomInt available_modifications.length].id if available_modifications.length > 0
else
throw new Error("Invalid addon type #{addon.type}")
else
#console.log "Need to remove something"
# Remove something
removable_things = []
for ship in @ships
removable_things.push ship
for upgrade in ship.upgrades
removable_things.push upgrade if upgrade.data?
removable_things.push ship.title if ship.title?.data?
removable_things.push ship.modification if ship.modification?.data?
if removable_things.length > 0
thing_to_remove = removable_things[$.randomInt removable_things.length]
#console.log "Removing #{thing_to_remove}"
if thing_to_remove instanceof Ship
@removeShip thing_to_remove
else if thing_to_remove instanceof GenericAddon
thing_to_remove.setData null
else
throw new Error("Unknown thing to remove #{thing_to_remove}")
# continue the "loop"
window.setTimeout @_makeRandomizerLoopFunc(data), 0
else
#console.log "Clearing timer #{data.timer}, iterations=#{data.iterations}, keep_running=#{data.keep_running}"
window.clearTimeout data.timer
# Update all selectors
for ship in @ships
ship.updateSelections()
@suppress_automatic_new_ship = false
@addShip()
_makeRandomizerLoopFunc: (data) =>
() =>
@_randomizerLoopBody(data)
randomSquad: (max_points=100, allowed_sources=null, timeout_ms=1000, max_iterations=1000) ->
@backend_status.fadeOut 'slow'
@suppress_automatic_new_ship = true
# Clear all existing ships
while @ships.length > 0
@removeShip @ships[0]
throw new Error("Ships not emptied") if @ships.length > 0
data =
iterations: 0
max_points: max_points
max_iterations: max_iterations
keep_running: true
allowed_sources: allowed_sources ? exportObj.expansions
stopHandler = () =>
#console.log "*** TIMEOUT *** TIMEOUT *** TIMEOUT ***"
data.keep_running = false
data.timer = window.setTimeout stopHandler , timeout_ms
#console.log "Timer set for #{timeout_ms}ms, timer is #{data.timer}"
window.setTimeout @_makeRandomizerLoopFunc(data), 0
@resetCurrentSquad()
@current_squad.name = '<NAME> Squad'
@container.trigger 'xwing-backend:squadNameChanged'
setBackend: (backend) ->
@backend = backend
describeSquad: ->
(ship.pilot.name for ship in @ships when ship.pilot?).join ', '
listCards: ->
card_obj = {}
for ship in @ships
if ship.pilot?
card_obj[ship.pilot.name] = null
for upgrade in ship.upgrades
card_obj[upgrade.data.name] = null if upgrade.data?
card_obj[ship.title.data.name] = null if ship.title?.data?
card_obj[ship.modification.data.name] = null if ship.modification?.data?
return Object.keys(card_obj).sort()
getNotes: ->
@notes.val()
getObstacles: ->
@current_obstacles
isSquadPossibleWithCollection: ->
# console.log "#{@faction}: isSquadPossibleWithCollection()"
# If the collection is uninitialized or empty, don't actually check it.
if Object.keys(@collection?.expansions ? {}).length == 0
# console.log "collection not ready or is empty"
return true
@collection.reset()
validity = true
for ship in @ships
if ship.pilot?
# Try to get both the physical model and the pilot card.
ship_is_available = @collection.use('ship', ship.pilot.english_ship)
pilot_is_available = @collection.use('pilot', ship.pilot.english_name)
# console.log "#{@faction}: Ship #{ship.pilot.english_ship} available: #{ship_is_available}"
# console.log "#{@faction}: Pilot #{ship.pilot.english_name} available: #{pilot_is_available}"
validity = false unless ship_is_available and pilot_is_available
for upgrade in ship.upgrades
if upgrade.data?
upgrade_is_available = @collection.use('upgrade', upgrade.data.english_name)
# console.log "#{@faction}: Upgrade #{upgrade.data.english_name} available: #{upgrade_is_available}"
validity = false unless upgrade_is_available
for modification in ship.modifications
if modification.data?
modification_is_available = @collection.use('modification', modification.data.english_name)
# console.log "#{@faction}: Modification #{modification.data.english_name} available: #{modification_is_available}"
validity = false unless modification_is_available
for title in ship.titles
if title?.data?
title_is_available = @collection.use('title', title.data.english_name)
# console.log "#{@faction}: Title #{title.data.english_name} available: #{title_is_available}"
validity = false unless title_is_available
validity
checkCollection: ->
# console.log "#{@faction}: Checking validity of squad against collection..."
if @collection?
@collection_invalid_container.toggleClass 'hidden', @isSquadPossibleWithCollection()
toXWS: ->
# Often you will want JSON.stringify(builder.toXWS())
xws =
description: @getNotes()
faction: exportObj.toXWSFaction[@faction]
name: @current_squad.name
pilots: []
points: @total_points
vendor:
yasb:
builder: '(Yet Another) X-Wing Miniatures Squad Builder'
builder_url: window.location.href.split('?')[0]
link: @getPermaLink()
version: '0.3.0'
for ship in @ships
if ship.pilot?
xws.pilots.push ship.toXWS()
# Associate multisection ships
# This maps id to list of pilots it comprises
multisection_id_to_pilots = {}
last_id = 0
unmatched = (pilot for pilot in xws.pilots when pilot.multisection?)
for _ in [0...(unmatched.length ** 2)]
break if unmatched.length == 0
# console.log "Top of loop, unmatched: #{m.name for m in unmatched}"
unmatched_pilot = unmatched.shift()
unmatched_pilot.multisection_id ?= last_id++
multisection_id_to_pilots[unmatched_pilot.multisection_id] ?= [unmatched_pilot]
break if unmatched.length == 0
# console.log "Finding matches for #{unmatched_pilot.name} (assigned id=#{unmatched_pilot.multisection_id})"
matches = []
for candidate in unmatched
# console.log "-> examine #{candidate.name}"
if unmatched_pilot.name in candidate.multisection
matches.push candidate
unmatched_pilot.multisection.removeItem candidate.name
candidate.multisection.removeItem unmatched_pilot.name
candidate.multisection_id = unmatched_pilot.multisection_id
# console.log "-> MATCH FOUND #{candidate.name}, assigned id=#{candidate.multisection_id}"
multisection_id_to_pilots[candidate.multisection_id].push candidate
if unmatched_pilot.multisection.length == 0
# console.log "-> No more sections to match for #{unmatched_pilot.name}"
break
for match in matches
if match.multisection.length == 0
# console.log "Dequeue #{match.name} since it has no more sections to match"
unmatched.removeItem match
for pilot in xws.pilots
delete pilot.multisection if pilot.multisection?
obstacles = @getObstacles()
if obstacles? and obstacles.length > 0
xws.obstacles = obstacles
xws
toMinimalXWS: ->
# Just what's necessary
xws = @toXWS()
# Keep mandatory stuff only
for own k, v of xws
delete xws[k] unless k in ['faction', 'pilots', 'version']
for own k, v of xws.pilots
delete xws[k] unless k in ['name', 'ship', 'upgrades', 'multisection_id']
xws
loadFromXWS: (xws, cb) ->
success = null
error = null
version_list = (parseInt x for x in xws.version.split('.'))
switch
# Not doing backward compatibility pre-1.x
when version_list > [0, 1]
xws_faction = exportObj.fromXWSFaction[xws.faction]
if @faction != xws_faction
throw new Error("Attempted to load XWS for #{xws.faction} but builder is #{@faction}")
if xws.name?
@current_squad.name = xws.name
if xws.description?
@notes.val xws.description
if xws.obstacles?
@current_squad.additional_data.obstacles = xws.obstacles
@suppress_automatic_new_ship = true
@removeAllShips()
for pilot in xws.pilots
new_ship = @addShip()
for ship_name, ship_data of exportObj.ships
if @matcher(ship_data.xws, pilot.ship)
shipnameXWS =
id: ship_data.name
xws: ship_data.xws
console.log "#{pilot.xws}"
try
new_ship.setPilot (p for p in (exportObj.pilotsByFactionXWS[@faction][pilot.id] ?= exportObj.pilotsByFactionCanonicalName[@faction][pilot.id]) when p.ship == shipnameXWS.id)[0]
catch err
console.error err.message
continue
# Turn all the upgrades into a flat list so we can keep trying to add them
addons = []
for upgrade_type, upgrade_canonicals of pilot.upgrades ? {}
for upgrade_canonical in upgrade_canonicals
# console.log upgrade_type, upgrade_canonical
slot = null
slot = exportObj.fromXWSUpgrade[upgrade_type] ? upgrade_type.capitalize()
addon = exportObj.upgradesBySlotXWSName[slot][upgrade_canonical] ?= exportObj.upgradesBySlotCanonicalName[slot][upgrade_canonical]
if addon?
# console.log "-> #{upgrade_type} #{addon.name} #{slot}"
addons.push
type: slot
data: addon
slot: slot
if addons.length > 0
for _ in [0...1000]
# Try to add an addon. If it's not eligible, requeue it and
# try it again later, as another addon might allow it.
addon = addons.shift()
# console.log "Adding #{addon.data.name} to #{new_ship}..."
addon_added = false
switch addon.type
when 'Modification'
for modification in new_ship.modifications
continue if modification.data?
modification.setData addon.data
addon_added = true
break
when 'Title'
for title in new_ship.titles
continue if title.data?
# Special cases :(
if addon.data instanceof Array
# Right now, the only time this happens is because of
# Heavy Scyk. Check the rest of the pending addons for torp,
# cannon, or missiles. Otherwise, it doesn't really matter.
slot_guesses = (a.data.slot for a in addons when a.data.slot in ['Cannon', 'Missile', 'Torpedo'])
# console.log slot_guesses
if slot_guesses.length > 0
# console.log "Guessing #{slot_guesses[0]}"
title.setData exportObj.titlesByLocalizedName[""""Heavy Scyk" Interceptor (#{slot_guesses[0]})"""]
else
# console.log "No idea, setting to #{addon.data[0].name}"
title.setData addon.data[0]
else
title.setData addon.data
addon_added = true
else
# console.log "Looking for unused #{addon.slot} in #{new_ship}..."
for upgrade, i in new_ship.upgrades
continue if upgrade.slot != addon.slot or upgrade.data?
upgrade.setData addon.data
addon_added = true
break
if addon_added
# console.log "Successfully added #{addon.data.name} to #{new_ship}"
if addons.length == 0
# console.log "Done with addons for #{new_ship}"
break
else
# Can't add it, requeue unless there are no other addons to add
# in which case this isn't valid
if addons.length == 0
success = false
error = "Could not add #{addon.data.name} to #{new_ship}"
break
else
# console.log "Could not add #{addon.data.name} to #{new_ship}, trying later"
addons.push addon
if addons.length > 0
success = false
error = "Could not add all upgrades"
break
@suppress_automatic_new_ship = false
# Finally, the unassigned ship
@addShip()
success = true
else
success = false
error = "Invalid or unsupported XWS version"
if success
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadNameChanged'
@container.trigger 'xwing-backend:squadDirtinessChanged'
# console.log "success: #{success}, error: #{error}"
cb
success: success
error: error
class Ship
constructor: (args) ->
# args
@builder = args.builder
@container = args.container
# internal state
@pilot = null
@data = null # ship data
@upgrades = []
@modifications = []
@titles = []
@setupUI()
destroy: (cb) ->
@resetPilot()
@resetAddons()
@teardownUI()
idx = @builder.ships.indexOf this
if idx < 0
throw new Error("Ship not registered with builder")
@builder.ships.splice idx, 1
cb()
copyFrom: (other) ->
throw new Error("Cannot copy from self") if other is this
#console.log "Attempt to copy #{other?.pilot?.name}"
return unless other.pilot? and other.data?
#console.log "Setting pilot to ID=#{other.pilot.id}"
if other.pilot.unique
# Look for cheapest generic or available unique, otherwise do nothing
available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled)
if available_pilots.length > 0
@setPilotById available_pilots[0].id
# Can't just copy upgrades since slots may be different
# Similar to setPilot() when ship is the same
other_upgrades = {}
for upgrade in other.upgrades
if upgrade?.data? and not upgrade.data.unique and ((not upgrade.data.max_per_squad?) or @builder.countUpgrades(upgrade.data.canonical_name) < upgrade.data.max_per_squad)
other_upgrades[upgrade.slot] ?= []
other_upgrades[upgrade.slot].push upgrade
other_modifications = []
for modification in other.modifications
if modification?.data? and not modification.data.unique
other_modifications.push modification
other_titles = []
for title in other.titles
if title?.data? and not title.data.unique
other_titles.push title
for title in @titles
other_title = other_titles.shift()
if other_title?
title.setById other_title.data.id
for modification in @modifications
other_modification = other_modifications.shift()
if other_modification?
modification.setById other_modification.data.id
for upgrade in @upgrades
other_upgrade = (other_upgrades[upgrade.slot] ? []).shift()
if other_upgrade?
upgrade.setById other_upgrade.data.id
else
return
else
# Exact clone, so we can copy things over directly
@setPilotById other.pilot.id
# set up non-conferred addons
other_conferred_addons = []
other_conferred_addons = other_conferred_addons.concat(other.titles[0].conferredAddons) if other.titles[0]?.data? # and other.titles.conferredAddons.length > 0
other_conferred_addons = other_conferred_addons.concat(other.modifications[0].conferredAddons) if other.modifications[0]?.data?
#console.log "Looking for conferred upgrades..."
for other_upgrade, i in other.upgrades
# console.log "Examining upgrade #{other_upgrade}"
if other_upgrade.data? and other_upgrade not in other_conferred_addons and not other_upgrade.data.unique and i < @upgrades.length and ((not other_upgrade.data.max_per_squad?) or @builder.countUpgrades(other_upgrade.data.canonical_name) < other_upgrade.data.max_per_squad)
#console.log "Copying non-unique upgrade #{other_upgrade} into slot #{i}"
@upgrades[i].setById other_upgrade.data.id
#console.log "Checking other ship base title #{other.title ? null}"
@titles[0].setById other.titles[0].data.id if other.titles[0]?.data? and not other.titles[0].data.unique
#console.log "Checking other ship base modification #{other.modifications[0] ? null}"
@modifications[0].setById other.modifications[0].data.id if other.modifications[0]?.data and not other.modifications[0].data.unique
# set up conferred non-unique addons
#console.log "Attempt to copy conferred addons..."
if other.titles[0]? and other.titles[0].conferredAddons.length > 0
#console.log "Other ship title #{other.titles[0]} confers addons"
for other_conferred_addon, i in other.titles[0].conferredAddons
@titles[0].conferredAddons[i].setById other_conferred_addon.data.id if other_conferred_addon.data? and not other_conferred_addon.data?.unique
if other.modifications[0]? and other.modifications[0].conferredAddons.length > 0
#console.log "Other ship base modification #{other.modifications[0]} confers addons"
for other_conferred_addon, i in other.modifications[0].conferredAddons
@modifications[0].conferredAddons[i].setById other_conferred_addon.data.id if other_conferred_addon.data? and not other_conferred_addon.data?.unique
@updateSelections()
@builder.container.trigger 'xwing:pointsUpdated'
@builder.current_squad.dirty = true
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
setShipType: (ship_type) ->
@pilot_selector.data('select2').container.show()
if ship_type != @pilot?.ship
# Ship changed; select first non-unique
@setPilot (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not exportObj.pilotsById[result.id].unique)[0]
# Clear ship background class
for cls in @row.attr('class').split(/\s+/)
if cls.indexOf('ship-') == 0
@row.removeClass cls
# Show delete button
@remove_button.fadeIn 'fast'
# Ship background
@row.addClass "ship-#{ship_type.toLowerCase().replace(/[^a-z0-9]/gi, '')}0"
@builder.container.trigger 'xwing:shipUpdated'
setPilotById: (id) ->
@setPilot exportObj.pilotsById[parseInt id]
setPilotByName: (name) ->
@setPilot exportObj.pilotsByLocalizedName[$.trim name]
setPilot: (new_pilot) ->
if new_pilot != @pilot
@builder.current_squad.dirty = true
same_ship = @pilot? and new_pilot?.ship == @pilot.ship
old_upgrades = {}
old_titles = []
old_modifications = []
if same_ship
# track addons and try to reassign them
for upgrade in @upgrades
if upgrade?.data?
old_upgrades[upgrade.slot] ?= []
old_upgrades[upgrade.slot].push upgrade
for title in @titles
if title?.data?
old_titles.push title
for modification in @modifications
if modification?.data?
old_modifications.push modification
@resetPilot()
@resetAddons()
if new_pilot?
@data = exportObj.ships[new_pilot?.ship]
if new_pilot?.unique?
await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ]
@pilot = new_pilot
@setupAddons() if @pilot?
@copy_button.show()
@setShipType @pilot.ship
if same_ship
# Hopefully this order is correct
for title in @titles
old_title = old_titles.shift()
if old_title?
title.setById old_title.data.id
for modification in @modifications
old_modification = old_modifications.shift()
if old_modification?
modification.setById old_modification.data.id
for upgrade in @upgrades
old_upgrade = (old_upgrades[upgrade.slot] ? []).shift()
if old_upgrade?
upgrade.setById old_upgrade.data.id
else
@copy_button.hide()
@builder.container.trigger 'xwing:pointsUpdated'
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
resetPilot: ->
if @pilot?.unique?
await @builder.container.trigger 'xwing:releaseUnique', [ @pilot, 'Pilot', defer() ]
@pilot = null
setupAddons: ->
# Upgrades from pilot
for slot in @pilot.slots ? []
@upgrades.push new exportObj.Upgrade
ship: this
container: @addon_container
slot: slot
# Title
#if @pilot.ship of exportObj.titlesByShip
# @titles.push new exportObj.Title
# ship: this
# container: @addon_container
# Modifications
#@modifications.push new exportObj.Modification
# ship: this
# container: @addon_container
resetAddons: ->
await
for title in @titles
title.destroy defer() if title?
for upgrade in @upgrades
upgrade.destroy defer() if upgrade?
for modification in @modifications
modification.destroy defer() if modification?
@upgrades = []
@modifications = []
@titles = []
getPoints: ->
points = @pilot?.points ? 0
for title in @titles
points += (title?.getPoints() ? 0)
for upgrade in @upgrades
points += upgrade.getPoints()
for modification in @modifications
points += (modification?.getPoints() ? 0)
@points_container.find('span').text points
if points > 0
@points_container.fadeTo 'fast', 1
else
@points_container.fadeTo 0, 0
points
getEpicPoints: ->
@data?.epic_points ? 0
updateSelections: ->
if @pilot?
@ship_selector.select2 'data',
id: @pilot.ship
text: @pilot.ship
canonical_name: exportObj.ships[@pilot.ship].canonical_name
@pilot_selector.select2 'data',
id: @pilot.id
text: "#{@pilot.name} (#{@pilot.points})"
@pilot_selector.data('select2').container.show()
for upgrade in @upgrades
upgrade.updateSelection()
for title in @titles
title.updateSelection() if title?
for modification in @modifications
modification.updateSelection() if modification?
else
@pilot_selector.select2 'data', null
@pilot_selector.data('select2').container.toggle(@ship_selector.val() != '')
setupUI: ->
@row = $ document.createElement 'DIV'
@row.addClass 'row-fluid ship'
@row.insertBefore @builder.notes_container
@row.append $.trim '''
<div class="span3">
<input class="ship-selector-container" type="hidden" />
<br />
<input type="hidden" class="pilot-selector-container" />
</div>
<div class="span1 points-display-container">
<span></span>
</div>
<div class="span6 addon-container" />
<div class="span2 button-container">
<button class="btn btn-danger remove-pilot"><span class="visible-desktop visible-tablet hidden-phone" data-toggle="tooltip" title="Remove Pilot"><i class="fa fa-times"></i></span><span class="hidden-desktop hidden-tablet visible-phone">Remove Pilot</span></button>
<button class="btn copy-pilot"><span class="visible-desktop visible-tablet hidden-phone" data-toggle="tooltip" title="Clone Pilot"><i class="fa fa-files-o"></i></span><span class="hidden-desktop hidden-tablet visible-phone">Clone Pilot</span></button>
</div>
'''
@row.find('.button-container span').tooltip()
@ship_selector = $ @row.find('input.ship-selector-container')
@pilot_selector = $ @row.find('input.pilot-selector-container')
shipResultFormatter = (object, container, query) ->
# Append directly so we don't have to disable markup escaping
$(container).append """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.canonical_name}"></i> #{object.text}"""
# If you return a string, Select2 will render it
undefined
@ship_selector.select2
width: '100%'
placeholder: exportObj.translate @builder.language, 'ui', 'shipSelectorPlaceholder'
query: (query) =>
@builder.checkCollection()
query.callback
more: false
results: @builder.getAvailableShipsMatching(query.term)
minimumResultsForSearch: if $.isMobile() then -1 else 0
formatResultCssClass: (obj) =>
if @builder.collection?
not_in_collection = false
if @pilot? and obj.id == exportObj.ships[@pilot.ship].id
# Currently selected ship; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@builder.collection.checkShelf('ship', obj.english_name) or @builder.collection.checkTable('pilot', obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @builder.collection.checkShelf('ship', obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
formatResult: shipResultFormatter
formatSelection: shipResultFormatter
@ship_selector.on 'change', (e) =>
@setShipType @ship_selector.val()
# assign ship row an id for testing purposes
@row.attr 'id', "row-#{@ship_selector.data('select2').container.attr('id')}"
@pilot_selector.select2
width: '100%'
placeholder: exportObj.translate @builder.language, 'ui', 'pilotSelectorPlaceholder'
query: (query) =>
@builder.checkCollection()
query.callback
more: false
results: @builder.getAvailablePilotsForShipIncluding(@ship_selector.val(), @pilot, query.term)
minimumResultsForSearch: if $.isMobile() then -1 else 0
formatResultCssClass: (obj) =>
if @builder.collection?
not_in_collection = false
if obj.id == @pilot?.id
# Currently selected pilot; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@builder.collection.checkShelf('pilot', obj.english_name) or @builder.collection.checkTable('pilot', obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @builder.collection.checkShelf('pilot', obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
@pilot_selector.on 'change', (e) =>
@setPilotById @pilot_selector.select2('val')
@builder.current_squad.dirty = true
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
@builder.backend_status.fadeOut 'slow'
@pilot_selector.data('select2').results.on 'mousemove-filtered', (e) =>
select2_data = $(e.target).closest('.select2-result').data 'select2-data'
@builder.showTooltip 'Pilot', exportObj.pilotsById[select2_data.id], {ship: @data?.english_name} if select2_data?.id?
@pilot_selector.data('select2').container.on 'mouseover', (e) =>
@builder.showTooltip 'Ship', this if @data?
@pilot_selector.data('select2').container.hide()
@points_container = $ @row.find('.points-display-container')
@points_container.fadeTo 0, 0
@addon_container = $ @row.find('div.addon-container')
@remove_button = $ @row.find('button.remove-pilot')
@remove_button.click (e) =>
e.preventDefault()
@row.slideUp 'fast', () =>
@builder.removeShip this
@backend_status?.fadeOut 'slow'
@remove_button.hide()
@copy_button = $ @row.find('button.copy-pilot')
@copy_button.click (e) =>
clone = @builder.ships[@builder.ships.length - 1]
clone.copyFrom(this)
@copy_button.hide()
teardownUI: ->
@row.text ''
@row.remove()
toString: ->
if @pilot?
"Pilot #{@pilot.name} flying #{@data.name}"
else
"Ship without pilot"
toHTML: ->
effective_stats = @effectiveStats()
action_icons = []
action_icons_red = []
for action in effective_stats.actions
action_icons.push switch action
when 'Focus'
"""<i class="xwing-miniatures-font xwing-miniatures-font-focus"></i>"""
when 'Evade'
"""<i class="xwing-miniatures-font xwing-miniatures-font-evade"></i>"""
when 'Barrel Roll'
"""<i class="xwing-miniatures-font xwing-miniatures-font-barrelroll"></i>"""
when 'Target Lock'
"""<i class="xwing-miniatures-font xwing-miniatures-font-lock"></i>"""
when 'Boost'
"""<i class="xwing-miniatures-font xwing-miniatures-font-boost"></i>"""
when 'Coordinate'
"""<i class="xwing-miniatures-font xwing-miniatures-font-coordinate"></i>"""
when 'Jam'
"""<i class="xwing-miniatures-font xwing-miniatures-font-jam"></i>"""
when 'Recover'
"""<i class="xwing-miniatures-font xwing-miniatures-font-recover"></i>"""
when 'Reinforce'
"""<i class="xwing-miniatures-font xwing-miniatures-font-reinforce"></i>"""
when 'Cloak'
"""<i class="xwing-miniatures-font xwing-miniatures-font-cloak"></i>"""
when 'Slam'
"""<i class="xwing-miniatures-font xwing-miniatures-font-slam"></i>"""
when 'Rotate Arc'
"""<i class="xwing-miniatures-font xwing-miniatures-font-rotatearc"></i>"""
when 'Reload'
"""<i class="xwing-miniatures-font xwing-miniatures-font-reload"></i>"""
when 'Calculate'
"""<i class="xwing-miniatures-font xwing-miniatures-font-calculate"></i>"""
when "<r>> Target Lock</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-lock"></i></r>"""
when "<r>> Barrel Roll</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-barrelroll"></i></r>"""
when "<r>> Focus</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-focus"></i></r>"""
when "<r>> Rotate Arc</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-rotatearc"></i></r>"""
when "<r>> Evade</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-evade"></i></r>"""
when "<r>> Calculate</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-calculate"></i></r>"""
else
"""<span> #{action}<span>"""
for actionred in effective_stats.actionsred
action_icons_red.push switch actionred
when 'Focus'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-focus"></i>"""
when 'Evade'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-evade"></i>"""
when 'Barrel Roll'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-barrelroll"></i>"""
when 'Target Lock'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-lock"></i>"""
when 'Boost'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-boost"></i>"""
when 'Coordinate'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-coordinate"></i>"""
when 'Jam'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-jam"></i>"""
when 'Recover'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-recover"></i>"""
when 'Reinforce'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-reinforce"></i>"""
when 'Cloak'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-cloak"></i>"""
when 'Slam'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-slam"></i>"""
when 'Rotate Arc'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-rotatearc"></i>"""
when 'Reload'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-reload"></i>"""
when 'Calculate'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-calculate"></i>"""
else
"""<span> #{action}<span>"""
action_bar = action_icons.join ' '
action_bar_red = action_icons_red.join ' '
attack_icon = @data.attack_icon ? 'xwing-miniatures-font-frontarc'
attackHTML = if (@pilot.ship_override?.attack? or @data.attack?) then $.trim """
<i class="xwing-miniatures-font #{attack_icon}"></i>
<span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attack ? @data.attack), effective_stats, 'attack')}</span>
""" else ''
energyHTML = if (@pilot.ship_override?.energy? or @data.energy?) then $.trim """
<i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>
<span class="info-data info-energy">#{statAndEffectiveStat((@pilot.ship_override?.energy ? @data.energy), effective_stats, 'energy')}</span>
""" else ''
forceHTML = if (@pilot.force?) then $.trim """
<i class="xwing-miniatures-font xwing-miniatures-font-force"></i>
<span class="info-data info-force">#{statAndEffectiveStat((@pilot.ship_override?.force ? @pilot.force), effective_stats, 'force')}</span>
""" else ''
html = $.trim """
<div class="fancy-pilot-header">
<div class="pilot-header-text">#{@pilot.name} <i class="xwing-miniatures-ship xwing-miniatures-ship-#{@data.canonical_name}"></i><span class="fancy-ship-type"> #{@data.name}</span></div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle pilot-points">#{@pilot.points}</div>
</div>
</div>
</div>
<div class="fancy-pilot-stats">
<div class="pilot-stats-content">
<span class="info-data info-skill">PS #{statAndEffectiveStat(@pilot.skill, effective_stats, 'skill')}</span>
#{attackHTML}
#{energyHTML}
<i class="xwing-miniatures-font xwing-miniatures-font-agility"></i>
<span class="info-data info-agility">#{statAndEffectiveStat((@pilot.ship_override?.agility ? @data.agility), effective_stats, 'agility')}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-hull"></i>
<span class="info-data info-hull">#{statAndEffectiveStat((@pilot.ship_override?.hull ? @data.hull), effective_stats, 'hull')}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-shield"></i>
<span class="info-data info-shields">#{statAndEffectiveStat((@pilot.ship_override?.shields ? @data.shields), effective_stats, 'shields')}</span>
#{forceHTML}
#{action_bar}
#{action_bar_red}
</div>
</div>
"""
if @pilot.text
html += $.trim """
<div class="fancy-pilot-text">#{@pilot.text}</div>
"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
html += $.trim """
<div class="fancy-upgrade-container">
"""
for upgrade in slotted_upgrades
html += upgrade.toHTML()
html += $.trim """
</div>
"""
# if @getPoints() != @pilot.points
html += $.trim """
<div class="ship-points-total">
<strong>Ship Total: #{@getPoints()}</strong>
</div>
"""
"""<div class="fancy-ship">#{html}</div>"""
toTableRow: ->
table_html = $.trim """
<tr class="simple-pilot">
<td class="name">#{@pilot.name} — #{@data.name}</td>
<td class="points">#{@pilot.points}</td>
</tr>
"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
for upgrade in slotted_upgrades
table_html += upgrade.toTableRow()
# if @getPoints() != @pilot.points
table_html += """<tr class="simple-ship-total"><td colspan="2">Ship Total: #{@getPoints()}</td></tr>"""
table_html += '<tr><td> </td><td></td></tr>'
table_html
toBBCode: ->
bbcode = """[b]#{@pilot.name} (#{@pilot.points})[/b]"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
bbcode +="\n"
bbcode_upgrades= []
for upgrade in slotted_upgrades
upgrade_bbcode = upgrade.toBBCode()
bbcode_upgrades.push upgrade_bbcode if upgrade_bbcode?
bbcode += bbcode_upgrades.join "\n"
bbcode
toSimpleHTML: ->
html = """<b>#{@pilot.name} (#{@pilot.points})</b><br />"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
for upgrade in slotted_upgrades
upgrade_html = upgrade.toSimpleHTML()
html += upgrade_html if upgrade_html?
html
toSerialized: ->
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
# Skip conferred upgrades
conferred_addons = []
for title in @titles
conferred_addons = conferred_addons.concat(title?.conferredAddons ? [])
for modification in @modifications
conferred_addons = conferred_addons.concat(modification?.conferredAddons ? [])
for upgrade in @upgrades
conferred_addons = conferred_addons.concat(upgrade?.conferredAddons ? [])
upgrades = """#{upgrade?.data?.id ? -1 for upgrade, i in @upgrades when upgrade not in conferred_addons}"""
serialized_conferred_addons = []
for addon in conferred_addons
serialized_conferred_addons.push addon.toSerialized()
[
@pilot.id,
upgrades,
@titles[0]?.data?.id ? -1,
@modifications[0]?.data?.id ? -1,
serialized_conferred_addons.join(','),
].join ':'
fromSerialized: (version, serialized) ->
switch version
when 1
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:TITLEUPGRADE1,TITLEUPGRADE2:MODIFICATIONID
[ pilot_id, upgrade_ids, title_id, title_conferred_upgrade_ids, modification_id ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
@upgrades[i].setById upgrade_id if upgrade_id >= 0
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
if @titles[0]? and @titles[0].conferredAddons.length > 0
for upgrade_id, i in title_conferred_upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
@titles[0].conferredAddons[i].setById upgrade_id if upgrade_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
when 2, 3
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
[ pilot_id, upgrade_ids, title_id, modification_id, conferredaddon_pairs ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
deferred_ids = []
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
continue if upgrade_id < 0 or isNaN(upgrade_id)
if @upgrades[i].isOccupied()
deferred_ids.push upgrade_id
else
@upgrades[i].setById upgrade_id
for deferred_id in deferred_ids
for upgrade, i in @upgrades
continue if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot
upgrade.setById deferred_id
break
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
# We confer title addons before modification addons, to pick an arbitrary ordering.
if conferredaddon_pairs?
conferredaddon_pairs = conferredaddon_pairs.split ','
else
conferredaddon_pairs = []
if @titles[0]? and @titles[0].conferredAddons.length > 0
title_conferred_addon_pairs = conferredaddon_pairs.splice 0, @titles[0].conferredAddons.length
for conferredaddon_pair, i in title_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = @titles[0].conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for modification in @modifications
if modification?.data? and modification.conferredAddons.length > 0
modification_conferred_addon_pairs = conferredaddon_pairs.splice 0, modification.conferredAddons.length
for conferredaddon_pair, i in modification_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = modification.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
when 4
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
[ pilot_id, upgrade_ids, title_id, modification_id, conferredaddon_pairs ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
deferred_ids = []
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
continue if upgrade_id < 0 or isNaN(upgrade_id)
# Defer fat upgrades
if @upgrades[i].isOccupied() or @upgrades[i].dataById[upgrade_id].also_occupies_upgrades?
deferred_ids.push upgrade_id
else
@upgrades[i].setById upgrade_id
for deferred_id in deferred_ids
for upgrade, i in @upgrades
continue if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot
upgrade.setById deferred_id
break
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
# We confer title addons before modification addons, to pick an arbitrary ordering.
if conferredaddon_pairs?
conferredaddon_pairs = conferredaddon_pairs.split ','
else
conferredaddon_pairs = []
for title, i in @titles
if title?.data? and title.conferredAddons.length > 0
# console.log "Confer title #{title.data.name} at #{i}"
title_conferred_addon_pairs = conferredaddon_pairs.splice 0, title.conferredAddons.length
for conferredaddon_pair, i in title_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = title.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for modification in @modifications
if modification?.data? and modification.conferredAddons.length > 0
modification_conferred_addon_pairs = conferredaddon_pairs.splice 0, modification.conferredAddons.length
for conferredaddon_pair, i in modification_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = modification.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for upgrade in @upgrades
if upgrade?.data? and upgrade.conferredAddons.length > 0
upgrade_conferred_addon_pairs = conferredaddon_pairs.splice 0, upgrade.conferredAddons.length
for conferredaddon_pair, i in upgrade_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = upgrade.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
@updateSelections()
effectiveStats: ->
stats =
skill: @pilot.skill
attack: @pilot.ship_override?.attack ? @data.attack
attackf: @pilot.ship_override?.attackf ? @data.attackf
attackb: @pilot.ship_override?.attackb ? @data.attackb
attackt: @pilot.ship_override?.attackt ? @data.attackt
attackdt: @pilot.ship_override?.attackdt ? @data.attackdt
energy: @pilot.ship_override?.energy ? @data.energy
agility: @pilot.ship_override?.agility ? @data.agility
hull: @pilot.ship_override?.hull ? @data.hull
shields: @pilot.ship_override?.shields ? @data.shields
force: @pilot.ship_override?.force ? @pilot.force
charge: @pilot.ship_override?.charge ? @pilot.charge
actions: (@pilot.ship_override?.actions ? @data.actions).slice 0
actionsred: ((@pilot.ship_override?.actionsred ? @data.actionsred) ? []).slice 0
# need a deep copy of maneuvers array
stats.maneuvers = []
for s in [0 ... (@data.maneuvers ? []).length]
stats.maneuvers[s] = @data.maneuvers[s].slice 0
for upgrade in @upgrades
upgrade.data.modifier_func(stats) if upgrade?.data?.modifier_func?
for title in @titles
title.data.modifier_func(stats) if title?.data?.modifier_func?
for modification in @modifications
modification.data.modifier_func(stats) if modification?.data?.modifier_func?
@pilot.modifier_func(stats) if @pilot?.modifier_func?
stats
validate: ->
# Remove addons that violate their validation functions (if any) one by one
# until everything checks out
# If there is no explicit validation_func, use restriction_func
max_checks = 128 # that's a lot of addons (Epic?)
for i in [0...max_checks]
valid = true
for upgrade in @upgrades
func = upgrade?.data?.validation_func ? upgrade?.data?.restriction_func ? undefined
if func? and not func(this, upgrade)
#console.log "Invalid upgrade: #{upgrade?.data?.name}"
upgrade.setById null
valid = false
break
for title in @titles
func = title?.data?.validation_func ? title?.data?.restriction_func ? undefined
if func? and not func this
#console.log "Invalid title: #{title?.data?.name}"
title.setById null
valid = false
break
for modification in @modifications
func = modification?.data?.validation_func ? modification?.data?.restriction_func ? undefined
if func? and not func(this, modification)
#console.log "Invalid modification: #{modification?.data?.name}"
modification.setById null
valid = false
break
break if valid
@updateSelections()
checkUnreleasedContent: ->
if @pilot? and not exportObj.isReleased @pilot
#console.log "#{@pilot.name} is unreleased"
return true
for title in @titles
if title?.data? and not exportObj.isReleased title.data
#console.log "#{title.data.name} is unreleased"
return true
for modification in @modifications
if modification?.data? and not exportObj.isReleased modification.data
#console.log "#{modification.data.name} is unreleased"
return true
for upgrade in @upgrades
if upgrade?.data? and not exportObj.isReleased upgrade.data
#console.log "#{upgrade.data.name} is unreleased"
return true
false
checkEpicContent: ->
if @pilot? and @pilot.epic?
return true
for title in @titles
if title?.data?.epic?
return true
for modification in @modifications
if modification?.data?.epic?
return true
for upgrade in @upgrades
if upgrade?.data?.epic?
return true
false
hasAnotherUnoccupiedSlotLike: (upgrade_obj) ->
for upgrade in @upgrades
continue if upgrade == upgrade_obj or upgrade.slot != upgrade_obj.slot
return true unless upgrade.isOccupied()
false
toXWS: ->
xws =
id: (@pilot.xws ? @pilot.canonical_name)
points: @getPoints()
#ship: @data.canonical_name
ship: @data.xws.canonicalize()
if @data.multisection
xws.multisection = @data.multisection.slice 0
upgrade_obj = {}
for upgrade in @upgrades
if upgrade?.data?
upgrade.toXWS upgrade_obj
for modification in @modifications
if modification?.data?
modification.toXWS upgrade_obj
for title in @titles
if title?.data?
title.toXWS upgrade_obj
if Object.keys(upgrade_obj).length > 0
xws.upgrades = upgrade_obj
xws
getConditions: ->
if Set?
conditions = new Set()
if @pilot?.applies_condition?
if @pilot.applies_condition instanceof Array
for condition in @pilot.applies_condition
conditions.add(exportObj.conditionsByCanonicalName[condition])
else
conditions.add(exportObj.conditionsByCanonicalName[@pilot.applies_condition])
for upgrade in @upgrades
if upgrade?.data?.applies_condition?
if upgrade.data.applies_condition instanceof Array
for condition in upgrade.data.applies_condition
conditions.add(exportObj.conditionsByCanonicalName[condition])
else
conditions.add(exportObj.conditionsByCanonicalName[upgrade.data.applies_condition])
conditions
else
console.warn 'Set not supported in this JS implementation, not implementing conditions'
[]
class GenericAddon
constructor: (args) ->
# args
@ship = args.ship
@container = $ args.container
# internal state
@data = null
@unadjusted_data = null
@conferredAddons = []
@serialization_code = 'X'
@occupied_by = null
@occupying = []
@destroyed = false
# Overridden by children
@type = null
@dataByName = null
@dataById = null
@adjustment_func = args.adjustment_func if args.adjustment_func?
@filter_func = args.filter_func if args.filter_func?
@placeholderMod_func = if args.placeholderMod_func? then args.placeholderMod_func else (x) => x
destroy: (cb, args...) ->
return cb(args) if @destroyed
if @data?.unique?
await @ship.builder.container.trigger 'xwing:releaseUnique', [ @data, @type, defer() ]
@destroyed = true
@rescindAddons()
@deoccupyOtherUpgrades()
@selector.select2 'destroy'
cb args
setupSelector: (args) ->
@selector = $ document.createElement 'INPUT'
@selector.attr 'type', 'hidden'
@container.append @selector
args.minimumResultsForSearch = -1 if $.isMobile()
args.formatResultCssClass = (obj) =>
if @ship.builder.collection?
not_in_collection = false
if obj.id == @data?.id
# Currently selected card; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@ship.builder.collection.checkShelf(@type.toLowerCase(), obj.english_name) or @ship.builder.collection.checkTable(@type.toLowerCase(), obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @ship.builder.collection.checkShelf(@type.toLowerCase(), obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
args.formatSelection = (obj, container) =>
icon = switch @type
when 'Upgrade'
@slot.toLowerCase().replace(/[^0-9a-z]/gi, '')
else
@type.toLowerCase().replace(/[^0-9a-z]/gi, '')
icon = icon.replace("configuration", "config")
.replace("force", "forcepower")
# Append directly so we don't have to disable markup escaping
$(container).append """<i class="xwing-miniatures-font xwing-miniatures-font-#{icon}"></i> #{obj.text}"""
# If you return a string, Select2 will render it
undefined
@selector.select2 args
@selector.on 'change', (e) =>
@setById @selector.select2('val')
@ship.builder.current_squad.dirty = true
@ship.builder.container.trigger 'xwing-backend:squadDirtinessChanged'
@ship.builder.backend_status.fadeOut 'slow'
@selector.data('select2').results.on 'mousemove-filtered', (e) =>
select2_data = $(e.target).closest('.select2-result').data 'select2-data'
@ship.builder.showTooltip 'Addon', @dataById[select2_data.id], {addon_type: @type} if select2_data?.id?
@selector.data('select2').container.on 'mouseover', (e) =>
@ship.builder.showTooltip 'Addon', @data, {addon_type: @type} if @data?
setById: (id) ->
@setData @dataById[parseInt id]
setByName: (name) ->
@setData @dataByName[$.trim name]
setData: (new_data) ->
if new_data?.id != @data?.id
if @data?.unique?
await @ship.builder.container.trigger 'xwing:releaseUnique', [ @unadjusted_data, @type, defer() ]
@rescindAddons()
@deoccupyOtherUpgrades()
if new_data?.unique?
await @ship.builder.container.trigger 'xwing:claimUnique', [ new_data, @type, defer() ]
# Need to make a copy of the data, but that means I can't just check equality
@data = @unadjusted_data = new_data
if @data?
if @data.superseded_by_id
return @setById @data.superseded_by_id
if @adjustment_func?
@data = @adjustment_func(@data)
@unequipOtherUpgrades()
@occupyOtherUpgrades()
@conferAddons()
else
@deoccupyOtherUpgrades()
@ship.builder.container.trigger 'xwing:pointsUpdated'
conferAddons: ->
if @data.confersAddons? and @data.confersAddons.length > 0
for addon in @data.confersAddons
cls = addon.type
args =
ship: @ship
container: @container
args.slot = addon.slot if addon.slot?
args.adjustment_func = addon.adjustment_func if addon.adjustment_func?
args.filter_func = addon.filter_func if addon.filter_func?
args.auto_equip = addon.auto_equip if addon.auto_equip?
args.placeholderMod_func = addon.placeholderMod_func if addon.placeholderMod_func?
addon = new cls args
if addon instanceof exportObj.Upgrade
@ship.upgrades.push addon
else if addon instanceof exportObj.Modification
@ship.modifications.push addon
else if addon instanceof exportObj.Title
@ship.titles.push addon
else
throw new Error("Unexpected addon type for addon #{addon}")
@conferredAddons.push addon
rescindAddons: ->
await
for addon in @conferredAddons
addon.destroy defer()
for addon in @conferredAddons
if addon instanceof exportObj.Upgrade
@ship.upgrades.removeItem addon
else if addon instanceof exportObj.Modification
@ship.modifications.removeItem addon
else if addon instanceof exportObj.Title
@ship.titles.removeItem addon
else
throw new Error("Unexpected addon type for addon #{addon}")
@conferredAddons = []
getPoints: ->
# Moar special case jankiness
if @data?.variableagility? and @ship?
Math.max(@data?.basepoints ? 0, (@data?.basepoints ? 0) + ((@ship?.data.agility - 1)*2) + 1)
else if @data?.variablebase? and not (@ship.data.medium? or @ship.data.large?)
Math.max(0, @data?.basepoints)
else if @data?.variablebase? and @ship?.data.medium?
Math.max(0, (@data?.basepoints ? 0) + (@data?.basepoints))
else if @data?.variablebase? and @ship?.data.large?
Math.max(0, (@data?.basepoints ? 0) + (@data?.basepoints * 2))
else
@data?.points ? 0
updateSelection: ->
if @data?
@selector.select2 'data',
id: @data.id
text: "#{@data.name} (#{@data.points})"
else
@selector.select2 'data', null
toString: ->
if @data?
"#{@data.name} (#{@data.points})"
else
"No #{@type}"
toHTML: ->
if @data?
upgrade_slot_font = (@data.slot ? @type).toLowerCase().replace(/[^0-9a-z]/gi, '')
match_array = @data.text.match(/(<span.*<\/span>)<br \/><br \/>(.*)/)
if match_array
restriction_html = '<div class="card-restriction-container">' + match_array[1] + '</div>'
text_str = match_array[2]
else
restriction_html = ''
text_str = @data.text
attackHTML = if (@data.attack?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attack}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-frontarc"></i>
</div>
""" else if (@data.attackt?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attackt}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-singleturretarc"></i>
</div>
""" else if (@data.attackbull?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attackbull}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-bullseyearc"></i>
</div>
""" else ''
energyHTML = if (@data.energy?) then $.trim """
<div class="upgrade-energy">
<span class="info-data info-energy">#{@data.energy}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>
</div>
""" else ''
$.trim """
<div class="upgrade-container">
<div class="upgrade-stats">
<div class="upgrade-name"><i class="xwing-miniatures-font xwing-miniatures-font-#{upgrade_slot_font}"></i>#{@data.name}</div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle upgrade-points">#{@data.points}</div>
</div>
</div>
#{restriction_html}
</div>
#{attackHTML}
#{energyHTML}
<div class="upgrade-text">#{text_str}</div>
<div style="clear: both;"></div>
</div>
"""
else
''
toTableRow: ->
if @data?
$.trim """
<tr class="simple-addon">
<td class="name">#{@data.name}</td>
<td class="points">#{@data.points}</td>
</tr>
"""
else
''
toBBCode: ->
if @data?
"""[i]#{@data.name} (#{@data.points})[/i]"""
else
null
toSimpleHTML: ->
if @data?
"""<i>#{@data.name} (#{@data.points})</i><br />"""
else
''
toSerialized: ->
"""#{@serialization_code}.#{@data?.id ? -1}"""
unequipOtherUpgrades: ->
for slot in @data?.unequips_upgrades ? []
for upgrade in @ship.upgrades
continue if upgrade.slot != slot or upgrade == this or not upgrade.isOccupied()
upgrade.setData null
break
if @data?.unequips_modifications
for modification in @ship.modifications
continue unless modification == this or modification.isOccupied()
modification.setData null
isOccupied: ->
@data? or @occupied_by?
occupyOtherUpgrades: ->
for slot in @data?.also_occupies_upgrades ? []
for upgrade in @ship.upgrades
continue if upgrade.slot != slot or upgrade == this or upgrade.isOccupied()
@occupy upgrade
break
if @data?.also_occupies_modifications
for modification in @ship.modifications
continue if modification == this or modification.isOccupied()
@occupy modification
deoccupyOtherUpgrades: ->
for upgrade in @occupying
@deoccupy upgrade
occupy: (upgrade) ->
upgrade.occupied_by = this
upgrade.selector.select2 'enable', false
@occupying.push upgrade
deoccupy: (upgrade) ->
upgrade.occupied_by = null
upgrade.selector.select2 'enable', true
occupiesAnotherUpgradeSlot: ->
for upgrade in @ship.upgrades
continue if upgrade.slot != @slot or upgrade == this or upgrade.data?
if upgrade.occupied_by? and upgrade.occupied_by == this
return true
false
toXWS: (upgrade_dict) ->
upgrade_type = switch @type
when 'Upgrade'
exportObj.toXWSUpgrade[@slot] ? @slot.canonicalize()
else
exportObj.toXWSUpgrade[@type] ? @type.canonicalize()
(upgrade_dict[upgrade_type] ?= []).push (@data.xws ? @data.canonical_name)
class exportObj.Upgrade extends GenericAddon
constructor: (args) ->
# args
super args
@slot = args.slot
@type = 'Upgrade'
@dataById = exportObj.upgradesById
@dataByName = exportObj.upgradesByLocalizedName
@serialization_code = 'U'
@setupSelector()
setupSelector: ->
super
width: '50%'
placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'upgradePlaceholder', @slot)
allowClear: true
query: (query) =>
@ship.builder.checkCollection()
query.callback
more: false
results: @ship.builder.getAvailableUpgradesIncluding(@slot, @data, @ship, this, query.term, @filter_func)
#Temporarily removed modifications as they are now upgrades
#class exportObj.Modification extends GenericAddon
# constructor: (args) ->
# super args
# @type = 'Modification'
# @dataById = exportObj.modificationsById
# @dataByName = exportObj.modificationsByLocalizedName
# @serialization_code = 'M'
# @setupSelector()
# setupSelector: ->
# super
# width: '50%'
# placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'modificationPlaceholder')
# allowClear: true
# query: (query) =>
# @ship.builder.checkCollection()
# query.callback
# more: false
# results: @ship.builder.getAvailableModificationsIncluding(@data, @ship, query.term, @filter_func)
class exportObj.Title extends GenericAddon
constructor: (args) ->
super args
@type = 'Title'
@dataById = exportObj.titlesById
@dataByName = exportObj.titlesByLocalizedName
@serialization_code = 'T'
@setupSelector()
setupSelector: ->
super
width: '50%'
placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'titlePlaceholder')
allowClear: true
query: (query) =>
@ship.builder.checkCollection()
query.callback
more: false
results: @ship.builder.getAvailableTitlesIncluding(@ship, @data, query.term)
class exportObj.RestrictedUpgrade extends exportObj.Upgrade
constructor: (args) ->
@filter_func = args.filter_func
super args
@serialization_code = 'u'
if args.auto_equip?
@setById args.auto_equip
#class exportObj.RestrictedModification extends exportObj.Modification
# constructor: (args) ->
# @filter_func = args.filter_func
# super args
# @serialization_code = 'm'
# if args.auto_equip?
# @setById args.auto_equip
SERIALIZATION_CODE_TO_CLASS =
'M': exportObj.Modification
'T': exportObj.Title
'U': exportObj.Upgrade
'u': exportObj.RestrictedUpgrade
'm': exportObj.RestrictedModification
| true | ###
X-Wing Squad Builder
PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
https://github.com/geordanr/xwing
###
exportObj = exports ? this
exportObj.sortHelper = (a, b) ->
if a.points == b.points
a_name = a.text.replace(/[^a-z0-9]/ig, '')
b_name = b.text.replace(/[^a-z0-9]/ig, '')
if a_name == b_name
0
else
if a_name > b_name then 1 else -1
else
if a.points > b.points then 1 else -1
$.isMobile = ->
navigator.userAgent.match /(iPhone|iPod|iPad|Android)/i
$.randomInt = (n) ->
Math.floor(Math.random() * n)
# ripped from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
$.getParameterByName = (name) ->
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
regexS = "[\\?&]" + name + "=([^&#]*)"
regex = new RegExp(regexS)
results = regex.exec(window.location.search)
if results == null
return ""
else
return decodeURIComponent(results[1].replace(/\+/g, " "))
Array::intersects = (other) ->
for item in this
if item in other
return true
return false
Array::removeItem = (item) ->
idx = @indexOf item
@splice(idx, 1) unless idx == -1
this
String::capitalize = ->
@charAt(0).toUpperCase() + @slice(1)
String::getXWSBaseName = ->
@split('-')[0]
URL_BASE = "#{window.location.protocol}//#{window.location.host}#{window.location.pathname}"
SQUAD_DISPLAY_NAME_MAX_LENGTH = 24
statAndEffectiveStat = (base_stat, effective_stats, key) ->
"""#{base_stat}#{if effective_stats[key] != base_stat then " (#{effective_stats[key]})" else ""}"""
getPrimaryFaction = (faction) ->
switch faction
when 'Rebel Alliance'
'Rebel Alliance'
when 'Galactic Empire'
'Galactic Empire'
else
faction
conditionToHTML = (condition) ->
html = $.trim """
<div class="condition">
<div class="name">#{if condition.unique then "· " else ""}#{condition.name}</div>
<div class="text">#{condition.text}</div>
</div>
"""
# Assumes cards.js will be loaded
class exportObj.SquadBuilder
constructor: (args) ->
# args
@container = $ args.container
@faction = $.trim args.faction
@printable_container = $ args.printable_container
@tab = $ args.tab
# internal state
@ships = []
@uniques_in_use =
Pilot:
[]
Upgrade:
[]
Modification:
[]
Title:
[]
@suppress_automatic_new_ship = false
@tooltip_currently_displaying = null
@randomizer_options =
sources: null
points: 100
@total_points = 0
@isCustom = false
@isEpic = false
@maxEpicPointsAllowed = 0
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
@backend = null
@current_squad = {}
@language = 'English'
@collection = null
@current_obstacles = []
@setupUI()
@setupEventHandlers()
window.setInterval @updatePermaLink, 250
@isUpdatingPoints = false
if $.getParameterByName('f') == @faction
@resetCurrentSquad(true)
@loadFromSerialized $.getParameterByName('d')
else
@resetCurrentSquad()
@addShip()
resetCurrentSquad: (initial_load=false) ->
default_squad_name = 'Unnamed Squadron'
squad_name = $.trim(@squad_name_input.val()) or default_squad_name
if initial_load and $.trim $.getParameterByName('sn')
squad_name = $.trim $.getParameterByName('sn')
squad_obstacles = []
if initial_load and $.trim $.getParameterByName('obs')
squad_obstacles = ($.trim $.getParameterByName('obs')).split(",").slice(0, 3)
@current_obstacles = squad_obstacles
else if @current_obstacles
squad_obstacles = @current_obstacles
@current_squad =
id: null
name: squad_name
dirty: false
additional_data:
points: @total_points
description: ''
cards: []
notes: ''
obstacles: squad_obstacles
faction: @faction
if @total_points > 0
if squad_name == default_squad_name
@current_squad.name = 'Unsaved Squadron'
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadNameChanged'
@container.trigger 'xwing-backend:squadDirtinessChanged'
newSquadFromScratch: ->
@squad_name_input.val 'PI:NAME:<NAME>END_PI Squadron'
@removeAllShips()
@addShip()
@current_obstacles = []
@resetCurrentSquad()
@notes.val ''
setupUI: ->
DEFAULT_RANDOMIZER_POINTS = 100
DEFAULT_RANDOMIZER_TIMEOUT_SEC = 2
DEFAULT_RANDOMIZER_ITERATIONS = 1000
@status_container = $ document.createElement 'DIV'
@status_container.addClass 'container-fluid'
@status_container.append $.trim '''
<div class="row-fluid">
<div class="span3 squad-name-container">
<div class="display-name">
<span class="squad-name"></span>
<i class="fa fa-pencil"></i>
</div>
<div class="input-append">
<input type="text" maxlength="64" placeholder="Name your squad..." />
<button class="btn save"><i class="fa fa-pencil-square-o"></i></button>
</div>
</div>
<div class="span4 points-display-container">
Points: <span class="total-points">0</span> / <input type="number" class="desired-points" value="100">
<select class="game-type-selector">
<option value="standard">Standard</option>
<option value="custom">Custom</option>
</select>
<span class="points-remaining-container">(<span class="points-remaining"></span> left)</span>
<span class="total-epic-points-container hidden"><br /><span class="total-epic-points">0</span> / <span class="max-epic-points">5</span> Epic Points</span>
<span class="content-warning unreleased-content-used hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning epic-content-used hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning illegal-epic-upgrades hidden"><br /><i class="fa fa-exclamation-circle"></i> Navigator cannot be equipped onto Huge ships in Epic tournament play!</span>
<span class="content-warning illegal-epic-too-many-small-ships hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning illegal-epic-too-many-large-ships hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
<span class="content-warning collection-invalid hidden"><br /><i class="fa fa-exclamation-circle"></i> <span class="translated"></span></span>
</div>
<div class="span5 pull-right button-container">
<div class="btn-group pull-right">
<button class="btn btn-primary view-as-text"><span class="hidden-phone"><i class="fa fa-print"></i> Print/View as </span>Text</button>
<!-- <button class="btn btn-primary print-list hidden-phone hidden-tablet"><i class="fa fa-print"></i> Print</button> -->
<a class="btn btn-primary hidden collection"><i class="fa fa-folder-open hidden-phone hidden-tabler"></i> Your Collection</a>
<!--
<button class="btn btn-primary randomize" ><i class="fa fa-random hidden-phone hidden-tablet"></i> Random!</button>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a class="randomize-options">Randomizer Options...</a></li>
</ul>
-->
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<button class="show-authenticated btn btn-primary save-list"><i class="fa fa-floppy-o"></i> Save</button>
<button class="show-authenticated btn btn-primary save-list-as"><i class="fa fa-files-o"></i> Save As...</button>
<button class="show-authenticated btn btn-primary delete-list disabled"><i class="fa fa-trash-o"></i> Delete</button>
<button class="show-authenticated btn btn-primary backend-list-my-squads show-authenticated">Load Squad</button>
<button class="btn btn-danger clear-squad">New Squad</button>
<span class="show-authenticated backend-status"></span>
</div>
</div>
'''
@container.append @status_container
@list_modal = $ document.createElement 'DIV'
@list_modal.addClass 'modal hide fade text-list-modal'
@container.append @list_modal
@list_modal.append $.trim """
<div class="modal-header">
<button type="button" class="close hidden-print" data-dismiss="modal" aria-hidden="true">×</button>
<div class="hidden-phone hidden-print">
<h3><span class="squad-name"></span> (<span class="total-points"></span>)<h3>
</div>
<div class="visible-phone hidden-print">
<h4><span class="squad-name"></span> (<span class="total-points"></span>)<h4>
</div>
<div class="visible-print">
<div class="fancy-header">
<div class="squad-name"></div>
<div class="squad-faction"></div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle">
<span class="total-points"></span>
</div>
</div>
</div>
</div>
<div class="fancy-under-header"></div>
</div>
</div>
<div class="modal-body">
<div class="fancy-list hidden-phone"></div>
<div class="simple-list"></div>
<div class="bbcode-list">
<p>Copy the BBCode below and paste it into your forum post.</p>
<textarea></textarea><button class="btn btn-copy">Copy</button>
</div>
<div class="html-list">
<textarea></textarea><button class="btn btn-copy">Copy</button>
</div>
</div>
<div class="modal-footer hidden-print">
<label class="vertical-space-checkbox">
Add space for damage/upgrade cards when printing <input type="checkbox" class="toggle-vertical-space" />
</label>
<label class="color-print-checkbox">
Print color <input type="checkbox" class="toggle-color-print" />
</label>
<label class="qrcode-checkbox hidden-phone">
Include QR codes <input type="checkbox" class="toggle-juggler-qrcode" checked="checked" />
</label>
<label class="qrcode-checkbox hidden-phone">
Include obstacle/damage deck choices <input type="checkbox" class="toggle-obstacles" />
</label>
<div class="btn-group list-display-mode">
<button class="btn select-simple-view">Simple</button>
<button class="btn select-fancy-view hidden-phone">Fancy</button>
<button class="btn select-bbcode-view">BBCode</button>
<button class="btn select-html-view">HTML</button>
</div>
<button class="btn print-list hidden-phone"><i class="fa fa-print"></i> Print</button>
<button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@fancy_container = $ @list_modal.find('div.modal-body .fancy-list')
@fancy_total_points_container = $ @list_modal.find('div.modal-header .total-points')
@simple_container = $ @list_modal.find('div.modal-body .simple-list')
@bbcode_container = $ @list_modal.find('div.modal-body .bbcode-list')
@bbcode_textarea = $ @bbcode_container.find('textarea')
@bbcode_textarea.attr 'readonly', 'readonly'
@htmlview_container = $ @list_modal.find('div.modal-body .html-list')
@html_textarea = $ @htmlview_container.find('textarea')
@html_textarea.attr 'readonly', 'readonly'
@toggle_vertical_space_container = $ @list_modal.find('.vertical-space-checkbox')
@toggle_color_print_container = $ @list_modal.find('.color-print-checkbox')
@list_modal.on 'click', 'button.btn-copy', (e) =>
@self = $(e.currentTarget)
@self.siblings('textarea').select()
@success = document.execCommand('copy')
if @success
@self.addClass 'btn-success'
setTimeout ( =>
@self.removeClass 'btn-success'
), 1000
@select_simple_view_button = $ @list_modal.find('.select-simple-view')
@select_simple_view_button.click (e) =>
@select_simple_view_button.blur()
unless @list_display_mode == 'simple'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_simple_view_button.addClass 'btn-inverse'
@list_display_mode = 'simple'
@simple_container.show()
@fancy_container.hide()
@bbcode_container.hide()
@htmlview_container.hide()
@toggle_vertical_space_container.hide()
@toggle_color_print_container.hide()
@select_fancy_view_button = $ @list_modal.find('.select-fancy-view')
@select_fancy_view_button.click (e) =>
@select_fancy_view_button.blur()
unless @list_display_mode == 'fancy'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_fancy_view_button.addClass 'btn-inverse'
@list_display_mode = 'fancy'
@fancy_container.show()
@simple_container.hide()
@bbcode_container.hide()
@htmlview_container.hide()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
@select_bbcode_view_button = $ @list_modal.find('.select-bbcode-view')
@select_bbcode_view_button.click (e) =>
@select_bbcode_view_button.blur()
unless @list_display_mode == 'bbcode'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_bbcode_view_button.addClass 'btn-inverse'
@list_display_mode = 'bbcode'
@bbcode_container.show()
@htmlview_container.hide()
@simple_container.hide()
@fancy_container.hide()
@bbcode_textarea.select()
@bbcode_textarea.focus()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
@select_html_view_button = $ @list_modal.find('.select-html-view')
@select_html_view_button.click (e) =>
@select_html_view_button.blur()
unless @list_display_mode == 'html'
@list_modal.find('.list-display-mode .btn').removeClass 'btn-inverse'
@select_html_view_button.addClass 'btn-inverse'
@list_display_mode = 'html'
@bbcode_container.hide()
@htmlview_container.show()
@simple_container.hide()
@fancy_container.hide()
@html_textarea.select()
@html_textarea.focus()
@toggle_vertical_space_container.show()
@toggle_color_print_container.show()
if $(window).width() >= 768
@simple_container.hide()
@select_fancy_view_button.click()
else
@select_simple_view_button.click()
@clear_squad_button = $ @status_container.find('.clear-squad')
@clear_squad_button.click (e) =>
if @current_squad.dirty and @backend?
@backend.warnUnsaved this, () =>
@newSquadFromScratch()
else
@newSquadFromScratch()
@squad_name_container = $ @status_container.find('div.squad-name-container')
@squad_name_display = $ @container.find('.display-name')
@squad_name_placeholder = $ @container.find('.squad-name')
@squad_name_input = $ @squad_name_container.find('input')
@squad_name_save_button = $ @squad_name_container.find('button.save')
@squad_name_input.closest('div').hide()
@points_container = $ @status_container.find('div.points-display-container')
@total_points_span = $ @points_container.find('.total-points')
@game_type_selector = $ @status_container.find('.game-type-selector')
@game_type_selector.change (e) =>
@onGameTypeChanged @game_type_selector.val()
@desired_points_input = $ @points_container.find('.desired-points')
@desired_points_input.change (e) =>
@game_type_selector.val 'custom'
@onGameTypeChanged 'custom'
@points_remaining_span = $ @points_container.find('.points-remaining')
@points_remaining_container = $ @points_container.find('.points-remaining-container')
@unreleased_content_used_container = $ @points_container.find('.unreleased-content-used')
@epic_content_used_container = $ @points_container.find('.epic-content-used')
@illegal_epic_upgrades_container = $ @points_container.find('.illegal-epic-upgrades')
@too_many_small_ships_container = $ @points_container.find('.illegal-epic-too-many-small-ships')
@too_many_large_ships_container = $ @points_container.find('.illegal-epic-too-many-large-ships')
@collection_invalid_container = $ @points_container.find('.collection-invalid')
@total_epic_points_container = $ @points_container.find('.total-epic-points-container')
@total_epic_points_span = $ @total_epic_points_container.find('.total-epic-points')
@max_epic_points_span = $ @points_container.find('.max-epic-points')
@view_list_button = $ @status_container.find('div.button-container button.view-as-text')
@randomize_button = $ @status_container.find('div.button-container button.randomize')
@customize_randomizer = $ @status_container.find('div.button-container a.randomize-options')
@backend_status = $ @status_container.find('.backend-status')
@backend_status.hide()
@collection_button = $ @status_container.find('div.button-container a.collection')
@collection_button.click (e) =>
e.preventDefault()
unless @collection_button.prop('disabled')
@collection.modal.modal 'show'
@squad_name_input.keypress (e) =>
if e.which == 13
@squad_name_save_button.click()
false
@squad_name_input.change (e) =>
@backend_status.fadeOut 'slow'
@squad_name_input.blur (e) =>
@squad_name_input.change()
@squad_name_save_button.click()
@squad_name_display.click (e) =>
e.preventDefault()
@squad_name_display.hide()
@squad_name_input.val $.trim(@current_squad.name)
# Because Firefox handles this badly
window.setTimeout () =>
@squad_name_input.focus()
@squad_name_input.select()
, 100
@squad_name_input.closest('div').show()
@squad_name_save_button.click (e) =>
e.preventDefault()
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
name = @current_squad.name = $.trim(@squad_name_input.val())
if name.length > 0
@squad_name_display.show()
@container.trigger 'xwing-backend:squadNameChanged'
@squad_name_input.closest('div').hide()
@randomizer_options_modal = $ document.createElement('DIV')
@randomizer_options_modal.addClass 'modal hide fade'
$('body').append @randomizer_options_modal
@randomizer_options_modal.append $.trim """
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Random Squad Builder Options</h3>
</div>
<div class="modal-body">
<form>
<label>
Desired Points
<input type="number" class="randomizer-points" value="#{DEFAULT_RANDOMIZER_POINTS}" placeholder="#{DEFAULT_RANDOMIZER_POINTS}" />
</label>
<label>
Sets and Expansions (default all)
<select class="randomizer-sources" multiple="1" data-placeholder="Use all sets and expansions">
</select>
</label>
<label>
Maximum Seconds to Spend Randomizing
<input type="number" class="randomizer-timeout" value="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" placeholder="#{DEFAULT_RANDOMIZER_TIMEOUT_SEC}" />
</label>
<label>
Maximum Randomization Iterations
<input type="number" class="randomizer-iterations" value="#{DEFAULT_RANDOMIZER_ITERATIONS}" placeholder="#{DEFAULT_RANDOMIZER_ITERATIONS}" />
</label>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary do-randomize" aria-hidden="true">Randomize!</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@randomizer_source_selector = $ @randomizer_options_modal.find('select.randomizer-sources')
for expansion in exportObj.expansions
opt = $ document.createElement('OPTION')
opt.text expansion
@randomizer_source_selector.append opt
@randomizer_source_selector.select2
width: "100%"
minimumResultsForSearch: if $.isMobile() then -1 else 0
@randomize_button.click (e) =>
e.preventDefault()
if @current_squad.dirty and @backend?
@backend.warnUnsaved this, () =>
@randomize_button.click()
else
points = parseInt $(@randomizer_options_modal.find('.randomizer-points')).val()
points = DEFAULT_RANDOMIZER_POINTS if (isNaN(points) or points <= 0)
timeout_sec = parseInt $(@randomizer_options_modal.find('.randomizer-timeout')).val()
timeout_sec = DEFAULT_RANDOMIZER_TIMEOUT_SEC if (isNaN(timeout_sec) or timeout_sec <= 0)
iterations = parseInt $(@randomizer_options_modal.find('.randomizer-iterations')).val()
iterations = DEFAULT_RANDOMIZER_ITERATIONS if (isNaN(iterations) or iterations <= 0)
#console.log "points=#{points}, sources=#{@randomizer_source_selector.val()}, timeout=#{timeout_sec}, iterations=#{iterations}"
@randomSquad(points, @randomizer_source_selector.val(), DEFAULT_RANDOMIZER_TIMEOUT_SEC * 1000, iterations)
@randomizer_options_modal.find('button.do-randomize').click (e) =>
e.preventDefault()
@randomizer_options_modal.modal('hide')
@randomize_button.click()
@customize_randomizer.click (e) =>
e.preventDefault()
@randomizer_options_modal.modal()
@choose_obstacles_modal = $ document.createElement 'DIV'
@choose_obstacles_modal.addClass 'modal hide fade choose-obstacles-modal'
@container.append @choose_obstacles_modal
@choose_obstacles_modal.append $.trim """
<div class="modal-header">
<label class='choose-obstacles-description'>Choose up to three obstacles, to include in the permalink for use in external programs</label>
</div>
<div class="modal-body">
<div class="obstacle-select-container" style="float:left">
<select multiple class='obstacle-select' size="18">
<option class="coreasteroid0-select" value="coreasteroid0">Core Asteroid 0</option>
<option class="coreasteroid1-select" value="coreasteroid1">Core Asteroid 1</option>
<option class="coreasteroid2-select" value="coreasteroid2">Core Asteroid 2</option>
<option class="coreasteroid3-select" value="coreasteroid3">Core Asteroid 3</option>
<option class="coreasteroid4-select" value="coreasteroid4">Core Asteroid 4</option>
<option class="coreasteroid5-select" value="coreasteroid5">Core Asteroid 5</option>
<option class="yt2400debris0-select" value="yt2400debris0">YT2400 Debris 0</option>
<option class="yt2400debris1-select" value="yt2400debris1">YT2400 Debris 1</option>
<option class="yt2400debris2-select" value="yt2400debris2">YT2400 Debris 2</option>
<option class="vt49decimatordebris0-select" value="vt49decimatordebris0">VT49 Debris 0</option>
<option class="vt49decimatordebris1-select" value="vt49decimatordebris1">VT49 Debris 1</option>
<option class="vt49decimatordebris2-select" value="vt49decimatordebris2">VT49 Debris 2</option>
<option class="core2asteroid0-select" value="core2asteroid0">Force Awakens Asteroid 0</option>
<option class="core2asteroid1-select" value="core2asteroid1">Force Awakens Asteroid 1</option>
<option class="core2asteroid2-select" value="core2asteroid2">Force Awakens Asteroid 2</option>
<option class="core2asteroid3-select" value="core2asteroid3">Force Awakens Asteroid 3</option>
<option class="core2asteroid4-select" value="core2asteroid4">Force Awakens Asteroid 4</option>
<option class="core2asteroid5-select" value="core2asteroid5">Force Awakens Asteroid 5</option>
</select>
</div>
<div class="obstacle-image-container" style="display:none;">
<img class="obstacle-image" src="images/core2asteroid0.png" />
</div>
</div>
<div class="modal-footer hidden-print">
<button class="btn close-print-dialog" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
"""
@obstacles_select = @choose_obstacles_modal.find('.obstacle-select')
@obstacles_select_image = @choose_obstacles_modal.find('.obstacle-image-container')
# Backend
@backend_list_squads_button = $ @container.find('button.backend-list-my-squads')
@backend_list_squads_button.click (e) =>
e.preventDefault()
if @backend?
@backend.list this
#@backend_list_all_squads_button = $ @container.find('button.backend-list-all-squads')
#@backend_list_all_squads_button.click (e) =>
# e.preventDefault()
# if @backend?
# @backend.list this, true
@backend_save_list_button = $ @container.find('button.save-list')
@backend_save_list_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_save_list_button.hasClass('disabled')
additional_data =
points: @total_points
description: @describeSquad()
cards: @listCards()
notes: @notes.val().substr(0, 1024)
obstacles: @getObstacles()
@backend_status.html $.trim """
<i class="fa fa-refresh fa-spin"></i> Saving squad...
"""
@backend_status.show()
@backend_save_list_button.addClass 'disabled'
await @backend.save @serialize(), @current_squad.id, @current_squad.name, @faction, additional_data, defer(results)
if results.success
@current_squad.dirty = false
if @current_squad.id?
@backend_status.html $.trim """
<i class="fa fa-check"></i> Squad updated successfully.
"""
else
@backend_status.html $.trim """
<i class="fa fa-check"></i> New squad saved successfully.
"""
@current_squad.id = results.id
@container.trigger 'xwing-backend:squadDirtinessChanged'
else
@backend_status.html $.trim """
<i class="fa fa-exclamation-circle"></i> #{results.error}
"""
@backend_save_list_button.removeClass 'disabled'
@backend_save_list_as_button = $ @container.find('button.save-list-as')
@backend_save_list_as_button.addClass 'disabled'
@backend_save_list_as_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_save_list_as_button.hasClass('disabled')
@backend.showSaveAsModal this
@backend_delete_list_button = $ @container.find('button.delete-list')
@backend_delete_list_button.click (e) =>
e.preventDefault()
if @backend? and not @backend_delete_list_button.hasClass('disabled')
@backend.showDeleteModal this
content_container = $ document.createElement 'DIV'
content_container.addClass 'container-fluid'
@container.append content_container
content_container.append $.trim """
<div class="row-fluid">
<div class="span9 ship-container">
<label class="notes-container show-authenticated">
<span>Squad Notes:</span>
<br />
<textarea class="squad-notes"></textarea>
</label>
<span class="obstacles-container">
<button class="btn btn-primary choose-obstacles">Choose Obstacles</button>
</span>
</div>
<div class="span3 info-container" />
</div>
"""
@ship_container = $ content_container.find('div.ship-container')
@info_container = $ content_container.find('div.info-container')
@obstacles_container = content_container.find('.obstacles-container')
@notes_container = $ content_container.find('.notes-container')
@notes = $ @notes_container.find('textarea.squad-notes')
@info_container.append $.trim """
<div class="well well-small info-well">
<span class="info-name"></span>
<br />
<span class="info-sources"></span>
<br />
<span class="info-collection"></span>
<table>
<tbody>
<tr class="info-ship">
<td class="info-header">Ship</td>
<td class="info-data"></td>
</tr>
<tr class="info-skill">
<td class="info-header">Initiative</td>
<td class="info-data info-skill"></td>
</tr>
<tr class="info-energy">
<td class="info-header"><i class="xwing-miniatures-font header-energy xwing-miniatures-font-energy"></i></td>
<td class="info-data info-energy"></td>
</tr>
<tr class="info-attack">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-frontarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-fullfront">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-fullfrontarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-bullseye">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-bullseyearc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-back">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-reararc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-turret">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-singleturretarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-attack-doubleturret">
<td class="info-header"><i class="xwing-miniatures-font header-attack xwing-miniatures-font-doubleturretarc"></i></td>
<td class="info-data info-attack"></td>
</tr>
<tr class="info-agility">
<td class="info-header"><i class="xwing-miniatures-font header-agility xwing-miniatures-font-agility"></i></td>
<td class="info-data info-agility"></td>
</tr>
<tr class="info-hull">
<td class="info-header"><i class="xwing-miniatures-font header-hull xwing-miniatures-font-hull"></i></td>
<td class="info-data info-hull"></td>
</tr>
<tr class="info-shields">
<td class="info-header"><i class="xwing-miniatures-font header-shield xwing-miniatures-font-shield"></i></td>
<td class="info-data info-shields"></td>
</tr>
<tr class="info-force">
<td class="info-header"><i class="xwing-miniatures-font header-force xwing-miniatures-font-forcecharge"></i></td>
<td class="info-data info-force"></td>
</tr>
<tr class="info-charge">
<td class="info-header"><i class="xwing-miniatures-font header-charge xwing-miniatures-font-charge"></i></td>
<td class="info-data info-charge"></td>
</tr>
<tr class="info-range">
<td class="info-header">Range</td>
<td class="info-data info-range"></td>
</tr>
<tr class="info-actions">
<td class="info-header">Actions</td>
<td class="info-data"></td>
</tr>
<tr class="info-actions-red">
<td></td>
<td class="info-data-red"></td>
</tr>
<tr class="info-upgrades">
<td class="info-header">Upgrades</td>
<td class="info-data"></td>
</tr>
</tbody>
</table>
<p class="info-text" />
<p class="info-maneuvers" />
</div>
"""
@info_container.hide()
@print_list_button = $ @container.find('button.print-list')
@container.find('[rel=tooltip]').tooltip()
# obstacles
@obstacles_button = $ @container.find('button.choose-obstacles')
@obstacles_button.click (e) =>
e.preventDefault()
@showChooseObstaclesModal()
# conditions
@condition_container = $ document.createElement('div')
@condition_container.addClass 'conditions-container'
@container.append @condition_container
setupEventHandlers: ->
@container.on 'xwing:claimUnique', (e, unique, type, cb) =>
@claimUnique unique, type, cb
.on 'xwing:releaseUnique', (e, unique, type, cb) =>
@releaseUnique unique, type, cb
.on 'xwing:pointsUpdated', (e, cb=$.noop) =>
if @isUpdatingPoints
cb()
else
@isUpdatingPoints = true
@onPointsUpdated () =>
@isUpdatingPoints = false
cb()
.on 'xwing-backend:squadLoadRequested', (e, squad) =>
@onSquadLoadRequested squad
.on 'xwing-backend:squadDirtinessChanged', (e) =>
@onSquadDirtinessChanged()
.on 'xwing-backend:squadNameChanged', (e) =>
@onSquadNameChanged()
.on 'xwing:beforeLanguageLoad', (e, cb=$.noop) =>
@pretranslation_serialized = @serialize()
# Need to remove ships here because the cards will change when the
# new language is loaded, and we don't want to have problems with
# unclaiming uniques.
# Preserve squad dirtiness
old_dirty = @current_squad.dirty
@removeAllShips()
@current_squad.dirty = old_dirty
cb()
.on 'xwing:afterLanguageLoad', (e, language, cb=$.noop) =>
@language = language
old_dirty = @current_squad.dirty
@loadFromSerialized @pretranslation_serialized
for ship in @ships
ship.updateSelections()
@current_squad.dirty = old_dirty
@pretranslation_serialized = undefined
cb()
# Recently moved this here. Did this ever work?
.on 'xwing:shipUpdated', (e, cb=$.noop) =>
all_allocated = true
for ship in @ships
ship.updateSelections()
if ship.ship_selector.val() == ''
all_allocated = false
#console.log "all_allocated is #{all_allocated}, suppress_automatic_new_ship is #{@suppress_automatic_new_ship}"
#console.log "should we add ship: #{all_allocated and not @suppress_automatic_new_ship}"
@addShip() if all_allocated and not @suppress_automatic_new_ship
$(window).on 'xwing-backend:authenticationChanged', (e) =>
@resetCurrentSquad()
.on 'xwing-collection:created', (e, collection) =>
# console.log "#{@faction}: collection was created"
@collection = collection
# console.log "#{@faction}: Collection created, checking squad"
@collection.onLanguageChange null, @language
@checkCollection()
@collection_button.removeClass 'hidden'
.on 'xwing-collection:changed', (e, collection) =>
# console.log "#{@faction}: Collection changed, checking squad"
@checkCollection()
.on 'xwing-collection:destroyed', (e, collection) =>
@collection = null
@collection_button.addClass 'hidden'
.on 'xwing:pingActiveBuilder', (e, cb) =>
cb(this) if @container.is(':visible')
.on 'xwing:activateBuilder', (e, faction, cb) =>
if faction == @faction
@tab.tab('show')
cb this
@obstacles_select.change (e) =>
if @obstacles_select.val().length > 3
@obstacles_select.val(@current_squad.additional_data.obstacles)
else
previous_obstacles = @current_squad.additional_data.obstacles
@current_obstacles = (o for o in @obstacles_select.val())
if (previous_obstacles?)
new_selection = @current_obstacles.filter((element) => return previous_obstacles.indexOf(element) == -1)
else
new_selection = @current_obstacles
if new_selection.length > 0
@showChooseObstaclesSelectImage(new_selection[0])
@current_squad.additional_data.obstacles = @current_obstacles
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
@view_list_button.click (e) =>
e.preventDefault()
@showTextListModal()
@print_list_button.click (e) =>
e.preventDefault()
# Copy text list to printable
@printable_container.find('.printable-header').html @list_modal.find('.modal-header').html()
@printable_container.find('.printable-body').text ''
switch @list_display_mode
when 'simple'
@printable_container.find('.printable-body').html @simple_container.html()
else
for ship in @ships
@printable_container.find('.printable-body').append ship.toHTML() if ship.pilot?
@printable_container.find('.fancy-ship').toggleClass 'tall', @list_modal.find('.toggle-vertical-space').prop('checked')
@printable_container.find('.printable-body').toggleClass 'bw', not @list_modal.find('.toggle-color-print').prop('checked')
faction = switch @faction
when 'Rebel Alliance'
'rebel'
when 'Galactic Empire'
'empire'
when 'Scum and Villainy'
'scum'
@printable_container.find('.squad-faction').html """<i class="xwing-miniatures-font xwing-miniatures-font-#{faction}"></i>"""
# Conditions
@printable_container.find('.printable-body').append $.trim """
<div class="print-conditions"></div>
"""
@printable_container.find('.printable-body .print-conditions').html @condition_container.html()
# Notes, if present
if $.trim(@notes.val()) != ''
@printable_container.find('.printable-body').append $.trim """
<h5 class="print-notes">Notes:</h5>
<pre class="print-notes"></pre>
"""
@printable_container.find('.printable-body pre.print-notes').text @notes.val()
# Obstacles
if @list_modal.find('.toggle-obstacles').prop('checked')
@printable_container.find('.printable-body').append $.trim """
<div class="obstacles">
<div>Mark the three obstacles you are using.</div>
<img class="obstacle-silhouettes" src="images/xws-obstacles.png" />
<div>Mark which damage deck you are using.</div>
<div><i class="fa fa-square-o"></i>Original Core Set   <i class="fa fa-square-o"></i>The Force Awakens Core Set</div>
</div>
"""
# Add List Juggler QR code
query = @getPermaLinkParams(['sn', 'obs'])
if query? and @list_modal.find('.toggle-juggler-qrcode').prop('checked')
@printable_container.find('.printable-body').append $.trim """
<div class="qrcode-container">
<div class="permalink-container">
<div class="qrcode"></div>
<div class="qrcode-text">Scan to open this list in the builder</div>
</div>
<div class="juggler-container">
<div class="qrcode"></div>
<div class="qrcode-text">TOs: Scan to load this squad into List Juggler</div>
</div>
</div>
"""
text = "https://yasb-xws.herokuapp.com/juggler#{query}"
@printable_container.find('.juggler-container .qrcode').qrcode
render: 'div'
ec: 'M'
size: if text.length < 144 then 144 else 160
text: text
text = "https://geordanr.github.io/xwing/#{query}"
@printable_container.find('.permalink-container .qrcode').qrcode
render: 'div'
ec: 'M'
size: if text.length < 144 then 144 else 160
text: text
window.print()
$(window).resize =>
@select_simple_view_button.click() if $(window).width() < 768 and @list_display_mode != 'simple'
@notes.change @onNotesUpdated
@notes.on 'keyup', @onNotesUpdated
getPermaLinkParams: (ignored_params=[]) =>
params = {}
params.f = encodeURI(@faction) unless 'f' in ignored_params
params.d = encodeURI(@serialize()) unless 'd' in ignored_params
params.sn = encodeURIComponent(@current_squad.name) unless 'sn' in ignored_params
params.obs = encodeURI(@current_squad.additional_data.obstacles || '') unless 'obs' in ignored_params
return "?" + ("#{k}=#{v}" for k, v of params).join("&")
getPermaLink: (params=@getPermaLinkParams()) => "#{URL_BASE}#{params}"
updatePermaLink: () =>
return unless @container.is(':visible') # gross but couldn't make clearInterval work
next_params = @getPermaLinkParams()
if window.location.search != next_params
window.history.replaceState(next_params, '', @getPermaLink(next_params))
onNotesUpdated: =>
if @total_points > 0
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
onGameTypeChanged: (gametype, cb=$.noop) =>
switch gametype
when 'standard'
@isEpic = false
@isCustom = false
@desired_points_input.val 200
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
when 'custom'
@isEpic = false
@isCustom = true
@maxSmallShipsOfOneType = null
@maxLargeShipsOfOneType = null
@max_epic_points_span.text @maxEpicPointsAllowed
@onPointsUpdated cb
onPointsUpdated: (cb=$.noop) =>
@total_points = 0
@total_epic_points = 0
unreleased_content_used = false
epic_content_used = false
for ship, i in @ships
ship.validate()
@total_points += ship.getPoints()
@total_epic_points += ship.getEpicPoints()
ship_uses_unreleased_content = ship.checkUnreleasedContent()
unreleased_content_used = ship_uses_unreleased_content if ship_uses_unreleased_content
ship_uses_epic_content = ship.checkEpicContent()
epic_content_used = ship_uses_epic_content if ship_uses_epic_content
@total_points_span.text @total_points
points_left = parseInt(@desired_points_input.val()) - @total_points
@points_remaining_span.text points_left
@points_remaining_container.toggleClass 'red', (points_left < 0)
@unreleased_content_used_container.toggleClass 'hidden', not unreleased_content_used
@epic_content_used_container.toggleClass 'hidden', (@isEpic or not epic_content_used)
# Check against Epic restrictions if applicable
@illegal_epic_upgrades_container.toggleClass 'hidden', true
@too_many_small_ships_container.toggleClass 'hidden', true
@too_many_large_ships_container.toggleClass 'hidden', true
@total_epic_points_container.toggleClass 'hidden', true
if @isEpic
@total_epic_points_container.toggleClass 'hidden', false
@total_epic_points_span.text @total_epic_points
@total_epic_points_span.toggleClass 'red', (@total_epic_points > @maxEpicPointsAllowed)
shipCountsByType = {}
illegal_for_epic = false
for ship, i in @ships
if ship?.data?
shipCountsByType[ship.data.name] ?= 0
shipCountsByType[ship.data.name] += 1
if ship.data.huge?
for upgrade in ship.upgrades
if upgrade?.data?.epic_restriction_func?
unless upgrade.data.epic_restriction_func(ship.data, upgrade)
illegal_for_epic = true
break
break if illegal_for_epic
@illegal_epic_upgrades_container.toggleClass 'hidden', not illegal_for_epic
if @maxLargeShipsOfOneType? and @maxSmallShipsOfOneType?
for ship_name, count of shipCountsByType
ship_data = exportObj.ships[ship_name]
if ship_data.large? and count > @maxLargeShipsOfOneType
@too_many_large_ships_container.toggleClass 'hidden', false
else if not ship.huge? and count > @maxSmallShipsOfOneType
@too_many_small_ships_container.toggleClass 'hidden', false
@fancy_total_points_container.text @total_points
# update text list
@fancy_container.text ''
@simple_container.html '<table class="simple-table"></table>'
bbcode_ships = []
htmlview_ships = []
for ship in @ships
if ship.pilot?
@fancy_container.append ship.toHTML()
@simple_container.find('table').append ship.toTableRow()
bbcode_ships.push ship.toBBCode()
htmlview_ships.push ship.toSimpleHTML()
@htmlview_container.find('textarea').val $.trim """#{htmlview_ships.join '<br />'}
<br />
<b><i>Total: #{@total_points}</i></b>
<br />
<a href="#{@getPermaLink()}">View in Yet Another Squad Builder</a>
"""
@bbcode_container.find('textarea').val $.trim """#{bbcode_ships.join "\n\n"}
[b][i]Total: #{@total_points}[/i][/b]
[url=#{@getPermaLink()}]View in Yet Another Squad Builder[/url]
"""
# console.log "#{@faction}: Squad updated, checking collection"
@checkCollection()
# update conditions used
# this old version of phantomjs i'm using doesn't support Set
if Set?
conditions_set = new Set()
for ship in @ships
# shouldn't there be a set union
ship.getConditions().forEach (condition) ->
conditions_set.add(condition)
conditions = []
conditions_set.forEach (condition) ->
conditions.push(condition)
conditions.sort (a, b) ->
if a.name.canonicalize() < b.name.canonicalize()
-1
else if b.name.canonicalize() > a.name.canonicalize()
1
else
0
@condition_container.text ''
conditions.forEach (condition) =>
@condition_container.append conditionToHTML(condition)
cb @total_points
onSquadLoadRequested: (squad) =>
console.log(squad.additional_data.obstacles)
@current_squad = squad
@backend_delete_list_button.removeClass 'disabled'
@squad_name_input.val @current_squad.name
@squad_name_placeholder.text @current_squad.name
@current_obstacles = @current_squad.additional_data.obstacles
@updateObstacleSelect(@current_squad.additional_data.obstacles)
@loadFromSerialized squad.serialized
@notes.val(squad.additional_data.notes ? '')
@backend_status.fadeOut 'slow'
@current_squad.dirty = false
@container.trigger 'xwing-backend:squadDirtinessChanged'
onSquadDirtinessChanged: () =>
@backend_save_list_button.toggleClass 'disabled', not (@current_squad.dirty and @total_points > 0)
@backend_save_list_as_button.toggleClass 'disabled', @total_points == 0
@backend_delete_list_button.toggleClass 'disabled', not @current_squad.id?
onSquadNameChanged: () =>
if @current_squad.name.length > SQUAD_DISPLAY_NAME_MAX_LENGTH
short_name = "#{@current_squad.name.substr(0, SQUAD_DISPLAY_NAME_MAX_LENGTH)}…"
else
short_name = @current_squad.name
@squad_name_placeholder.text ''
@squad_name_placeholder.append short_name
@squad_name_input.val @current_squad.name
removeAllShips: ->
while @ships.length > 0
@removeShip @ships[0]
throw new Error("Ships not emptied") if @ships.length > 0
showTextListModal: ->
# Display modal
@list_modal.modal 'show'
showChooseObstaclesModal: ->
@obstacles_select.val(@current_squad.additional_data.obstacles)
@choose_obstacles_modal.modal 'show'
showChooseObstaclesSelectImage: (obstacle) ->
@image_name = 'images/' + obstacle + '.png'
@obstacles_select_image.find('.obstacle-image').attr 'src', @image_name
@obstacles_select_image.show()
updateObstacleSelect: (obstacles) ->
@current_obstacles = obstacles
@obstacles_select.val(obstacles)
serialize: ->
#( "#{ship.pilot.id}:#{ship.upgrades[i].data?.id ? -1 for slot, i in ship.pilot.slots}:#{ship.title?.data?.id ? -1}:#{upgrade.data?.id ? -1 for upgrade in ship.title?.conferredUpgrades ? []}:#{ship.modification?.data?.id ? -1}" for ship in @ships when ship.pilot? ).join ';'
serialization_version = 4
game_type_abbrev = switch @game_type_selector.val()
when 'standard'
's'
when 'custom'
"c=#{$.trim @desired_points_input.val()}"
"""v#{serialization_version}!#{game_type_abbrev}!#{( ship.toSerialized() for ship in @ships when ship.pilot? ).join ';'}"""
loadFromSerialized: (serialized) ->
@suppress_automatic_new_ship = true
# Clear all existing ships
@removeAllShips()
re = /^v(\d+)!(.*)/
matches = re.exec serialized
if matches?
# versioned
version = parseInt matches[1]
switch version
when 3, 4
# parse out game type
[ game_type_abbrev, serialized_ships ] = matches[2].split('!')
switch game_type_abbrev
when 's'
@game_type_selector.val 'standard'
@game_type_selector.change()
else
@game_type_selector.val 'custom'
@desired_points_input.val parseInt(game_type_abbrev.split('=')[1])
@desired_points_input.change()
for serialized_ship in serialized_ships.split(';')
unless serialized_ship == ''
new_ship = @addShip()
new_ship.fromSerialized version, serialized_ship
when 2
for serialized_ship in matches[2].split(';')
unless serialized_ship == ''
new_ship = @addShip()
new_ship.fromSerialized version, serialized_ship
else
# v1 (unversioned)
for serialized_ship in serialized.split(';')
unless serialized == ''
new_ship = @addShip()
new_ship.fromSerialized 1, serialized_ship
@suppress_automatic_new_ship = false
# Finally, the unassigned ship
@addShip()
uniqueIndex: (unique, type) ->
if type not of @uniques_in_use
throw new Error("Invalid unique type '#{type}'")
@uniques_in_use[type].indexOf unique
claimUnique: (unique, type, cb) =>
if @uniqueIndex(unique, type) < 0
# Claim pilots with the same canonical name
for other in (exportObj.pilotsByUniqueName[unique.canonical_name.getXWSBaseName()] or [])
if unique != other
if @uniqueIndex(other, 'Pilot') < 0
# console.log "Also claiming unique pilot #{other.canonical_name} in use"
@uniques_in_use['Pilot'].push other
else
throw new Error("Unique #{type} '#{unique.name}' already claimed as pilot")
# Claim other upgrades with the same canonical name
for otherslot, bycanonical of exportObj.upgradesBySlotUniqueName
for canonical, other of bycanonical
if canonical.getXWSBaseName() == unique.canonical_name.getXWSBaseName() and unique != other
if @uniqueIndex(other, 'Upgrade') < 0
# console.log "Also claiming unique #{other.canonical_name} (#{otherslot}) in use"
@uniques_in_use['Upgrade'].push other
# else
# throw new Error("Unique #{type} '#{unique.name}' already claimed as #{otherslot}")
@uniques_in_use[type].push unique
else
throw new Error("Unique #{type} '#{unique.name}' already claimed")
cb()
releaseUnique: (unique, type, cb) =>
idx = @uniqueIndex(unique, type)
if idx >= 0
# Release all uniques with the same canonical name and base name
for type, uniques of @uniques_in_use
# Removing stuff in a loop sucks, so we'll construct a new list
@uniques_in_use[type] = []
for u in uniques
if u.canonical_name.getXWSBaseName() != unique.canonical_name.getXWSBaseName()
# Keep this one
@uniques_in_use[type].push u
# else
# console.log "Releasing #{u.name} (#{type}) with canonical name #{unique.canonical_name}"
else
throw new Error("Unique #{type} '#{unique.name}' not in use")
cb()
addShip: ->
new_ship = new Ship
builder: this
container: @ship_container
@ships.push new_ship
new_ship
removeShip: (ship) ->
await ship.destroy defer()
await @container.trigger 'xwing:pointsUpdated', defer()
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadDirtinessChanged'
matcher: (item, term) ->
item.toUpperCase().indexOf(term.toUpperCase()) >= 0
isOurFaction: (faction) ->
if faction instanceof Array
for f in faction
if getPrimaryFaction(f) == @faction
return true
false
else
getPrimaryFaction(faction) == @faction
getAvailableShipsMatching: (term='') ->
ships = []
for ship_name, ship_data of exportObj.ships
if @isOurFaction(ship_data.factions) and @matcher(ship_data.name, term)
if not ship_data.huge or (@isEpic or @isCustom)
ships.push
id: ship_data.name
text: ship_data.name
english_name: ship_data.english_name
canonical_name: ship_data.canonical_name
ships.sort exportObj.sortHelper
getAvailablePilotsForShipIncluding: (ship, include_pilot, term='') ->
# Returns data formatted for Select2
available_faction_pilots = (pilot for pilot_name, pilot of exportObj.pilotsByLocalizedName when (not ship? or pilot.ship == ship) and @isOurFaction(pilot.faction) and @matcher(pilot_name, term))
eligible_faction_pilots = (pilot for pilot_name, pilot of available_faction_pilots when (not pilot.unique? or pilot not in @uniques_in_use['Pilot'] or pilot.canonical_name.getXWSBaseName() == include_pilot?.canonical_name.getXWSBaseName()))
# Re-add selected pilot
if include_pilot? and include_pilot.unique? and @matcher(include_pilot.name, term)
eligible_faction_pilots.push include_pilot
({ id: pilot.id, text: "#{pilot.name} (#{pilot.points})", points: pilot.points, ship: pilot.ship, english_name: pilot.english_name, disabled: pilot not in eligible_faction_pilots } for pilot in available_faction_pilots).sort exportObj.sortHelper
dfl_filter_func = ->
true
countUpgrades: (canonical_name) ->
# returns number of upgrades with given canonical name equipped
count = 0
for ship in @ships
for upgrade in ship.upgrades
if upgrade?.data?.canonical_name == canonical_name
count++
count
getAvailableUpgradesIncluding: (slot, include_upgrade, ship, this_upgrade_obj, term='', filter_func=@dfl_filter_func) ->
# Returns data formatted for Select2
limited_upgrades_in_use = (upgrade.data for upgrade in ship.upgrades when upgrade?.data?.limited?)
available_upgrades = (upgrade for upgrade_name, upgrade of exportObj.upgradesByLocalizedName when upgrade.slot == slot and @matcher(upgrade_name, term) and (not upgrade.ship? or upgrade.ship == ship.data.name) and (not upgrade.faction? or @isOurFaction(upgrade.faction)))
if filter_func != @dfl_filter_func
available_upgrades = (upgrade for upgrade in available_upgrades when filter_func(upgrade))
# Special case #3
eligible_upgrades = (upgrade for upgrade_name, upgrade of available_upgrades when (not upgrade.unique? or upgrade not in @uniques_in_use['Upgrade']) and (not (ship? and upgrade.restriction_func?) or upgrade.restriction_func(ship, this_upgrade_obj)) and upgrade not in limited_upgrades_in_use and ((not upgrade.max_per_squad?) or ship.builder.countUpgrades(upgrade.canonical_name) < upgrade.max_per_squad))
# Special case #2 :(
# current_upgrade_forcibly_removed = false
#for title in ship?.titles ? []
# if title?.data?.special_case == 'A-Wing Test Pilot'
# for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?)
# eligible_upgrades.removeItem equipped_upgrade
# current_upgrade_forcibly_removed = true if equipped_upgrade == include_upgrade
for equipped_upgrade in (upgrade.data for upgrade in ship.upgrades when upgrade?.data?)
eligible_upgrades.removeItem equipped_upgrade
# Re-enable selected upgrade
if include_upgrade? and (((include_upgrade.unique? or include_upgrade.limited? or include_upgrade.max_per_squad?) and @matcher(include_upgrade.name, term)))# or current_upgrade_forcibly_removed)
# available_upgrades.push include_upgrade
eligible_upgrades.push include_upgrade
retval = ({ id: upgrade.id, text: "#{upgrade.name} (#{upgrade.points})", points: upgrade.points, english_name: upgrade.english_name, disabled: upgrade not in eligible_upgrades } for upgrade in available_upgrades).sort exportObj.sortHelper
# Possibly adjust the upgrade
if this_upgrade_obj.adjustment_func?
(this_upgrade_obj.adjustment_func(upgrade) for upgrade in retval)
else
retval
getAvailableModificationsIncluding: (include_modification, ship, term='', filter_func=@dfl_filter_func) ->
# Returns data formatted for Select2
limited_modifications_in_use = (modification.data for modification in ship.modifications when modification?.data?.limited?)
available_modifications = (modification for modification_name, modification of exportObj.modificationsByLocalizedName when @matcher(modification_name, term) and (not modification.ship? or modification.ship == ship.data.name))
if filter_func != @dfl_filter_func
available_modifications = (modification for modification in available_modifications when filter_func(modification))
if ship? and exportObj.hugeOnly(ship) > 0
# Only show allowed mods for Epic ships
available_modifications = (modification for modification in available_modifications when modification.ship? or not modification.restriction_func? or modification.restriction_func ship)
eligible_modifications = (modification for modification_name, modification of available_modifications when (not modification.unique? or modification not in @uniques_in_use['Modification']) and (not modification.faction? or @isOurFaction(modification.faction)) and (not (ship? and modification.restriction_func?) or modification.restriction_func ship) and modification not in limited_modifications_in_use)
# I finally had to add a special case :( If something else demands it
# then I will try to make this more systematic, but I haven't come up
# with a good solution... yet.
# current_mod_forcibly_removed = false
for thing in (ship?.titles ? []).concat(ship?.upgrades ? [])
if thing?.data?.special_case == 'Royal Guard TIE'
# Need to refetch by ID because Vaksai may have modified its cost
for equipped_modification in (modificationsById[modification.data.id] for modification in ship.modifications when modification?.data?)
eligible_modifications.removeItem equipped_modification
# current_mod_forcibly_removed = true if equipped_modification == include_modification
# Re-add selected modification
if include_modification? and (((include_modification.unique? or include_modification.limited?) and @matcher(include_modification.name, term)))# or current_mod_forcibly_removed)
eligible_modifications.push include_modification
({ id: modification.id, text: "#{modification.name} (#{modification.points})", points: modification.points, english_name: modification.english_name, disabled: modification not in eligible_modifications } for modification in available_modifications).sort exportObj.sortHelper
getAvailableTitlesIncluding: (ship, include_title, term='') ->
# Returns data formatted for Select2
# Titles are no longer unique!
limited_titles_in_use = (title.data for title in ship.titles when title?.data?.limited?)
available_titles = (title for title_name, title of exportObj.titlesByLocalizedName when (not title.ship? or title.ship == ship.data.name) and @matcher(title_name, term))
eligible_titles = (title for title_name, title of available_titles when (not title.unique? or (title not in @uniques_in_use['Title'] and title.canonical_name.getXWSBaseName() not in (t.canonical_name.getXWSBaseName() for t in @uniques_in_use['Title'])) or title.canonical_name.getXWSBaseName() == include_title?.canonical_name.getXWSBaseName()) and (not title.faction? or @isOurFaction(title.faction)) and (not (ship? and title.restriction_func?) or title.restriction_func ship) and title not in limited_titles_in_use)
# Re-add selected title
if include_title? and (((include_title.unique? or include_title.limited?) and @matcher(include_title.name, term)))
eligible_titles.push include_title
({ id: title.id, text: "#{title.name} (#{title.points})", points: title.points, english_name: title.english_name, disabled: title not in eligible_titles } for title in available_titles).sort exportObj.sortHelper
# Converts a maneuver table for into an HTML table.
getManeuverTableHTML: (maneuvers, baseManeuvers) ->
if not maneuvers? or maneuvers.length == 0
return "Missing maneuver info."
# Preprocess maneuvers to see which bearings are never used so we
# don't render them.
bearings_without_maneuvers = [0...maneuvers[0].length]
for bearings in maneuvers
for difficulty, bearing in bearings
if difficulty > 0
bearings_without_maneuvers.removeItem bearing
# console.log "bearings without maneuvers:"
# console.dir bearings_without_maneuvers
outTable = "<table><tbody>"
for speed in [maneuvers.length - 1 .. 0]
haveManeuver = false
for v in maneuvers[speed]
if v > 0
haveManeuver = true
break
continue if not haveManeuver
outTable += "<tr><td>#{speed}</td>"
for turn in [0 ... maneuvers[speed].length]
continue if turn in bearings_without_maneuvers
outTable += "<td>"
if maneuvers[speed][turn] > 0
color = switch maneuvers[speed][turn]
when 1 then "white"
when 2 then "dodgerblue"
when 3 then "red"
outTable += """<svg xmlns="http://www.w3.org/2000/svg" width="30px" height="30px" viewBox="0 0 200 200">"""
if speed == 0
outTable += """<rect x="50" y="50" width="100" height="100" style="fill:#{color}" />"""
else
outlineColor = "black"
if maneuvers[speed][turn] != baseManeuvers[speed][turn]
outlineColor = "mediumblue" # highlight manuevers modified by another card (e.g. R2 Astromech makes all 1 & 2 speed maneuvers green)
transform = ""
className = ""
switch turn
when 0
# turn left
linePath = "M160,180 L160,70 80,70"
trianglePath = "M80,100 V40 L30,70 Z"
when 1
# bank left
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(-5 -15) rotate(45 70 90)' "
when 2
# straight
linePath = "M100,180 L100,100 100,80"
trianglePath = "M70,80 H130 L100,30 Z"
when 3
# bank right
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(5 -15) rotate(-45 130 90)' "
when 4
# turn right
linePath = "M40,180 L40,70 120,70"
trianglePath = "M120,100 V40 L170,70 Z"
when 5
# k-turn/u-turn
linePath = "M50,180 L50,100 C50,10 140,10 140,100 L140,120"
trianglePath = "M170,120 H110 L140,180 Z"
when 6
# segnor's loop left
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(0 50)'"
when 7
# segnor's loop right
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(0 50)'"
when 8
# tallon roll left
linePath = "M160,180 L160,70 80,70"
trianglePath = "M60,100 H100 L80,140 Z"
when 9
# tallon roll right
linePath = "M40,180 L40,70 120,70"
trianglePath = "M100,100 H140 L120,140 Z"
when 10
# backward left
linePath = "M50,180 S50,120 120,60"
trianglePath = "M120,100 V40 L170,70 Z"
transform = "transform='translate(5 -15) rotate(-45 130 90)' "
className = 'backwards'
when 11
# backward straight
linePath = "M100,180 L100,100 100,80"
trianglePath = "M70,80 H130 L100,30 Z"
className = 'backwards'
when 12
# backward right
linePath = "M150,180 S150,120 80,60"
trianglePath = "M80,100 V40 L30,70 Z"
transform = "transform='translate(-5 -15) rotate(45 70 90)' "
className = 'backwards'
outTable += $.trim """
<g class="maneuver #{className}">
<path d='#{trianglePath}' fill='#{color}' stroke-width='5' stroke='#{outlineColor}' #{transform}/>
<path stroke-width='25' fill='none' stroke='#{outlineColor}' d='#{linePath}' />
<path stroke-width='15' fill='none' stroke='#{color}' d='#{linePath}' />
</g>
"""
outTable += "</svg>"
outTable += "</td>"
outTable += "</tr>"
outTable += "</tbody></table>"
outTable
showTooltip: (type, data, additional_opts) ->
if data != @tooltip_currently_displaying
switch type
when 'Ship'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.pilot.sources).sort().join(', ')
if @collection?.counts?
ship_count = @collection.counts?.ship?[data.data.english_name] ? 0
pilot_count = @collection.counts?.pilot?[data.pilot.english_name] ? 0
@info_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection."""
else
@info_container.find('.info-collection').text ''
effective_stats = data.effectiveStats()
extra_actions = $.grep effective_stats.actions, (el, i) ->
el not in (data.pilot.ship_override?.actions ? data.data.actions)
extra_actions_red = $.grep effective_stats.actionsred, (el, i) ->
el not in (data.pilot.ship_override?.actionsred ? data.data.actionsred)
@info_container.find('.info-name').html """#{if data.pilot.unique then "· " else ""}#{data.pilot.name}#{if data.pilot.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data.pilot) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.pilot.text ? ''
@info_container.find('tr.info-ship td.info-data').text data.pilot.ship
@info_container.find('tr.info-ship').show()
@info_container.find('tr.info-skill td.info-data').text statAndEffectiveStat(data.pilot.skill, effective_stats, 'skill')
@info_container.find('tr.info-skill').show()
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-attack')
@info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(data.data.attack_icon ? 'xwing-miniatures-font-attack')
@info_container.find('tr.info-attack td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attack ? data.data.attack), effective_stats, 'attack')
@info_container.find('tr.info-attack').toggle(data.pilot.ship_override?.attack? or data.data.attack?)
@info_container.find('tr.info-attack-fullfront td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackf ? data.data.attackf), effective_stats, 'attackf')
@info_container.find('tr.info-attack-fullfront').toggle(data.pilot.ship_override?.attackf? or data.data.attackf?)
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-back td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackb ? data.data.attackb), effective_stats, 'attackb')
@info_container.find('tr.info-attack-back').toggle(data.pilot.ship_override?.attackb? or data.data.attackb?)
@info_container.find('tr.info-attack-turret td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackt ? data.data.attackt), effective_stats, 'attackt')
@info_container.find('tr.info-attack-turret').toggle(data.pilot.ship_override?.attackt? or data.data.attackt?)
@info_container.find('tr.info-attack-doubleturret td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.attackdt ? data.data.attackdt), effective_stats, 'attackdt')
@info_container.find('tr.info-attack-doubleturret').toggle(data.pilot.ship_override?.attackdt? or data.data.attackdt?)
@info_container.find('tr.info-energy td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.energy ? data.data.energy), effective_stats, 'energy')
@info_container.find('tr.info-energy').toggle(data.pilot.ship_override?.energy? or data.data.energy?)
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-agility td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.agility ? data.data.agility), effective_stats, 'agility')
@info_container.find('tr.info-agility').show()
@info_container.find('tr.info-hull td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.hull ? data.data.hull), effective_stats, 'hull')
@info_container.find('tr.info-hull').show()
@info_container.find('tr.info-shields td.info-data').text statAndEffectiveStat((data.pilot.ship_override?.shields ? data.data.shields), effective_stats, 'shields')
@info_container.find('tr.info-shields').show()
@info_container.find('tr.info-force td.info-data').html (statAndEffectiveStat((data.pilot.ship_override?.force ? data.pilot.force), effective_stats, 'force') + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
if data.pilot.ship_override?.force? or data.pilot.force?
@info_container.find('tr.info-force').show()
else
@info_container.find('tr.info-force').hide()
if data.pilot.charge?
if data.pilot.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.pilot.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
else
@info_container.find('tr.info-charge td.info-data').text data.pilot.charge
@info_container.find('tr.info-charge').show()
else
@info_container.find('tr.info-charge').hide()
@info_container.find('tr.info-actions td.info-data').html (exportObj.translate(@language, 'action', a) for a in (data.pilot.ship_override?.actions ? data.data.actions).concat( ("<strong>#{exportObj.translate @language, 'action', action}</strong>" for action in extra_actions))).join ' '
if data.data.actionsred?
@info_container.find('tr.info-actions-red td.info-data-red').html (exportObj.translate(@language, 'action', a) for a in (data.pilot.ship_override?.actionsred ? data.data.actionsred).concat( ("<strong>#{exportObj.translate @language, 'action', action}</strong>" for action in extra_actions_red))).join ' '
@info_container.find('tr.info-actions-red').toggle(data.data.actionsred?)
@info_container.find('tr.info-actions').show()
@info_container.find('tr.info-upgrades').show()
@info_container.find('tr.info-upgrades td.info-data').text((exportObj.translate(@language, 'slot', slot) for slot in data.pilot.slots).join(', ') or 'None')
@info_container.find('p.info-maneuvers').show()
@info_container.find('p.info-maneuvers').html(@getManeuverTableHTML(effective_stats.maneuvers, data.data.maneuvers))
when 'Pilot'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ')
if @collection?.counts?
pilot_count = @collection.counts?.pilot?[data.english_name] ? 0
ship_count = @collection.counts.ship?[additional_opts.ship] ? 0
@info_container.find('.info-collection').text """You have #{ship_count} ship model#{if ship_count > 1 then 's' else ''} and #{pilot_count} pilot card#{if pilot_count > 1 then 's' else ''} in your collection."""
else
@info_container.find('.info-collection').text ''
@info_container.find('.info-name').html """#{if data.unique then "· " else ""}#{data.name}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.text ? ''
ship = exportObj.ships[data.ship]
@info_container.find('tr.info-ship td.info-data').text data.ship
@info_container.find('tr.info-ship').show()
@info_container.find('tr.info-skill td.info-data').text data.skill
@info_container.find('tr.info-skill').show()
@info_container.find('tr.info-attack td.info-data').text(data.ship_override?.attack ? ship.attack)
@info_container.find('tr.info-attack').toggle(data.ship_override?.attack? or ship.attack?)
@info_container.find('tr.info-attack-fullfront td.info-data').text(ship.attackf)
@info_container.find('tr.info-attack-fullfront').toggle(ship.attackf?)
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-back td.info-data').text(ship.attackb)
@info_container.find('tr.info-attack-back').toggle(ship.attackb?)
@info_container.find('tr.info-attack-turret td.info-data').text(ship.attackt)
@info_container.find('tr.info-attack-turret').toggle(ship.attackt?)
@info_container.find('tr.info-attack-doubleturret td.info-data').text(ship.attackdt)
@info_container.find('tr.info-attack-doubleturret').toggle(ship.attackdt?)
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc')
@info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass(ship.attack_icon ? 'xwing-miniatures-font-frontarc')
@info_container.find('tr.info-energy td.info-data').text(data.ship_override?.energy ? ship.energy)
@info_container.find('tr.info-energy').toggle(data.ship_override?.energy? or ship.energy?)
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-agility td.info-data').text(data.ship_override?.agility ? ship.agility)
@info_container.find('tr.info-agility').show()
@info_container.find('tr.info-hull td.info-data').text(data.ship_override?.hull ? ship.hull)
@info_container.find('tr.info-hull').show()
@info_container.find('tr.info-shields td.info-data').text(data.ship_override?.shields ? ship.shields)
@info_container.find('tr.info-shields').show()
if data.ship_override?.force or data.force?
@info_container.find('tr.info-force td.info-data').html ((data.ship_override?.force ? data.force)+ '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
@info_container.find('tr.info-force').show()
else
@info_container.find('tr.info-force').hide()
if data.charge?
if data.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.charge + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
else
@info_container.find('tr.info-charge td.info-data').text data.charge
@info_container.find('tr.info-charge').show()
else
@info_container.find('tr.info-charge').hide()
@info_container.find('tr.info-actions td.info-data').html (exportObj.translate(@language, 'action', action) for action in (data.ship_override?.actions ? exportObj.ships[data.ship].actions)).join(' ')
if ships[data.ship].actionsred?
@info_container.find('tr.info-actions-red td.info-data-red').html (exportObj.translate(@language, 'action', action) for action in (data.ship_override?.actionsred ? exportObj.ships[data.ship].actionsred)).join(' ')
@info_container.find('tr.info-actions-red').show()
else
@info_container.find('tr.info-actions-red').hide()
@info_container.find('tr.info-actions').show()
@info_container.find('tr.info-upgrades').show()
@info_container.find('tr.info-upgrades td.info-data').text((exportObj.translate(@language, 'slot', slot) for slot in data.slots).join(', ') or 'None')
@info_container.find('p.info-maneuvers').show()
@info_container.find('p.info-maneuvers').html(@getManeuverTableHTML(ship.maneuvers, ship.maneuvers))
when 'Addon'
@info_container.find('.info-sources').text (exportObj.translate(@language, 'sources', source) for source in data.sources).sort().join(', ')
if @collection?.counts?
addon_count = @collection.counts?[additional_opts.addon_type.toLowerCase()]?[data.english_name] ? 0
@info_container.find('.info-collection').text """You have #{addon_count} in your collection."""
else
@info_container.find('.info-collection').text ''
@info_container.find('.info-name').html """#{if data.unique then "· " else ""}#{data.name}#{if data.limited? then " (#{exportObj.translate(@language, 'ui', 'limited')})" else ""}#{if data.epic? then " (#{exportObj.translate(@language, 'ui', 'epic')})" else ""}#{if exportObj.isReleased(data) then "" else " (#{exportObj.translate(@language, 'ui', 'unreleased')})"}"""
@info_container.find('p.info-text').html data.text ? ''
@info_container.find('tr.info-ship').hide()
@info_container.find('tr.info-skill').hide()
if data.energy?
@info_container.find('tr.info-energy td.info-data').text data.energy
@info_container.find('tr.info-energy').show()
else
@info_container.find('tr.info-energy').hide()
if data.attack?
# Attack icons on upgrade cards don't get special icons
# for cls in @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font')[0].classList
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').removeClass(cls) if cls.startsWith('xwing-miniatures-font-frontarc')
# @info_container.find('tr.info-attack td.info-header i.xwing-miniatures-font').addClass('xwing-miniatures-font-frontarc')
@info_container.find('tr.info-attack td.info-data').text data.attack
@info_container.find('tr.info-attack').show()
else
@info_container.find('tr.info-attack').hide()
if data.attackt?
@info_container.find('tr.info-attack-turret td.info-data').text data.attackt
@info_container.find('tr.info-attack-turret').show()
else
@info_container.find('tr.info-attack-turret').hide()
if data.attackbull?
@info_container.find('tr.info-attack-bullseye td.info-data').text data.attackbull
@info_container.find('tr.info-attack-bullseye').show()
else
@info_container.find('tr.info-attack-bullseye').hide()
@info_container.find('tr.info-attack-fullfront').hide()
@info_container.find('tr.info-attack-back').hide()
@info_container.find('tr.info-attack-doubleturret').hide()
if data.recurring?
@info_container.find('tr.info-charge td.info-data').html (data.charge + """<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>""")
else
@info_container.find('tr.info-charge td.info-data').text data.charge
@info_container.find('tr.info-charge').toggle(data.charge?)
if data.range?
@info_container.find('tr.info-range td.info-data').text data.range
@info_container.find('tr.info-range').show()
else
@info_container.find('tr.info-range').hide()
@info_container.find('tr.info-force td.info-data').html (data.force + '<i class="xwing-miniatures-font xwing-miniatures-font-recurring"></i>')
@info_container.find('tr.info-force').toggle(data.force?)
@info_container.find('tr.info-agility').hide()
@info_container.find('tr.info-hull').hide()
@info_container.find('tr.info-shields').hide()
@info_container.find('tr.info-actions').hide()
@info_container.find('tr.info-actions-red').hide()
@info_container.find('tr.info-upgrades').hide()
@info_container.find('p.info-maneuvers').hide()
@info_container.show()
@tooltip_currently_displaying = data
_randomizerLoopBody: (data) =>
if data.keep_running and data.iterations < data.max_iterations
data.iterations++
#console.log "Current points: #{@total_points} of #{data.max_points}, iteration=#{data.iterations} of #{data.max_iterations}, keep_running=#{data.keep_running}"
if @total_points == data.max_points
# Exact hit!
#console.log "Points reached exactly"
data.keep_running = false
else if @total_points < data.max_points
#console.log "Need to add something"
# Add something
# Possible options: ship or empty addon slot
unused_addons = []
for ship in @ships
for upgrade in ship.upgrades
unused_addons.push upgrade unless upgrade.data?
unused_addons.push ship.title if ship.title? and not ship.title.data?
for modification in ship.modifications
unused_addons.push modification unless modification.data?
# 0 is ship, otherwise addon
idx = $.randomInt(1 + unused_addons.length)
if idx == 0
# Add random ship
#console.log "Add ship"
available_ships = @getAvailableShipsMatching()
ship_type = available_ships[$.randomInt available_ships.length].text
available_pilots = @getAvailablePilotsForShipIncluding(ship_type)
pilot = available_pilots[$.randomInt available_pilots.length]
if exportObj.pilotsById[pilot.id].sources.intersects(data.allowed_sources)
new_ship = @addShip()
new_ship.setPilotById pilot.id
else
# Add upgrade/title/modification
#console.log "Add addon"
addon = unused_addons[idx - 1]
switch addon.type
when 'Upgrade'
available_upgrades = (upgrade for upgrade in @getAvailableUpgradesIncluding(addon.slot, null, addon.ship) when exportObj.upgradesById[upgrade.id].sources.intersects(data.allowed_sources))
addon.setById available_upgrades[$.randomInt available_upgrades.length].id if available_upgrades.length > 0
when 'Title'
available_titles = (title for title in @getAvailableTitlesIncluding(addon.ship) when exportObj.titlesById[title.id].sources.intersects(data.allowed_sources))
addon.setById available_titles[$.randomInt available_titles.length].id if available_titles.length > 0
when 'Modification'
available_modifications = (modification for modification in @getAvailableModificationsIncluding(null, addon.ship) when exportObj.modificationsById[modification.id].sources.intersects(data.allowed_sources))
addon.setById available_modifications[$.randomInt available_modifications.length].id if available_modifications.length > 0
else
throw new Error("Invalid addon type #{addon.type}")
else
#console.log "Need to remove something"
# Remove something
removable_things = []
for ship in @ships
removable_things.push ship
for upgrade in ship.upgrades
removable_things.push upgrade if upgrade.data?
removable_things.push ship.title if ship.title?.data?
removable_things.push ship.modification if ship.modification?.data?
if removable_things.length > 0
thing_to_remove = removable_things[$.randomInt removable_things.length]
#console.log "Removing #{thing_to_remove}"
if thing_to_remove instanceof Ship
@removeShip thing_to_remove
else if thing_to_remove instanceof GenericAddon
thing_to_remove.setData null
else
throw new Error("Unknown thing to remove #{thing_to_remove}")
# continue the "loop"
window.setTimeout @_makeRandomizerLoopFunc(data), 0
else
#console.log "Clearing timer #{data.timer}, iterations=#{data.iterations}, keep_running=#{data.keep_running}"
window.clearTimeout data.timer
# Update all selectors
for ship in @ships
ship.updateSelections()
@suppress_automatic_new_ship = false
@addShip()
_makeRandomizerLoopFunc: (data) =>
() =>
@_randomizerLoopBody(data)
randomSquad: (max_points=100, allowed_sources=null, timeout_ms=1000, max_iterations=1000) ->
@backend_status.fadeOut 'slow'
@suppress_automatic_new_ship = true
# Clear all existing ships
while @ships.length > 0
@removeShip @ships[0]
throw new Error("Ships not emptied") if @ships.length > 0
data =
iterations: 0
max_points: max_points
max_iterations: max_iterations
keep_running: true
allowed_sources: allowed_sources ? exportObj.expansions
stopHandler = () =>
#console.log "*** TIMEOUT *** TIMEOUT *** TIMEOUT ***"
data.keep_running = false
data.timer = window.setTimeout stopHandler , timeout_ms
#console.log "Timer set for #{timeout_ms}ms, timer is #{data.timer}"
window.setTimeout @_makeRandomizerLoopFunc(data), 0
@resetCurrentSquad()
@current_squad.name = 'PI:NAME:<NAME>END_PI Squad'
@container.trigger 'xwing-backend:squadNameChanged'
setBackend: (backend) ->
@backend = backend
describeSquad: ->
(ship.pilot.name for ship in @ships when ship.pilot?).join ', '
listCards: ->
card_obj = {}
for ship in @ships
if ship.pilot?
card_obj[ship.pilot.name] = null
for upgrade in ship.upgrades
card_obj[upgrade.data.name] = null if upgrade.data?
card_obj[ship.title.data.name] = null if ship.title?.data?
card_obj[ship.modification.data.name] = null if ship.modification?.data?
return Object.keys(card_obj).sort()
getNotes: ->
@notes.val()
getObstacles: ->
@current_obstacles
isSquadPossibleWithCollection: ->
# console.log "#{@faction}: isSquadPossibleWithCollection()"
# If the collection is uninitialized or empty, don't actually check it.
if Object.keys(@collection?.expansions ? {}).length == 0
# console.log "collection not ready or is empty"
return true
@collection.reset()
validity = true
for ship in @ships
if ship.pilot?
# Try to get both the physical model and the pilot card.
ship_is_available = @collection.use('ship', ship.pilot.english_ship)
pilot_is_available = @collection.use('pilot', ship.pilot.english_name)
# console.log "#{@faction}: Ship #{ship.pilot.english_ship} available: #{ship_is_available}"
# console.log "#{@faction}: Pilot #{ship.pilot.english_name} available: #{pilot_is_available}"
validity = false unless ship_is_available and pilot_is_available
for upgrade in ship.upgrades
if upgrade.data?
upgrade_is_available = @collection.use('upgrade', upgrade.data.english_name)
# console.log "#{@faction}: Upgrade #{upgrade.data.english_name} available: #{upgrade_is_available}"
validity = false unless upgrade_is_available
for modification in ship.modifications
if modification.data?
modification_is_available = @collection.use('modification', modification.data.english_name)
# console.log "#{@faction}: Modification #{modification.data.english_name} available: #{modification_is_available}"
validity = false unless modification_is_available
for title in ship.titles
if title?.data?
title_is_available = @collection.use('title', title.data.english_name)
# console.log "#{@faction}: Title #{title.data.english_name} available: #{title_is_available}"
validity = false unless title_is_available
validity
checkCollection: ->
# console.log "#{@faction}: Checking validity of squad against collection..."
if @collection?
@collection_invalid_container.toggleClass 'hidden', @isSquadPossibleWithCollection()
toXWS: ->
# Often you will want JSON.stringify(builder.toXWS())
xws =
description: @getNotes()
faction: exportObj.toXWSFaction[@faction]
name: @current_squad.name
pilots: []
points: @total_points
vendor:
yasb:
builder: '(Yet Another) X-Wing Miniatures Squad Builder'
builder_url: window.location.href.split('?')[0]
link: @getPermaLink()
version: '0.3.0'
for ship in @ships
if ship.pilot?
xws.pilots.push ship.toXWS()
# Associate multisection ships
# This maps id to list of pilots it comprises
multisection_id_to_pilots = {}
last_id = 0
unmatched = (pilot for pilot in xws.pilots when pilot.multisection?)
for _ in [0...(unmatched.length ** 2)]
break if unmatched.length == 0
# console.log "Top of loop, unmatched: #{m.name for m in unmatched}"
unmatched_pilot = unmatched.shift()
unmatched_pilot.multisection_id ?= last_id++
multisection_id_to_pilots[unmatched_pilot.multisection_id] ?= [unmatched_pilot]
break if unmatched.length == 0
# console.log "Finding matches for #{unmatched_pilot.name} (assigned id=#{unmatched_pilot.multisection_id})"
matches = []
for candidate in unmatched
# console.log "-> examine #{candidate.name}"
if unmatched_pilot.name in candidate.multisection
matches.push candidate
unmatched_pilot.multisection.removeItem candidate.name
candidate.multisection.removeItem unmatched_pilot.name
candidate.multisection_id = unmatched_pilot.multisection_id
# console.log "-> MATCH FOUND #{candidate.name}, assigned id=#{candidate.multisection_id}"
multisection_id_to_pilots[candidate.multisection_id].push candidate
if unmatched_pilot.multisection.length == 0
# console.log "-> No more sections to match for #{unmatched_pilot.name}"
break
for match in matches
if match.multisection.length == 0
# console.log "Dequeue #{match.name} since it has no more sections to match"
unmatched.removeItem match
for pilot in xws.pilots
delete pilot.multisection if pilot.multisection?
obstacles = @getObstacles()
if obstacles? and obstacles.length > 0
xws.obstacles = obstacles
xws
toMinimalXWS: ->
# Just what's necessary
xws = @toXWS()
# Keep mandatory stuff only
for own k, v of xws
delete xws[k] unless k in ['faction', 'pilots', 'version']
for own k, v of xws.pilots
delete xws[k] unless k in ['name', 'ship', 'upgrades', 'multisection_id']
xws
loadFromXWS: (xws, cb) ->
success = null
error = null
version_list = (parseInt x for x in xws.version.split('.'))
switch
# Not doing backward compatibility pre-1.x
when version_list > [0, 1]
xws_faction = exportObj.fromXWSFaction[xws.faction]
if @faction != xws_faction
throw new Error("Attempted to load XWS for #{xws.faction} but builder is #{@faction}")
if xws.name?
@current_squad.name = xws.name
if xws.description?
@notes.val xws.description
if xws.obstacles?
@current_squad.additional_data.obstacles = xws.obstacles
@suppress_automatic_new_ship = true
@removeAllShips()
for pilot in xws.pilots
new_ship = @addShip()
for ship_name, ship_data of exportObj.ships
if @matcher(ship_data.xws, pilot.ship)
shipnameXWS =
id: ship_data.name
xws: ship_data.xws
console.log "#{pilot.xws}"
try
new_ship.setPilot (p for p in (exportObj.pilotsByFactionXWS[@faction][pilot.id] ?= exportObj.pilotsByFactionCanonicalName[@faction][pilot.id]) when p.ship == shipnameXWS.id)[0]
catch err
console.error err.message
continue
# Turn all the upgrades into a flat list so we can keep trying to add them
addons = []
for upgrade_type, upgrade_canonicals of pilot.upgrades ? {}
for upgrade_canonical in upgrade_canonicals
# console.log upgrade_type, upgrade_canonical
slot = null
slot = exportObj.fromXWSUpgrade[upgrade_type] ? upgrade_type.capitalize()
addon = exportObj.upgradesBySlotXWSName[slot][upgrade_canonical] ?= exportObj.upgradesBySlotCanonicalName[slot][upgrade_canonical]
if addon?
# console.log "-> #{upgrade_type} #{addon.name} #{slot}"
addons.push
type: slot
data: addon
slot: slot
if addons.length > 0
for _ in [0...1000]
# Try to add an addon. If it's not eligible, requeue it and
# try it again later, as another addon might allow it.
addon = addons.shift()
# console.log "Adding #{addon.data.name} to #{new_ship}..."
addon_added = false
switch addon.type
when 'Modification'
for modification in new_ship.modifications
continue if modification.data?
modification.setData addon.data
addon_added = true
break
when 'Title'
for title in new_ship.titles
continue if title.data?
# Special cases :(
if addon.data instanceof Array
# Right now, the only time this happens is because of
# Heavy Scyk. Check the rest of the pending addons for torp,
# cannon, or missiles. Otherwise, it doesn't really matter.
slot_guesses = (a.data.slot for a in addons when a.data.slot in ['Cannon', 'Missile', 'Torpedo'])
# console.log slot_guesses
if slot_guesses.length > 0
# console.log "Guessing #{slot_guesses[0]}"
title.setData exportObj.titlesByLocalizedName[""""Heavy Scyk" Interceptor (#{slot_guesses[0]})"""]
else
# console.log "No idea, setting to #{addon.data[0].name}"
title.setData addon.data[0]
else
title.setData addon.data
addon_added = true
else
# console.log "Looking for unused #{addon.slot} in #{new_ship}..."
for upgrade, i in new_ship.upgrades
continue if upgrade.slot != addon.slot or upgrade.data?
upgrade.setData addon.data
addon_added = true
break
if addon_added
# console.log "Successfully added #{addon.data.name} to #{new_ship}"
if addons.length == 0
# console.log "Done with addons for #{new_ship}"
break
else
# Can't add it, requeue unless there are no other addons to add
# in which case this isn't valid
if addons.length == 0
success = false
error = "Could not add #{addon.data.name} to #{new_ship}"
break
else
# console.log "Could not add #{addon.data.name} to #{new_ship}, trying later"
addons.push addon
if addons.length > 0
success = false
error = "Could not add all upgrades"
break
@suppress_automatic_new_ship = false
# Finally, the unassigned ship
@addShip()
success = true
else
success = false
error = "Invalid or unsupported XWS version"
if success
@current_squad.dirty = true
@container.trigger 'xwing-backend:squadNameChanged'
@container.trigger 'xwing-backend:squadDirtinessChanged'
# console.log "success: #{success}, error: #{error}"
cb
success: success
error: error
class Ship
constructor: (args) ->
# args
@builder = args.builder
@container = args.container
# internal state
@pilot = null
@data = null # ship data
@upgrades = []
@modifications = []
@titles = []
@setupUI()
destroy: (cb) ->
@resetPilot()
@resetAddons()
@teardownUI()
idx = @builder.ships.indexOf this
if idx < 0
throw new Error("Ship not registered with builder")
@builder.ships.splice idx, 1
cb()
copyFrom: (other) ->
throw new Error("Cannot copy from self") if other is this
#console.log "Attempt to copy #{other?.pilot?.name}"
return unless other.pilot? and other.data?
#console.log "Setting pilot to ID=#{other.pilot.id}"
if other.pilot.unique
# Look for cheapest generic or available unique, otherwise do nothing
available_pilots = (pilot_data for pilot_data in @builder.getAvailablePilotsForShipIncluding(other.data.name) when not pilot_data.disabled)
if available_pilots.length > 0
@setPilotById available_pilots[0].id
# Can't just copy upgrades since slots may be different
# Similar to setPilot() when ship is the same
other_upgrades = {}
for upgrade in other.upgrades
if upgrade?.data? and not upgrade.data.unique and ((not upgrade.data.max_per_squad?) or @builder.countUpgrades(upgrade.data.canonical_name) < upgrade.data.max_per_squad)
other_upgrades[upgrade.slot] ?= []
other_upgrades[upgrade.slot].push upgrade
other_modifications = []
for modification in other.modifications
if modification?.data? and not modification.data.unique
other_modifications.push modification
other_titles = []
for title in other.titles
if title?.data? and not title.data.unique
other_titles.push title
for title in @titles
other_title = other_titles.shift()
if other_title?
title.setById other_title.data.id
for modification in @modifications
other_modification = other_modifications.shift()
if other_modification?
modification.setById other_modification.data.id
for upgrade in @upgrades
other_upgrade = (other_upgrades[upgrade.slot] ? []).shift()
if other_upgrade?
upgrade.setById other_upgrade.data.id
else
return
else
# Exact clone, so we can copy things over directly
@setPilotById other.pilot.id
# set up non-conferred addons
other_conferred_addons = []
other_conferred_addons = other_conferred_addons.concat(other.titles[0].conferredAddons) if other.titles[0]?.data? # and other.titles.conferredAddons.length > 0
other_conferred_addons = other_conferred_addons.concat(other.modifications[0].conferredAddons) if other.modifications[0]?.data?
#console.log "Looking for conferred upgrades..."
for other_upgrade, i in other.upgrades
# console.log "Examining upgrade #{other_upgrade}"
if other_upgrade.data? and other_upgrade not in other_conferred_addons and not other_upgrade.data.unique and i < @upgrades.length and ((not other_upgrade.data.max_per_squad?) or @builder.countUpgrades(other_upgrade.data.canonical_name) < other_upgrade.data.max_per_squad)
#console.log "Copying non-unique upgrade #{other_upgrade} into slot #{i}"
@upgrades[i].setById other_upgrade.data.id
#console.log "Checking other ship base title #{other.title ? null}"
@titles[0].setById other.titles[0].data.id if other.titles[0]?.data? and not other.titles[0].data.unique
#console.log "Checking other ship base modification #{other.modifications[0] ? null}"
@modifications[0].setById other.modifications[0].data.id if other.modifications[0]?.data and not other.modifications[0].data.unique
# set up conferred non-unique addons
#console.log "Attempt to copy conferred addons..."
if other.titles[0]? and other.titles[0].conferredAddons.length > 0
#console.log "Other ship title #{other.titles[0]} confers addons"
for other_conferred_addon, i in other.titles[0].conferredAddons
@titles[0].conferredAddons[i].setById other_conferred_addon.data.id if other_conferred_addon.data? and not other_conferred_addon.data?.unique
if other.modifications[0]? and other.modifications[0].conferredAddons.length > 0
#console.log "Other ship base modification #{other.modifications[0]} confers addons"
for other_conferred_addon, i in other.modifications[0].conferredAddons
@modifications[0].conferredAddons[i].setById other_conferred_addon.data.id if other_conferred_addon.data? and not other_conferred_addon.data?.unique
@updateSelections()
@builder.container.trigger 'xwing:pointsUpdated'
@builder.current_squad.dirty = true
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
setShipType: (ship_type) ->
@pilot_selector.data('select2').container.show()
if ship_type != @pilot?.ship
# Ship changed; select first non-unique
@setPilot (exportObj.pilotsById[result.id] for result in @builder.getAvailablePilotsForShipIncluding(ship_type) when not exportObj.pilotsById[result.id].unique)[0]
# Clear ship background class
for cls in @row.attr('class').split(/\s+/)
if cls.indexOf('ship-') == 0
@row.removeClass cls
# Show delete button
@remove_button.fadeIn 'fast'
# Ship background
@row.addClass "ship-#{ship_type.toLowerCase().replace(/[^a-z0-9]/gi, '')}0"
@builder.container.trigger 'xwing:shipUpdated'
setPilotById: (id) ->
@setPilot exportObj.pilotsById[parseInt id]
setPilotByName: (name) ->
@setPilot exportObj.pilotsByLocalizedName[$.trim name]
setPilot: (new_pilot) ->
if new_pilot != @pilot
@builder.current_squad.dirty = true
same_ship = @pilot? and new_pilot?.ship == @pilot.ship
old_upgrades = {}
old_titles = []
old_modifications = []
if same_ship
# track addons and try to reassign them
for upgrade in @upgrades
if upgrade?.data?
old_upgrades[upgrade.slot] ?= []
old_upgrades[upgrade.slot].push upgrade
for title in @titles
if title?.data?
old_titles.push title
for modification in @modifications
if modification?.data?
old_modifications.push modification
@resetPilot()
@resetAddons()
if new_pilot?
@data = exportObj.ships[new_pilot?.ship]
if new_pilot?.unique?
await @builder.container.trigger 'xwing:claimUnique', [ new_pilot, 'Pilot', defer() ]
@pilot = new_pilot
@setupAddons() if @pilot?
@copy_button.show()
@setShipType @pilot.ship
if same_ship
# Hopefully this order is correct
for title in @titles
old_title = old_titles.shift()
if old_title?
title.setById old_title.data.id
for modification in @modifications
old_modification = old_modifications.shift()
if old_modification?
modification.setById old_modification.data.id
for upgrade in @upgrades
old_upgrade = (old_upgrades[upgrade.slot] ? []).shift()
if old_upgrade?
upgrade.setById old_upgrade.data.id
else
@copy_button.hide()
@builder.container.trigger 'xwing:pointsUpdated'
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
resetPilot: ->
if @pilot?.unique?
await @builder.container.trigger 'xwing:releaseUnique', [ @pilot, 'Pilot', defer() ]
@pilot = null
setupAddons: ->
# Upgrades from pilot
for slot in @pilot.slots ? []
@upgrades.push new exportObj.Upgrade
ship: this
container: @addon_container
slot: slot
# Title
#if @pilot.ship of exportObj.titlesByShip
# @titles.push new exportObj.Title
# ship: this
# container: @addon_container
# Modifications
#@modifications.push new exportObj.Modification
# ship: this
# container: @addon_container
resetAddons: ->
await
for title in @titles
title.destroy defer() if title?
for upgrade in @upgrades
upgrade.destroy defer() if upgrade?
for modification in @modifications
modification.destroy defer() if modification?
@upgrades = []
@modifications = []
@titles = []
getPoints: ->
points = @pilot?.points ? 0
for title in @titles
points += (title?.getPoints() ? 0)
for upgrade in @upgrades
points += upgrade.getPoints()
for modification in @modifications
points += (modification?.getPoints() ? 0)
@points_container.find('span').text points
if points > 0
@points_container.fadeTo 'fast', 1
else
@points_container.fadeTo 0, 0
points
getEpicPoints: ->
@data?.epic_points ? 0
updateSelections: ->
if @pilot?
@ship_selector.select2 'data',
id: @pilot.ship
text: @pilot.ship
canonical_name: exportObj.ships[@pilot.ship].canonical_name
@pilot_selector.select2 'data',
id: @pilot.id
text: "#{@pilot.name} (#{@pilot.points})"
@pilot_selector.data('select2').container.show()
for upgrade in @upgrades
upgrade.updateSelection()
for title in @titles
title.updateSelection() if title?
for modification in @modifications
modification.updateSelection() if modification?
else
@pilot_selector.select2 'data', null
@pilot_selector.data('select2').container.toggle(@ship_selector.val() != '')
setupUI: ->
@row = $ document.createElement 'DIV'
@row.addClass 'row-fluid ship'
@row.insertBefore @builder.notes_container
@row.append $.trim '''
<div class="span3">
<input class="ship-selector-container" type="hidden" />
<br />
<input type="hidden" class="pilot-selector-container" />
</div>
<div class="span1 points-display-container">
<span></span>
</div>
<div class="span6 addon-container" />
<div class="span2 button-container">
<button class="btn btn-danger remove-pilot"><span class="visible-desktop visible-tablet hidden-phone" data-toggle="tooltip" title="Remove Pilot"><i class="fa fa-times"></i></span><span class="hidden-desktop hidden-tablet visible-phone">Remove Pilot</span></button>
<button class="btn copy-pilot"><span class="visible-desktop visible-tablet hidden-phone" data-toggle="tooltip" title="Clone Pilot"><i class="fa fa-files-o"></i></span><span class="hidden-desktop hidden-tablet visible-phone">Clone Pilot</span></button>
</div>
'''
@row.find('.button-container span').tooltip()
@ship_selector = $ @row.find('input.ship-selector-container')
@pilot_selector = $ @row.find('input.pilot-selector-container')
shipResultFormatter = (object, container, query) ->
# Append directly so we don't have to disable markup escaping
$(container).append """<i class="xwing-miniatures-ship xwing-miniatures-ship-#{object.canonical_name}"></i> #{object.text}"""
# If you return a string, Select2 will render it
undefined
@ship_selector.select2
width: '100%'
placeholder: exportObj.translate @builder.language, 'ui', 'shipSelectorPlaceholder'
query: (query) =>
@builder.checkCollection()
query.callback
more: false
results: @builder.getAvailableShipsMatching(query.term)
minimumResultsForSearch: if $.isMobile() then -1 else 0
formatResultCssClass: (obj) =>
if @builder.collection?
not_in_collection = false
if @pilot? and obj.id == exportObj.ships[@pilot.ship].id
# Currently selected ship; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@builder.collection.checkShelf('ship', obj.english_name) or @builder.collection.checkTable('pilot', obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @builder.collection.checkShelf('ship', obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
formatResult: shipResultFormatter
formatSelection: shipResultFormatter
@ship_selector.on 'change', (e) =>
@setShipType @ship_selector.val()
# assign ship row an id for testing purposes
@row.attr 'id', "row-#{@ship_selector.data('select2').container.attr('id')}"
@pilot_selector.select2
width: '100%'
placeholder: exportObj.translate @builder.language, 'ui', 'pilotSelectorPlaceholder'
query: (query) =>
@builder.checkCollection()
query.callback
more: false
results: @builder.getAvailablePilotsForShipIncluding(@ship_selector.val(), @pilot, query.term)
minimumResultsForSearch: if $.isMobile() then -1 else 0
formatResultCssClass: (obj) =>
if @builder.collection?
not_in_collection = false
if obj.id == @pilot?.id
# Currently selected pilot; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@builder.collection.checkShelf('pilot', obj.english_name) or @builder.collection.checkTable('pilot', obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @builder.collection.checkShelf('pilot', obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
@pilot_selector.on 'change', (e) =>
@setPilotById @pilot_selector.select2('val')
@builder.current_squad.dirty = true
@builder.container.trigger 'xwing-backend:squadDirtinessChanged'
@builder.backend_status.fadeOut 'slow'
@pilot_selector.data('select2').results.on 'mousemove-filtered', (e) =>
select2_data = $(e.target).closest('.select2-result').data 'select2-data'
@builder.showTooltip 'Pilot', exportObj.pilotsById[select2_data.id], {ship: @data?.english_name} if select2_data?.id?
@pilot_selector.data('select2').container.on 'mouseover', (e) =>
@builder.showTooltip 'Ship', this if @data?
@pilot_selector.data('select2').container.hide()
@points_container = $ @row.find('.points-display-container')
@points_container.fadeTo 0, 0
@addon_container = $ @row.find('div.addon-container')
@remove_button = $ @row.find('button.remove-pilot')
@remove_button.click (e) =>
e.preventDefault()
@row.slideUp 'fast', () =>
@builder.removeShip this
@backend_status?.fadeOut 'slow'
@remove_button.hide()
@copy_button = $ @row.find('button.copy-pilot')
@copy_button.click (e) =>
clone = @builder.ships[@builder.ships.length - 1]
clone.copyFrom(this)
@copy_button.hide()
teardownUI: ->
@row.text ''
@row.remove()
toString: ->
if @pilot?
"Pilot #{@pilot.name} flying #{@data.name}"
else
"Ship without pilot"
toHTML: ->
effective_stats = @effectiveStats()
action_icons = []
action_icons_red = []
for action in effective_stats.actions
action_icons.push switch action
when 'Focus'
"""<i class="xwing-miniatures-font xwing-miniatures-font-focus"></i>"""
when 'Evade'
"""<i class="xwing-miniatures-font xwing-miniatures-font-evade"></i>"""
when 'Barrel Roll'
"""<i class="xwing-miniatures-font xwing-miniatures-font-barrelroll"></i>"""
when 'Target Lock'
"""<i class="xwing-miniatures-font xwing-miniatures-font-lock"></i>"""
when 'Boost'
"""<i class="xwing-miniatures-font xwing-miniatures-font-boost"></i>"""
when 'Coordinate'
"""<i class="xwing-miniatures-font xwing-miniatures-font-coordinate"></i>"""
when 'Jam'
"""<i class="xwing-miniatures-font xwing-miniatures-font-jam"></i>"""
when 'Recover'
"""<i class="xwing-miniatures-font xwing-miniatures-font-recover"></i>"""
when 'Reinforce'
"""<i class="xwing-miniatures-font xwing-miniatures-font-reinforce"></i>"""
when 'Cloak'
"""<i class="xwing-miniatures-font xwing-miniatures-font-cloak"></i>"""
when 'Slam'
"""<i class="xwing-miniatures-font xwing-miniatures-font-slam"></i>"""
when 'Rotate Arc'
"""<i class="xwing-miniatures-font xwing-miniatures-font-rotatearc"></i>"""
when 'Reload'
"""<i class="xwing-miniatures-font xwing-miniatures-font-reload"></i>"""
when 'Calculate'
"""<i class="xwing-miniatures-font xwing-miniatures-font-calculate"></i>"""
when "<r>> Target Lock</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-lock"></i></r>"""
when "<r>> Barrel Roll</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-barrelroll"></i></r>"""
when "<r>> Focus</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-focus"></i></r>"""
when "<r>> Rotate Arc</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-rotatearc"></i></r>"""
when "<r>> Evade</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-evade"></i></r>"""
when "<r>> Calculate</r>"
"""<r>> <i class="xwing-miniatures-font info-attack red xwing-miniatures-font-calculate"></i></r>"""
else
"""<span> #{action}<span>"""
for actionred in effective_stats.actionsred
action_icons_red.push switch actionred
when 'Focus'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-focus"></i>"""
when 'Evade'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-evade"></i>"""
when 'Barrel Roll'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-barrelroll"></i>"""
when 'Target Lock'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-lock"></i>"""
when 'Boost'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-boost"></i>"""
when 'Coordinate'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-coordinate"></i>"""
when 'Jam'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-jam"></i>"""
when 'Recover'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-recover"></i>"""
when 'Reinforce'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-reinforce"></i>"""
when 'Cloak'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-cloak"></i>"""
when 'Slam'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-slam"></i>"""
when 'Rotate Arc'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-rotatearc"></i>"""
when 'Reload'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-reload"></i>"""
when 'Calculate'
"""<i class="xwing-miniatures-font red xwing-miniatures-font-calculate"></i>"""
else
"""<span> #{action}<span>"""
action_bar = action_icons.join ' '
action_bar_red = action_icons_red.join ' '
attack_icon = @data.attack_icon ? 'xwing-miniatures-font-frontarc'
attackHTML = if (@pilot.ship_override?.attack? or @data.attack?) then $.trim """
<i class="xwing-miniatures-font #{attack_icon}"></i>
<span class="info-data info-attack">#{statAndEffectiveStat((@pilot.ship_override?.attack ? @data.attack), effective_stats, 'attack')}</span>
""" else ''
energyHTML = if (@pilot.ship_override?.energy? or @data.energy?) then $.trim """
<i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>
<span class="info-data info-energy">#{statAndEffectiveStat((@pilot.ship_override?.energy ? @data.energy), effective_stats, 'energy')}</span>
""" else ''
forceHTML = if (@pilot.force?) then $.trim """
<i class="xwing-miniatures-font xwing-miniatures-font-force"></i>
<span class="info-data info-force">#{statAndEffectiveStat((@pilot.ship_override?.force ? @pilot.force), effective_stats, 'force')}</span>
""" else ''
html = $.trim """
<div class="fancy-pilot-header">
<div class="pilot-header-text">#{@pilot.name} <i class="xwing-miniatures-ship xwing-miniatures-ship-#{@data.canonical_name}"></i><span class="fancy-ship-type"> #{@data.name}</span></div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle pilot-points">#{@pilot.points}</div>
</div>
</div>
</div>
<div class="fancy-pilot-stats">
<div class="pilot-stats-content">
<span class="info-data info-skill">PS #{statAndEffectiveStat(@pilot.skill, effective_stats, 'skill')}</span>
#{attackHTML}
#{energyHTML}
<i class="xwing-miniatures-font xwing-miniatures-font-agility"></i>
<span class="info-data info-agility">#{statAndEffectiveStat((@pilot.ship_override?.agility ? @data.agility), effective_stats, 'agility')}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-hull"></i>
<span class="info-data info-hull">#{statAndEffectiveStat((@pilot.ship_override?.hull ? @data.hull), effective_stats, 'hull')}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-shield"></i>
<span class="info-data info-shields">#{statAndEffectiveStat((@pilot.ship_override?.shields ? @data.shields), effective_stats, 'shields')}</span>
#{forceHTML}
#{action_bar}
#{action_bar_red}
</div>
</div>
"""
if @pilot.text
html += $.trim """
<div class="fancy-pilot-text">#{@pilot.text}</div>
"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
html += $.trim """
<div class="fancy-upgrade-container">
"""
for upgrade in slotted_upgrades
html += upgrade.toHTML()
html += $.trim """
</div>
"""
# if @getPoints() != @pilot.points
html += $.trim """
<div class="ship-points-total">
<strong>Ship Total: #{@getPoints()}</strong>
</div>
"""
"""<div class="fancy-ship">#{html}</div>"""
toTableRow: ->
table_html = $.trim """
<tr class="simple-pilot">
<td class="name">#{@pilot.name} — #{@data.name}</td>
<td class="points">#{@pilot.points}</td>
</tr>
"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
for upgrade in slotted_upgrades
table_html += upgrade.toTableRow()
# if @getPoints() != @pilot.points
table_html += """<tr class="simple-ship-total"><td colspan="2">Ship Total: #{@getPoints()}</td></tr>"""
table_html += '<tr><td> </td><td></td></tr>'
table_html
toBBCode: ->
bbcode = """[b]#{@pilot.name} (#{@pilot.points})[/b]"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
bbcode +="\n"
bbcode_upgrades= []
for upgrade in slotted_upgrades
upgrade_bbcode = upgrade.toBBCode()
bbcode_upgrades.push upgrade_bbcode if upgrade_bbcode?
bbcode += bbcode_upgrades.join "\n"
bbcode
toSimpleHTML: ->
html = """<b>#{@pilot.name} (#{@pilot.points})</b><br />"""
slotted_upgrades = (upgrade for upgrade in @upgrades when upgrade.data?)
.concat (modification for modification in @modifications when modification.data?)
.concat (title for title in @titles when title.data?)
if slotted_upgrades.length > 0
for upgrade in slotted_upgrades
upgrade_html = upgrade.toSimpleHTML()
html += upgrade_html if upgrade_html?
html
toSerialized: ->
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
# Skip conferred upgrades
conferred_addons = []
for title in @titles
conferred_addons = conferred_addons.concat(title?.conferredAddons ? [])
for modification in @modifications
conferred_addons = conferred_addons.concat(modification?.conferredAddons ? [])
for upgrade in @upgrades
conferred_addons = conferred_addons.concat(upgrade?.conferredAddons ? [])
upgrades = """#{upgrade?.data?.id ? -1 for upgrade, i in @upgrades when upgrade not in conferred_addons}"""
serialized_conferred_addons = []
for addon in conferred_addons
serialized_conferred_addons.push addon.toSerialized()
[
@pilot.id,
upgrades,
@titles[0]?.data?.id ? -1,
@modifications[0]?.data?.id ? -1,
serialized_conferred_addons.join(','),
].join ':'
fromSerialized: (version, serialized) ->
switch version
when 1
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:TITLEUPGRADE1,TITLEUPGRADE2:MODIFICATIONID
[ pilot_id, upgrade_ids, title_id, title_conferred_upgrade_ids, modification_id ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
@upgrades[i].setById upgrade_id if upgrade_id >= 0
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
if @titles[0]? and @titles[0].conferredAddons.length > 0
for upgrade_id, i in title_conferred_upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
@titles[0].conferredAddons[i].setById upgrade_id if upgrade_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
when 2, 3
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
[ pilot_id, upgrade_ids, title_id, modification_id, conferredaddon_pairs ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
deferred_ids = []
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
continue if upgrade_id < 0 or isNaN(upgrade_id)
if @upgrades[i].isOccupied()
deferred_ids.push upgrade_id
else
@upgrades[i].setById upgrade_id
for deferred_id in deferred_ids
for upgrade, i in @upgrades
continue if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot
upgrade.setById deferred_id
break
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
# We confer title addons before modification addons, to pick an arbitrary ordering.
if conferredaddon_pairs?
conferredaddon_pairs = conferredaddon_pairs.split ','
else
conferredaddon_pairs = []
if @titles[0]? and @titles[0].conferredAddons.length > 0
title_conferred_addon_pairs = conferredaddon_pairs.splice 0, @titles[0].conferredAddons.length
for conferredaddon_pair, i in title_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = @titles[0].conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for modification in @modifications
if modification?.data? and modification.conferredAddons.length > 0
modification_conferred_addon_pairs = conferredaddon_pairs.splice 0, modification.conferredAddons.length
for conferredaddon_pair, i in modification_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = modification.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
when 4
# PILOT_ID:UPGRADEID1,UPGRADEID2:TITLEID:MODIFICATIONID:CONFERREDADDONTYPE1.CONFERREDADDONID1,CONFERREDADDONTYPE2.CONFERREDADDONID2
[ pilot_id, upgrade_ids, title_id, modification_id, conferredaddon_pairs ] = serialized.split ':'
@setPilotById parseInt(pilot_id)
deferred_ids = []
for upgrade_id, i in upgrade_ids.split ','
upgrade_id = parseInt upgrade_id
continue if upgrade_id < 0 or isNaN(upgrade_id)
# Defer fat upgrades
if @upgrades[i].isOccupied() or @upgrades[i].dataById[upgrade_id].also_occupies_upgrades?
deferred_ids.push upgrade_id
else
@upgrades[i].setById upgrade_id
for deferred_id in deferred_ids
for upgrade, i in @upgrades
continue if upgrade.isOccupied() or upgrade.slot != exportObj.upgradesById[deferred_id].slot
upgrade.setById deferred_id
break
title_id = parseInt title_id
@titles[0].setById title_id if title_id >= 0
modification_id = parseInt modification_id
@modifications[0].setById modification_id if modification_id >= 0
# We confer title addons before modification addons, to pick an arbitrary ordering.
if conferredaddon_pairs?
conferredaddon_pairs = conferredaddon_pairs.split ','
else
conferredaddon_pairs = []
for title, i in @titles
if title?.data? and title.conferredAddons.length > 0
# console.log "Confer title #{title.data.name} at #{i}"
title_conferred_addon_pairs = conferredaddon_pairs.splice 0, title.conferredAddons.length
for conferredaddon_pair, i in title_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = title.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for modification in @modifications
if modification?.data? and modification.conferredAddons.length > 0
modification_conferred_addon_pairs = conferredaddon_pairs.splice 0, modification.conferredAddons.length
for conferredaddon_pair, i in modification_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = modification.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
for upgrade in @upgrades
if upgrade?.data? and upgrade.conferredAddons.length > 0
upgrade_conferred_addon_pairs = conferredaddon_pairs.splice 0, upgrade.conferredAddons.length
for conferredaddon_pair, i in upgrade_conferred_addon_pairs
[ addon_type_serialized, addon_id ] = conferredaddon_pair.split '.'
addon_id = parseInt addon_id
addon_cls = SERIALIZATION_CODE_TO_CLASS[addon_type_serialized]
conferred_addon = upgrade.conferredAddons[i]
if conferred_addon instanceof addon_cls
conferred_addon.setById addon_id
else
throw new Error("Expected addon class #{addon_cls.constructor.name} for conferred addon at index #{i} but #{conferred_addon.constructor.name} is there")
@updateSelections()
effectiveStats: ->
stats =
skill: @pilot.skill
attack: @pilot.ship_override?.attack ? @data.attack
attackf: @pilot.ship_override?.attackf ? @data.attackf
attackb: @pilot.ship_override?.attackb ? @data.attackb
attackt: @pilot.ship_override?.attackt ? @data.attackt
attackdt: @pilot.ship_override?.attackdt ? @data.attackdt
energy: @pilot.ship_override?.energy ? @data.energy
agility: @pilot.ship_override?.agility ? @data.agility
hull: @pilot.ship_override?.hull ? @data.hull
shields: @pilot.ship_override?.shields ? @data.shields
force: @pilot.ship_override?.force ? @pilot.force
charge: @pilot.ship_override?.charge ? @pilot.charge
actions: (@pilot.ship_override?.actions ? @data.actions).slice 0
actionsred: ((@pilot.ship_override?.actionsred ? @data.actionsred) ? []).slice 0
# need a deep copy of maneuvers array
stats.maneuvers = []
for s in [0 ... (@data.maneuvers ? []).length]
stats.maneuvers[s] = @data.maneuvers[s].slice 0
for upgrade in @upgrades
upgrade.data.modifier_func(stats) if upgrade?.data?.modifier_func?
for title in @titles
title.data.modifier_func(stats) if title?.data?.modifier_func?
for modification in @modifications
modification.data.modifier_func(stats) if modification?.data?.modifier_func?
@pilot.modifier_func(stats) if @pilot?.modifier_func?
stats
validate: ->
# Remove addons that violate their validation functions (if any) one by one
# until everything checks out
# If there is no explicit validation_func, use restriction_func
max_checks = 128 # that's a lot of addons (Epic?)
for i in [0...max_checks]
valid = true
for upgrade in @upgrades
func = upgrade?.data?.validation_func ? upgrade?.data?.restriction_func ? undefined
if func? and not func(this, upgrade)
#console.log "Invalid upgrade: #{upgrade?.data?.name}"
upgrade.setById null
valid = false
break
for title in @titles
func = title?.data?.validation_func ? title?.data?.restriction_func ? undefined
if func? and not func this
#console.log "Invalid title: #{title?.data?.name}"
title.setById null
valid = false
break
for modification in @modifications
func = modification?.data?.validation_func ? modification?.data?.restriction_func ? undefined
if func? and not func(this, modification)
#console.log "Invalid modification: #{modification?.data?.name}"
modification.setById null
valid = false
break
break if valid
@updateSelections()
checkUnreleasedContent: ->
if @pilot? and not exportObj.isReleased @pilot
#console.log "#{@pilot.name} is unreleased"
return true
for title in @titles
if title?.data? and not exportObj.isReleased title.data
#console.log "#{title.data.name} is unreleased"
return true
for modification in @modifications
if modification?.data? and not exportObj.isReleased modification.data
#console.log "#{modification.data.name} is unreleased"
return true
for upgrade in @upgrades
if upgrade?.data? and not exportObj.isReleased upgrade.data
#console.log "#{upgrade.data.name} is unreleased"
return true
false
checkEpicContent: ->
if @pilot? and @pilot.epic?
return true
for title in @titles
if title?.data?.epic?
return true
for modification in @modifications
if modification?.data?.epic?
return true
for upgrade in @upgrades
if upgrade?.data?.epic?
return true
false
hasAnotherUnoccupiedSlotLike: (upgrade_obj) ->
for upgrade in @upgrades
continue if upgrade == upgrade_obj or upgrade.slot != upgrade_obj.slot
return true unless upgrade.isOccupied()
false
toXWS: ->
xws =
id: (@pilot.xws ? @pilot.canonical_name)
points: @getPoints()
#ship: @data.canonical_name
ship: @data.xws.canonicalize()
if @data.multisection
xws.multisection = @data.multisection.slice 0
upgrade_obj = {}
for upgrade in @upgrades
if upgrade?.data?
upgrade.toXWS upgrade_obj
for modification in @modifications
if modification?.data?
modification.toXWS upgrade_obj
for title in @titles
if title?.data?
title.toXWS upgrade_obj
if Object.keys(upgrade_obj).length > 0
xws.upgrades = upgrade_obj
xws
getConditions: ->
if Set?
conditions = new Set()
if @pilot?.applies_condition?
if @pilot.applies_condition instanceof Array
for condition in @pilot.applies_condition
conditions.add(exportObj.conditionsByCanonicalName[condition])
else
conditions.add(exportObj.conditionsByCanonicalName[@pilot.applies_condition])
for upgrade in @upgrades
if upgrade?.data?.applies_condition?
if upgrade.data.applies_condition instanceof Array
for condition in upgrade.data.applies_condition
conditions.add(exportObj.conditionsByCanonicalName[condition])
else
conditions.add(exportObj.conditionsByCanonicalName[upgrade.data.applies_condition])
conditions
else
console.warn 'Set not supported in this JS implementation, not implementing conditions'
[]
class GenericAddon
constructor: (args) ->
# args
@ship = args.ship
@container = $ args.container
# internal state
@data = null
@unadjusted_data = null
@conferredAddons = []
@serialization_code = 'X'
@occupied_by = null
@occupying = []
@destroyed = false
# Overridden by children
@type = null
@dataByName = null
@dataById = null
@adjustment_func = args.adjustment_func if args.adjustment_func?
@filter_func = args.filter_func if args.filter_func?
@placeholderMod_func = if args.placeholderMod_func? then args.placeholderMod_func else (x) => x
destroy: (cb, args...) ->
return cb(args) if @destroyed
if @data?.unique?
await @ship.builder.container.trigger 'xwing:releaseUnique', [ @data, @type, defer() ]
@destroyed = true
@rescindAddons()
@deoccupyOtherUpgrades()
@selector.select2 'destroy'
cb args
setupSelector: (args) ->
@selector = $ document.createElement 'INPUT'
@selector.attr 'type', 'hidden'
@container.append @selector
args.minimumResultsForSearch = -1 if $.isMobile()
args.formatResultCssClass = (obj) =>
if @ship.builder.collection?
not_in_collection = false
if obj.id == @data?.id
# Currently selected card; mark as not in collection if it's neither
# on the shelf nor on the table
unless (@ship.builder.collection.checkShelf(@type.toLowerCase(), obj.english_name) or @ship.builder.collection.checkTable(@type.toLowerCase(), obj.english_name))
not_in_collection = true
else
# Not currently selected; check shelf only
not_in_collection = not @ship.builder.collection.checkShelf(@type.toLowerCase(), obj.english_name)
if not_in_collection then 'select2-result-not-in-collection' else ''
else
''
args.formatSelection = (obj, container) =>
icon = switch @type
when 'Upgrade'
@slot.toLowerCase().replace(/[^0-9a-z]/gi, '')
else
@type.toLowerCase().replace(/[^0-9a-z]/gi, '')
icon = icon.replace("configuration", "config")
.replace("force", "forcepower")
# Append directly so we don't have to disable markup escaping
$(container).append """<i class="xwing-miniatures-font xwing-miniatures-font-#{icon}"></i> #{obj.text}"""
# If you return a string, Select2 will render it
undefined
@selector.select2 args
@selector.on 'change', (e) =>
@setById @selector.select2('val')
@ship.builder.current_squad.dirty = true
@ship.builder.container.trigger 'xwing-backend:squadDirtinessChanged'
@ship.builder.backend_status.fadeOut 'slow'
@selector.data('select2').results.on 'mousemove-filtered', (e) =>
select2_data = $(e.target).closest('.select2-result').data 'select2-data'
@ship.builder.showTooltip 'Addon', @dataById[select2_data.id], {addon_type: @type} if select2_data?.id?
@selector.data('select2').container.on 'mouseover', (e) =>
@ship.builder.showTooltip 'Addon', @data, {addon_type: @type} if @data?
setById: (id) ->
@setData @dataById[parseInt id]
setByName: (name) ->
@setData @dataByName[$.trim name]
setData: (new_data) ->
if new_data?.id != @data?.id
if @data?.unique?
await @ship.builder.container.trigger 'xwing:releaseUnique', [ @unadjusted_data, @type, defer() ]
@rescindAddons()
@deoccupyOtherUpgrades()
if new_data?.unique?
await @ship.builder.container.trigger 'xwing:claimUnique', [ new_data, @type, defer() ]
# Need to make a copy of the data, but that means I can't just check equality
@data = @unadjusted_data = new_data
if @data?
if @data.superseded_by_id
return @setById @data.superseded_by_id
if @adjustment_func?
@data = @adjustment_func(@data)
@unequipOtherUpgrades()
@occupyOtherUpgrades()
@conferAddons()
else
@deoccupyOtherUpgrades()
@ship.builder.container.trigger 'xwing:pointsUpdated'
conferAddons: ->
if @data.confersAddons? and @data.confersAddons.length > 0
for addon in @data.confersAddons
cls = addon.type
args =
ship: @ship
container: @container
args.slot = addon.slot if addon.slot?
args.adjustment_func = addon.adjustment_func if addon.adjustment_func?
args.filter_func = addon.filter_func if addon.filter_func?
args.auto_equip = addon.auto_equip if addon.auto_equip?
args.placeholderMod_func = addon.placeholderMod_func if addon.placeholderMod_func?
addon = new cls args
if addon instanceof exportObj.Upgrade
@ship.upgrades.push addon
else if addon instanceof exportObj.Modification
@ship.modifications.push addon
else if addon instanceof exportObj.Title
@ship.titles.push addon
else
throw new Error("Unexpected addon type for addon #{addon}")
@conferredAddons.push addon
rescindAddons: ->
await
for addon in @conferredAddons
addon.destroy defer()
for addon in @conferredAddons
if addon instanceof exportObj.Upgrade
@ship.upgrades.removeItem addon
else if addon instanceof exportObj.Modification
@ship.modifications.removeItem addon
else if addon instanceof exportObj.Title
@ship.titles.removeItem addon
else
throw new Error("Unexpected addon type for addon #{addon}")
@conferredAddons = []
getPoints: ->
# Moar special case jankiness
if @data?.variableagility? and @ship?
Math.max(@data?.basepoints ? 0, (@data?.basepoints ? 0) + ((@ship?.data.agility - 1)*2) + 1)
else if @data?.variablebase? and not (@ship.data.medium? or @ship.data.large?)
Math.max(0, @data?.basepoints)
else if @data?.variablebase? and @ship?.data.medium?
Math.max(0, (@data?.basepoints ? 0) + (@data?.basepoints))
else if @data?.variablebase? and @ship?.data.large?
Math.max(0, (@data?.basepoints ? 0) + (@data?.basepoints * 2))
else
@data?.points ? 0
updateSelection: ->
if @data?
@selector.select2 'data',
id: @data.id
text: "#{@data.name} (#{@data.points})"
else
@selector.select2 'data', null
toString: ->
if @data?
"#{@data.name} (#{@data.points})"
else
"No #{@type}"
toHTML: ->
if @data?
upgrade_slot_font = (@data.slot ? @type).toLowerCase().replace(/[^0-9a-z]/gi, '')
match_array = @data.text.match(/(<span.*<\/span>)<br \/><br \/>(.*)/)
if match_array
restriction_html = '<div class="card-restriction-container">' + match_array[1] + '</div>'
text_str = match_array[2]
else
restriction_html = ''
text_str = @data.text
attackHTML = if (@data.attack?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attack}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-frontarc"></i>
</div>
""" else if (@data.attackt?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attackt}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-singleturretarc"></i>
</div>
""" else if (@data.attackbull?) then $.trim """
<div class="upgrade-attack">
<span class="upgrade-attack-range">#{@data.range}</span>
<span class="info-data info-attack">#{@data.attackbull}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-bullseyearc"></i>
</div>
""" else ''
energyHTML = if (@data.energy?) then $.trim """
<div class="upgrade-energy">
<span class="info-data info-energy">#{@data.energy}</span>
<i class="xwing-miniatures-font xwing-miniatures-font-energy"></i>
</div>
""" else ''
$.trim """
<div class="upgrade-container">
<div class="upgrade-stats">
<div class="upgrade-name"><i class="xwing-miniatures-font xwing-miniatures-font-#{upgrade_slot_font}"></i>#{@data.name}</div>
<div class="mask">
<div class="outer-circle">
<div class="inner-circle upgrade-points">#{@data.points}</div>
</div>
</div>
#{restriction_html}
</div>
#{attackHTML}
#{energyHTML}
<div class="upgrade-text">#{text_str}</div>
<div style="clear: both;"></div>
</div>
"""
else
''
toTableRow: ->
if @data?
$.trim """
<tr class="simple-addon">
<td class="name">#{@data.name}</td>
<td class="points">#{@data.points}</td>
</tr>
"""
else
''
toBBCode: ->
if @data?
"""[i]#{@data.name} (#{@data.points})[/i]"""
else
null
toSimpleHTML: ->
if @data?
"""<i>#{@data.name} (#{@data.points})</i><br />"""
else
''
toSerialized: ->
"""#{@serialization_code}.#{@data?.id ? -1}"""
unequipOtherUpgrades: ->
for slot in @data?.unequips_upgrades ? []
for upgrade in @ship.upgrades
continue if upgrade.slot != slot or upgrade == this or not upgrade.isOccupied()
upgrade.setData null
break
if @data?.unequips_modifications
for modification in @ship.modifications
continue unless modification == this or modification.isOccupied()
modification.setData null
isOccupied: ->
@data? or @occupied_by?
occupyOtherUpgrades: ->
for slot in @data?.also_occupies_upgrades ? []
for upgrade in @ship.upgrades
continue if upgrade.slot != slot or upgrade == this or upgrade.isOccupied()
@occupy upgrade
break
if @data?.also_occupies_modifications
for modification in @ship.modifications
continue if modification == this or modification.isOccupied()
@occupy modification
deoccupyOtherUpgrades: ->
for upgrade in @occupying
@deoccupy upgrade
occupy: (upgrade) ->
upgrade.occupied_by = this
upgrade.selector.select2 'enable', false
@occupying.push upgrade
deoccupy: (upgrade) ->
upgrade.occupied_by = null
upgrade.selector.select2 'enable', true
occupiesAnotherUpgradeSlot: ->
for upgrade in @ship.upgrades
continue if upgrade.slot != @slot or upgrade == this or upgrade.data?
if upgrade.occupied_by? and upgrade.occupied_by == this
return true
false
toXWS: (upgrade_dict) ->
upgrade_type = switch @type
when 'Upgrade'
exportObj.toXWSUpgrade[@slot] ? @slot.canonicalize()
else
exportObj.toXWSUpgrade[@type] ? @type.canonicalize()
(upgrade_dict[upgrade_type] ?= []).push (@data.xws ? @data.canonical_name)
class exportObj.Upgrade extends GenericAddon
constructor: (args) ->
# args
super args
@slot = args.slot
@type = 'Upgrade'
@dataById = exportObj.upgradesById
@dataByName = exportObj.upgradesByLocalizedName
@serialization_code = 'U'
@setupSelector()
setupSelector: ->
super
width: '50%'
placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'upgradePlaceholder', @slot)
allowClear: true
query: (query) =>
@ship.builder.checkCollection()
query.callback
more: false
results: @ship.builder.getAvailableUpgradesIncluding(@slot, @data, @ship, this, query.term, @filter_func)
#Temporarily removed modifications as they are now upgrades
#class exportObj.Modification extends GenericAddon
# constructor: (args) ->
# super args
# @type = 'Modification'
# @dataById = exportObj.modificationsById
# @dataByName = exportObj.modificationsByLocalizedName
# @serialization_code = 'M'
# @setupSelector()
# setupSelector: ->
# super
# width: '50%'
# placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'modificationPlaceholder')
# allowClear: true
# query: (query) =>
# @ship.builder.checkCollection()
# query.callback
# more: false
# results: @ship.builder.getAvailableModificationsIncluding(@data, @ship, query.term, @filter_func)
class exportObj.Title extends GenericAddon
constructor: (args) ->
super args
@type = 'Title'
@dataById = exportObj.titlesById
@dataByName = exportObj.titlesByLocalizedName
@serialization_code = 'T'
@setupSelector()
setupSelector: ->
super
width: '50%'
placeholder: @placeholderMod_func(exportObj.translate @ship.builder.language, 'ui', 'titlePlaceholder')
allowClear: true
query: (query) =>
@ship.builder.checkCollection()
query.callback
more: false
results: @ship.builder.getAvailableTitlesIncluding(@ship, @data, query.term)
class exportObj.RestrictedUpgrade extends exportObj.Upgrade
constructor: (args) ->
@filter_func = args.filter_func
super args
@serialization_code = 'u'
if args.auto_equip?
@setById args.auto_equip
#class exportObj.RestrictedModification extends exportObj.Modification
# constructor: (args) ->
# @filter_func = args.filter_func
# super args
# @serialization_code = 'm'
# if args.auto_equip?
# @setById args.auto_equip
SERIALIZATION_CODE_TO_CLASS =
'M': exportObj.Modification
'T': exportObj.Title
'U': exportObj.Upgrade
'u': exportObj.RestrictedUpgrade
'm': exportObj.RestrictedModification
|
[
{
"context": "esent both owned\n and shared resources.\n\n NOTE (chris): To really get these chained calls to work we ei",
"end": 660,
"score": 0.6398270130157471,
"start": 655,
"tag": "NAME",
"value": "chris"
}
] | src/core/initializers.relational/proxy.coffee | classdojo/mongoose-builder | 0 | ###
This module creates exports a relation proxy class
and also exports a handler that child_plugin can
inject into a mongoose schema.
###
###
class: RelationProxy
Responsible for piecing together the optional arguments
from a relational request.
eg.
options =
query: {some mongoose compliant restriction query}
permissions: <PermissionObject>
teacher.classes (err, classes) ->
By default only resources that the owner resource DIRECTLY owns
will be returned. See permission.coffee for information about
how to configure a Permissions object to represent both owned
and shared resources.
NOTE (chris): To really get these chained calls to work we either
need to modify the api with
teacher.classes({some query}).with("students").with("awardRecords")....
OR
use harmony proxies to create GET traps on the chain. Favoring harmony
proxies in the longterm..but short term will probably stick with some chained
method.
###
class RelationProxy
constructor: (thisModel, options) ->
@_currModel = thisModel
@_currOptions = @options
@_callStack = []
exec: (callback) ->
# if not callback?
# #this is a chained call
# q = @_buildMongooseQuery(@_currModel, @_currOptions)
# stackEntry =
# model: @_currModel
# options: @_currOptions
# cachedQuery: q
# # callChain should really be a list
# # of mongoose query objects
# @_callChain.push stackEntry
# return @
# else
if @_callStack.length isnt 0
#execute call stack
else
#this is a single call
if not utils.objectContains('own', @_currModel)
callback new Error("Object #{@_currModel} must inherit from type owner!"), null
else
q = @buildMongooseQuery(@_currModel, @_currOptions)
callback null, q
###
Decouple from current class variables @_curr* in case
we need to use this function in some sort of iteration.
eg.
for s in @_callStack
@buildMongooseQuery(s.model, s.options)
###
buildMongooseQuery: (model, options) ->
optional = {}
if options?
#handle options brah
optional = {}
myBaseQuery = model._ownQuery()
q = _.extend(myBaseQuery, optional) #optional fields can override base...
#also provide an index hint?
return q
###
Handle exposed to the actual mongoose model instance. Must inject with a reference
to mongoose model instances.
###
handle = (models, childInfo) ->
return (args...) ->
if _.isFunction(args[0]) || _.isFunction(args[1])
#create relation proxy and execute now
if _.isFunction(args[0])
fn = args[0]
rP = new RelationProxy(@, null)
else
fn = args[1]
rP = new RelationProxy(@, args[0])
rP.exec (err, query) =>
if err?
fn err, null
else
console.log "FULLY QUALIFIED", query
models[childInfo.name].find(query, fn)
# return @find(qualifiedQuery, args[0])
else
#this is a chained callback
throw new Error("Can't use chained calls yet :)")
rP = new RelationProxy(@, args[0])
return rP.exec()
exports.handle = handle
| 207702 | ###
This module creates exports a relation proxy class
and also exports a handler that child_plugin can
inject into a mongoose schema.
###
###
class: RelationProxy
Responsible for piecing together the optional arguments
from a relational request.
eg.
options =
query: {some mongoose compliant restriction query}
permissions: <PermissionObject>
teacher.classes (err, classes) ->
By default only resources that the owner resource DIRECTLY owns
will be returned. See permission.coffee for information about
how to configure a Permissions object to represent both owned
and shared resources.
NOTE (<NAME>): To really get these chained calls to work we either
need to modify the api with
teacher.classes({some query}).with("students").with("awardRecords")....
OR
use harmony proxies to create GET traps on the chain. Favoring harmony
proxies in the longterm..but short term will probably stick with some chained
method.
###
class RelationProxy
constructor: (thisModel, options) ->
@_currModel = thisModel
@_currOptions = @options
@_callStack = []
exec: (callback) ->
# if not callback?
# #this is a chained call
# q = @_buildMongooseQuery(@_currModel, @_currOptions)
# stackEntry =
# model: @_currModel
# options: @_currOptions
# cachedQuery: q
# # callChain should really be a list
# # of mongoose query objects
# @_callChain.push stackEntry
# return @
# else
if @_callStack.length isnt 0
#execute call stack
else
#this is a single call
if not utils.objectContains('own', @_currModel)
callback new Error("Object #{@_currModel} must inherit from type owner!"), null
else
q = @buildMongooseQuery(@_currModel, @_currOptions)
callback null, q
###
Decouple from current class variables @_curr* in case
we need to use this function in some sort of iteration.
eg.
for s in @_callStack
@buildMongooseQuery(s.model, s.options)
###
buildMongooseQuery: (model, options) ->
optional = {}
if options?
#handle options brah
optional = {}
myBaseQuery = model._ownQuery()
q = _.extend(myBaseQuery, optional) #optional fields can override base...
#also provide an index hint?
return q
###
Handle exposed to the actual mongoose model instance. Must inject with a reference
to mongoose model instances.
###
handle = (models, childInfo) ->
return (args...) ->
if _.isFunction(args[0]) || _.isFunction(args[1])
#create relation proxy and execute now
if _.isFunction(args[0])
fn = args[0]
rP = new RelationProxy(@, null)
else
fn = args[1]
rP = new RelationProxy(@, args[0])
rP.exec (err, query) =>
if err?
fn err, null
else
console.log "FULLY QUALIFIED", query
models[childInfo.name].find(query, fn)
# return @find(qualifiedQuery, args[0])
else
#this is a chained callback
throw new Error("Can't use chained calls yet :)")
rP = new RelationProxy(@, args[0])
return rP.exec()
exports.handle = handle
| true | ###
This module creates exports a relation proxy class
and also exports a handler that child_plugin can
inject into a mongoose schema.
###
###
class: RelationProxy
Responsible for piecing together the optional arguments
from a relational request.
eg.
options =
query: {some mongoose compliant restriction query}
permissions: <PermissionObject>
teacher.classes (err, classes) ->
By default only resources that the owner resource DIRECTLY owns
will be returned. See permission.coffee for information about
how to configure a Permissions object to represent both owned
and shared resources.
NOTE (PI:NAME:<NAME>END_PI): To really get these chained calls to work we either
need to modify the api with
teacher.classes({some query}).with("students").with("awardRecords")....
OR
use harmony proxies to create GET traps on the chain. Favoring harmony
proxies in the longterm..but short term will probably stick with some chained
method.
###
class RelationProxy
constructor: (thisModel, options) ->
@_currModel = thisModel
@_currOptions = @options
@_callStack = []
exec: (callback) ->
# if not callback?
# #this is a chained call
# q = @_buildMongooseQuery(@_currModel, @_currOptions)
# stackEntry =
# model: @_currModel
# options: @_currOptions
# cachedQuery: q
# # callChain should really be a list
# # of mongoose query objects
# @_callChain.push stackEntry
# return @
# else
if @_callStack.length isnt 0
#execute call stack
else
#this is a single call
if not utils.objectContains('own', @_currModel)
callback new Error("Object #{@_currModel} must inherit from type owner!"), null
else
q = @buildMongooseQuery(@_currModel, @_currOptions)
callback null, q
###
Decouple from current class variables @_curr* in case
we need to use this function in some sort of iteration.
eg.
for s in @_callStack
@buildMongooseQuery(s.model, s.options)
###
buildMongooseQuery: (model, options) ->
optional = {}
if options?
#handle options brah
optional = {}
myBaseQuery = model._ownQuery()
q = _.extend(myBaseQuery, optional) #optional fields can override base...
#also provide an index hint?
return q
###
Handle exposed to the actual mongoose model instance. Must inject with a reference
to mongoose model instances.
###
handle = (models, childInfo) ->
return (args...) ->
if _.isFunction(args[0]) || _.isFunction(args[1])
#create relation proxy and execute now
if _.isFunction(args[0])
fn = args[0]
rP = new RelationProxy(@, null)
else
fn = args[1]
rP = new RelationProxy(@, args[0])
rP.exec (err, query) =>
if err?
fn err, null
else
console.log "FULLY QUALIFIED", query
models[childInfo.name].find(query, fn)
# return @find(qualifiedQuery, args[0])
else
#this is a chained callback
throw new Error("Can't use chained calls yet :)")
rP = new RelationProxy(@, args[0])
return rP.exec()
exports.handle = handle
|
[
{
"context": " },(msg)=>\n @setAssetList msg.files\n #@app.client.sendRequest {\n # name: \"list_public_project_f",
"end": 6261,
"score": 0.92899090051651,
"start": 6251,
"tag": "EMAIL",
"value": "app.client"
},
{
"context": "\n div.appendChild author\n\n if @app... | static/js/explore/projectdetails.coffee | sksdutra/microstudio | 0 | class @ProjectDetails
constructor:(@app)->
@menu = ["code","sprites","sounds","music","assets","doc"]
for s in @menu
do (s)=>
document.getElementById("project-contents-menu-#{s}").addEventListener "click",()=>
@setSection s
@splitbar = new SplitBar("explore-project-details","horizontal")
@splitbar.setPosition(45)
@editor = ace.edit "project-contents-view-editor"
@editor.$blockScrolling = Infinity
@editor.setTheme("ace/theme/tomorrow_night_bright")
@editor.getSession().setMode("ace/mode/microscript")
@editor.setReadOnly(true)
@editor.getSession().setOptions
tabSize: 2
useSoftTabs: true
useWorker: false # disables lua autocorrection ; preserves syntax coloring
document.querySelector("#project-contents-source-import").addEventListener "click",()=>
return if not @app.project?
file = @selected_source
return if not file?
return if @imported_sources[file]
@imported_sources[file] = true
name = file.split(".")[0]
count = 1
while @app.project.getSource(name)?
count += 1
name = file.split(".")[0]+count
file = name+".ms"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "ms/#{file}"
content: @sources[@selected_source]
},(msg)=>
@app.project.updateSourceList()
@setSelectedSource(@selected_source)
document.getElementById("project-contents-sprite-import").addEventListener "click",()=>
return if not @app.project?
return if not @selected_sprite?
name = @selected_sprite.name
return if not name?
return if @imported_sprites[name]
@imported_sprites[name] = true
document.getElementById("project-contents-sprite-import").style.display = "none"
count = 1
base = name
while @app.project.getSprite(name)?
count += 1
name = base+count
data = @selected_sprite.saveData().split(",")[1]
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{name}.png"
properties:
frames: @selected_sprite.frames.length
fps: @selected_sprite.fps
content: data
},(msg)=>
@app.project.updateSpriteList()
document.querySelector("#project-contents-doc-import").addEventListener "click",()=>
return if not @app.project?
return if @imported_doc or not @doc?
@imported_doc = true
value = @app.doc_editor.editor.getValue()
if value? and value.length>0
value = value + "\n\n"+@doc
else
value = @doc
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "doc/doc.md"
content: value
},(msg)=>
@app.project.loadDoc()
document.querySelector("#project-contents-doc-import").classList.add "done"
document.querySelector("#project-contents-doc-import i").classList.add "fa-check"
document.querySelector("#project-contents-doc-import i").classList.remove "fa-download"
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get "Doc imported"
document.getElementById("post-project-comment-button").addEventListener "click",()=>
text = document.querySelector("#post-project-comment textarea").value
if text? and text.length>0
@postComment(text)
document.querySelector("#post-project-comment textarea").value = ""
document.getElementById("login-to-post-comment").addEventListener "click",()=>
@app.appui.showLoginPanel()
document.getElementById("validate-to-post-comment").addEventListener "click",()=>
@app.appui.setMainSection("usersettings")
set:(@project)->
@splitbar.update()
@sources = []
@sprites = []
@sounds = []
@music = []
@maps = []
@imported_sources = {}
@imported_sprites = {}
@imported_doc = false
document.querySelector("#project-contents-doc-import").classList.remove "done"
document.querySelector("#project-contents-doc-import").style.display = if @app.project? then "block" else "none"
document.querySelector("#project-contents-source-import").style.display = if @app.project? then "block" else "none"
if @app.project?
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get("Import doc to")+" "+@app.project.title
document.querySelector("#project-contents-view .code-list").innerHTML = ""
document.querySelector("#project-contents-view .sprite-list").innerHTML = ""
document.querySelector("#project-contents-view .sound-list").innerHTML = ""
document.querySelector("#project-contents-view .music-list").innerHTML = ""
document.querySelector("#project-contents-view .asset-list").innerHTML = ""
#document.querySelector("#project-contents-view .maps").innerHTML = ""
document.querySelector("#project-contents-view .doc-render").innerHTML = ""
section = "code"
for t in @project.tags
if t.indexOf("sprite")>=0
section = "sprites"
else if t.indexOf("tutorial")>=0 or t.indexOf("tutoriel")>=0
section = "doc"
if @project.type in ["tutorial","library"]
section = "doc"
@setSection(section)
@sources = {}
@selected_source = null
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "ms"
},(msg)=>
@setSourceList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sprites"
},(msg)=>
@setSpriteList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sounds"
},(msg)=>
@setSoundList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "music"
},(msg)=>
@setMusicList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "assets"
},(msg)=>
@setAssetList msg.files
#@app.client.sendRequest {
# name: "list_public_project_files"
# project: @project.id
# folder: "maps"
#},(msg)=>
# @setMapList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "doc"
},(msg)=>
@setDocList msg.files
@updateComments()
@updateCredentials()
a = document.querySelector("#project-contents-view .sprites .export-panel a")
a.href = "/#{@project.owner}/#{@project.slug}/export/sprites/"
a.download = "#{@project.slug}_sprites.zip"
a = document.querySelector("#project-details-exportbutton")
a.href = "/#{@project.owner}/#{@project.slug}/export/project/"
a.download = "#{@project.slug}_files.zip"
updateCredentials:()->
if @app.user?
document.getElementById("login-to-post-comment").style.display = "none"
if @app.user.flags.validated
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "block"
else
document.getElementById("validate-to-post-comment").style.display = "inline-block"
document.getElementById("post-project-comment").style.display = "none"
else
document.getElementById("login-to-post-comment").style.display = "inline-block"
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "none"
loadFile:(url,callback)->
req = new XMLHttpRequest()
req.onreadystatechange = (event) =>
if req.readyState == XMLHttpRequest.DONE
if req.status == 200
callback(req.responseText)
req.open "GET",url
req.send()
setSection:(section)->
for s in @menu
if s == section
document.getElementById("project-contents-menu-#{s}").classList.add "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "block"
else
document.getElementById("project-contents-menu-#{s}").classList.remove "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "none"
return
createSourceEntry:(file)->
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "ms/#{file}"
},(msg)=>
@sources[file] = msg.content
div = document.createElement "div"
div.innerHTML = "<i class='fa fa-file-code'></i> #{file.split(".")[0]}"
document.querySelector("#project-contents-view .code-list").appendChild div
div.id = "project-contents-view-source-#{file}"
div.addEventListener "click",()=>@setSelectedSource(file)
if not @selected_source?
@setSelectedSource(file)
setSelectedSource:(file)->
@selected_source = file
@source_folder.setSelectedItem file
source = @project_sources[file]
if source? and source.parent?
source.parent.setOpen true
@editor.setValue @sources[file],-1
return if not @app.project?
if @imported_sources[file]
document.querySelector("#project-contents-source-import").classList.add "done"
document.querySelector("#project-contents-source-import i").classList.remove "fa-download"
document.querySelector("#project-contents-source-import i").classList.add "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Source file imported")
else
document.querySelector("#project-contents-source-import").classList.remove "done"
document.querySelector("#project-contents-source-import i").classList.add "fa-download"
document.querySelector("#project-contents-source-import i").classList.remove "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Import source file to")+" "+@app.project.title
setSourceList:(files)->
# for f in files
# @createSourceEntry(f.file)
# return
table = {}
manager =
folder: "ms"
item: "source"
openItem:(item)=>
@setSelectedSource item
# table[item].play()
@project_sources = {}
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.app = @app
project.notifyListeners = (source)=>
@sources[source.name] = source.content
if not @selected_source?
@setSelectedSource(source.name)
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"source"
for f in files
s = new ExploreProjectSource project,f.file
@project_sources[s.name] = s
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .code-list")
@source_folder = view
view.editable = false
view.rebuildList folder
return
setSpriteList:(files)->
table = {}
@sprites = {}
manager =
folder: "sprites"
item: "sprite"
openItem:(item)=>
@sprites_folder_view.setSelectedItem item
@selected_sprite = @sprites[item]
if @app.project? and not @imported_sprites[item]
document.querySelector("#project-contents-sprite-import span").innerText = @app.translator.get("Import %ITEM% to project %PROJECT%").replace("%ITEM%",item.replace(/-/g,"/")).replace("%PROJECT%",@app.project.title)
document.getElementById("project-contents-sprite-import").style.display = "block"
else
document.getElementById("project-contents-sprite-import").style.display = "none"
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
project.map_list = []
project.notifyListeners = ()->
folder = new ProjectFolder null,"sprites"
for f in files
s = new ProjectSprite project,f.file,null,null,f.properties
folder.push s
table[s.name] = s
@sprites[s.name] = s
@sprites_folder_view = new FolderView manager,document.querySelector("#project-contents-view .sprite-list")
@sprites_folder_view.editable = false
@sprites_folder_view.rebuildList folder
document.getElementById("project-contents-sprite-import").style.display = "none"
return
setSoundList:(files)->
if files.length>0
document.getElementById("project-contents-menu-sounds").style.display = "block"
else
document.getElementById("project-contents-menu-sounds").style.display = "none"
table = {}
manager =
folder: "sounds"
item: "sound"
openItem:(item)->
table[item].play()
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"sounds"
for f in files
s = new ProjectSound project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .sound-list")
view.editable = false
view.rebuildList folder
return
setMusicList:(files)->
if files.length>0
document.getElementById("project-contents-menu-music").style.display = "block"
else
document.getElementById("project-contents-menu-music").style.display = "none"
table = {}
manager =
folder: "music"
item: "music"
openItem:(item)->
table[item].play()
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()=>
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"sounds"
for f in files
s = new ProjectMusic project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .music-list")
view.editable = false
view.rebuildList folder
return
setAssetList:(files)->
if files.length>0
document.getElementById("project-contents-menu-assets").style.display = "block"
else
document.getElementById("project-contents-menu-assets").style.display = "none"
table = {}
manager =
folder: "assets"
item: "asset"
openItem:(item)->
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"assets"
for f in files
s = new ProjectAsset project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .asset-list")
view.editable = false
view.rebuildList folder
return
setMapList:(files)->
console.info files
setDocList:(files)->
if files.length>0
document.getElementById("project-contents-menu-doc").style.display = "block"
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "doc/#{files[0].file}"
},(msg)=>
@doc = msg.content
if @doc? and @doc.trim().length>0
document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize marked msg.content
else
document.getElementById("project-contents-menu-doc").style.display = "none"
else
document.getElementById("project-contents-menu-doc").style.display = "none"
#console.info files
updateComments:()->
@app.client.sendRequest {
name: "get_project_comments"
project: @project.id
},(msg)=>
e = document.getElementById("project-comment-list")
e.innerHTML = ""
if msg.comments?
for c in msg.comments
@createCommentBox(c)
return
createCommentBox:(c)->
console.info c
div = document.createElement("div")
div.classList.add "comment"
author = document.createElement("div")
author.classList.add "author"
i = document.createElement("i")
i.classList.add "fa"
i.classList.add "fa-user"
span = document.createElement "span"
span.innerText = c.user
author.appendChild i
author.appendChild span
author = @app.appui.createUserTag(c.user,c.user_info.tier,c.user_info.profile_image,12)
time = document.createElement "div"
time.classList.add "time"
t = (Date.now()-c.time)/60000
if t<2
tt = @app.translator.get("now")
else if t<120
tt = @app.translator.get("%NUM% minutes ago").replace("%NUM%",Math.round(t))
else
t /= 60
if t<48
tt = @app.translator.get("%NUM% hours ago").replace("%NUM%",Math.round(t))
else
t/= 24
if t<14
tt = @app.translator.get("%NUM% days ago").replace("%NUM%",Math.round(t))
else if t<30
tt = @app.translator.get("%NUM% weeks ago").replace("%NUM%",Math.round(t/7))
else
tt = new Date(c.time).toLocaleDateString(@app.translator.lang,{ year: 'numeric', month: 'long', day: 'numeric' })
time.innerText = tt
div.appendChild time
div.appendChild author
if @app.user? and (@app.user.nick == c.user or @app.user.flags.admin)
buttons = document.createElement "div"
buttons.classList.add "buttons"
#buttons.appendChild @createButton "edit","Edit","green",()=>
# @editComment c
#buttons.appendChild document.createElement "br"
buttons.appendChild @createButton "trash",@app.translator.get("Delete"),"red",()=>
@deleteComment c
div.appendChild buttons
contents = document.createElement "div"
contents.classList.add "contents"
contents.innerHTML = DOMPurify.sanitize marked c.text
div.appendChild contents
clear = document.createElement "div"
clear.style = "clear:both"
div.appendChild clear
document.getElementById("project-comment-list").appendChild div
createButton:(icon,text,color,callback)->
button = document.createElement "div"
button.classList.add "small"+color+"button"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-#{icon}"
button.appendChild i
span = document.createElement "span"
span.innerText = text
button.appendChild span
button.addEventListener "click",()=>callback()
button
postComment:(text)->
@app.client.sendRequest {
name: "add_project_comment"
project: @project.id
text: text
},(msg)=>
@updateComments()
editComment:(id,text)->
deleteComment:(c)->
ConfirmDialog.confirm @app.translator.get("Do you really want to delete this comment?"),@app.translator.get("Delete"),@app.translator.get("Cancel"),()=>
@app.client.sendRequest {
name: "delete_project_comment"
project: @project.id
id: c.id
},(msg)=>
@updateComments()
class @ExploreProjectSource
constructor:(@project,@file,@size=0)->
@name = @file.split(".")[0]
@ext = @file.split(".")[1]
@filename = @file
@file = "ms/#{@file}"
s = @name.split "-"
@shortname = s[s.length-1]
@path_prefix = if s.length>1 then s.splice(0,s.length-1).join("-")+"-" else ""
@content = ""
@fetched = false
@reload()
reload:()->
fetch(@project.getFullURL()+"ms/#{@name}.ms").then (result)=>
result.text().then (text)=>
@content = text
@fetched = true
@project.notifyListeners @
| 136861 | class @ProjectDetails
constructor:(@app)->
@menu = ["code","sprites","sounds","music","assets","doc"]
for s in @menu
do (s)=>
document.getElementById("project-contents-menu-#{s}").addEventListener "click",()=>
@setSection s
@splitbar = new SplitBar("explore-project-details","horizontal")
@splitbar.setPosition(45)
@editor = ace.edit "project-contents-view-editor"
@editor.$blockScrolling = Infinity
@editor.setTheme("ace/theme/tomorrow_night_bright")
@editor.getSession().setMode("ace/mode/microscript")
@editor.setReadOnly(true)
@editor.getSession().setOptions
tabSize: 2
useSoftTabs: true
useWorker: false # disables lua autocorrection ; preserves syntax coloring
document.querySelector("#project-contents-source-import").addEventListener "click",()=>
return if not @app.project?
file = @selected_source
return if not file?
return if @imported_sources[file]
@imported_sources[file] = true
name = file.split(".")[0]
count = 1
while @app.project.getSource(name)?
count += 1
name = file.split(".")[0]+count
file = name+".ms"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "ms/#{file}"
content: @sources[@selected_source]
},(msg)=>
@app.project.updateSourceList()
@setSelectedSource(@selected_source)
document.getElementById("project-contents-sprite-import").addEventListener "click",()=>
return if not @app.project?
return if not @selected_sprite?
name = @selected_sprite.name
return if not name?
return if @imported_sprites[name]
@imported_sprites[name] = true
document.getElementById("project-contents-sprite-import").style.display = "none"
count = 1
base = name
while @app.project.getSprite(name)?
count += 1
name = base+count
data = @selected_sprite.saveData().split(",")[1]
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{name}.png"
properties:
frames: @selected_sprite.frames.length
fps: @selected_sprite.fps
content: data
},(msg)=>
@app.project.updateSpriteList()
document.querySelector("#project-contents-doc-import").addEventListener "click",()=>
return if not @app.project?
return if @imported_doc or not @doc?
@imported_doc = true
value = @app.doc_editor.editor.getValue()
if value? and value.length>0
value = value + "\n\n"+@doc
else
value = @doc
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "doc/doc.md"
content: value
},(msg)=>
@app.project.loadDoc()
document.querySelector("#project-contents-doc-import").classList.add "done"
document.querySelector("#project-contents-doc-import i").classList.add "fa-check"
document.querySelector("#project-contents-doc-import i").classList.remove "fa-download"
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get "Doc imported"
document.getElementById("post-project-comment-button").addEventListener "click",()=>
text = document.querySelector("#post-project-comment textarea").value
if text? and text.length>0
@postComment(text)
document.querySelector("#post-project-comment textarea").value = ""
document.getElementById("login-to-post-comment").addEventListener "click",()=>
@app.appui.showLoginPanel()
document.getElementById("validate-to-post-comment").addEventListener "click",()=>
@app.appui.setMainSection("usersettings")
set:(@project)->
@splitbar.update()
@sources = []
@sprites = []
@sounds = []
@music = []
@maps = []
@imported_sources = {}
@imported_sprites = {}
@imported_doc = false
document.querySelector("#project-contents-doc-import").classList.remove "done"
document.querySelector("#project-contents-doc-import").style.display = if @app.project? then "block" else "none"
document.querySelector("#project-contents-source-import").style.display = if @app.project? then "block" else "none"
if @app.project?
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get("Import doc to")+" "+@app.project.title
document.querySelector("#project-contents-view .code-list").innerHTML = ""
document.querySelector("#project-contents-view .sprite-list").innerHTML = ""
document.querySelector("#project-contents-view .sound-list").innerHTML = ""
document.querySelector("#project-contents-view .music-list").innerHTML = ""
document.querySelector("#project-contents-view .asset-list").innerHTML = ""
#document.querySelector("#project-contents-view .maps").innerHTML = ""
document.querySelector("#project-contents-view .doc-render").innerHTML = ""
section = "code"
for t in @project.tags
if t.indexOf("sprite")>=0
section = "sprites"
else if t.indexOf("tutorial")>=0 or t.indexOf("tutoriel")>=0
section = "doc"
if @project.type in ["tutorial","library"]
section = "doc"
@setSection(section)
@sources = {}
@selected_source = null
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "ms"
},(msg)=>
@setSourceList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sprites"
},(msg)=>
@setSpriteList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sounds"
},(msg)=>
@setSoundList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "music"
},(msg)=>
@setMusicList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "assets"
},(msg)=>
@setAssetList msg.files
#@<EMAIL>.sendRequest {
# name: "list_public_project_files"
# project: @project.id
# folder: "maps"
#},(msg)=>
# @setMapList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "doc"
},(msg)=>
@setDocList msg.files
@updateComments()
@updateCredentials()
a = document.querySelector("#project-contents-view .sprites .export-panel a")
a.href = "/#{@project.owner}/#{@project.slug}/export/sprites/"
a.download = "#{@project.slug}_sprites.zip"
a = document.querySelector("#project-details-exportbutton")
a.href = "/#{@project.owner}/#{@project.slug}/export/project/"
a.download = "#{@project.slug}_files.zip"
updateCredentials:()->
if @app.user?
document.getElementById("login-to-post-comment").style.display = "none"
if @app.user.flags.validated
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "block"
else
document.getElementById("validate-to-post-comment").style.display = "inline-block"
document.getElementById("post-project-comment").style.display = "none"
else
document.getElementById("login-to-post-comment").style.display = "inline-block"
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "none"
loadFile:(url,callback)->
req = new XMLHttpRequest()
req.onreadystatechange = (event) =>
if req.readyState == XMLHttpRequest.DONE
if req.status == 200
callback(req.responseText)
req.open "GET",url
req.send()
setSection:(section)->
for s in @menu
if s == section
document.getElementById("project-contents-menu-#{s}").classList.add "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "block"
else
document.getElementById("project-contents-menu-#{s}").classList.remove "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "none"
return
createSourceEntry:(file)->
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "ms/#{file}"
},(msg)=>
@sources[file] = msg.content
div = document.createElement "div"
div.innerHTML = "<i class='fa fa-file-code'></i> #{file.split(".")[0]}"
document.querySelector("#project-contents-view .code-list").appendChild div
div.id = "project-contents-view-source-#{file}"
div.addEventListener "click",()=>@setSelectedSource(file)
if not @selected_source?
@setSelectedSource(file)
setSelectedSource:(file)->
@selected_source = file
@source_folder.setSelectedItem file
source = @project_sources[file]
if source? and source.parent?
source.parent.setOpen true
@editor.setValue @sources[file],-1
return if not @app.project?
if @imported_sources[file]
document.querySelector("#project-contents-source-import").classList.add "done"
document.querySelector("#project-contents-source-import i").classList.remove "fa-download"
document.querySelector("#project-contents-source-import i").classList.add "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Source file imported")
else
document.querySelector("#project-contents-source-import").classList.remove "done"
document.querySelector("#project-contents-source-import i").classList.add "fa-download"
document.querySelector("#project-contents-source-import i").classList.remove "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Import source file to")+" "+@app.project.title
setSourceList:(files)->
# for f in files
# @createSourceEntry(f.file)
# return
table = {}
manager =
folder: "ms"
item: "source"
openItem:(item)=>
@setSelectedSource item
# table[item].play()
@project_sources = {}
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.app = @app
project.notifyListeners = (source)=>
@sources[source.name] = source.content
if not @selected_source?
@setSelectedSource(source.name)
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"source"
for f in files
s = new ExploreProjectSource project,f.file
@project_sources[s.name] = s
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .code-list")
@source_folder = view
view.editable = false
view.rebuildList folder
return
setSpriteList:(files)->
table = {}
@sprites = {}
manager =
folder: "sprites"
item: "sprite"
openItem:(item)=>
@sprites_folder_view.setSelectedItem item
@selected_sprite = @sprites[item]
if @app.project? and not @imported_sprites[item]
document.querySelector("#project-contents-sprite-import span").innerText = @app.translator.get("Import %ITEM% to project %PROJECT%").replace("%ITEM%",item.replace(/-/g,"/")).replace("%PROJECT%",@app.project.title)
document.getElementById("project-contents-sprite-import").style.display = "block"
else
document.getElementById("project-contents-sprite-import").style.display = "none"
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
project.map_list = []
project.notifyListeners = ()->
folder = new ProjectFolder null,"sprites"
for f in files
s = new ProjectSprite project,f.file,null,null,f.properties
folder.push s
table[s.name] = s
@sprites[s.name] = s
@sprites_folder_view = new FolderView manager,document.querySelector("#project-contents-view .sprite-list")
@sprites_folder_view.editable = false
@sprites_folder_view.rebuildList folder
document.getElementById("project-contents-sprite-import").style.display = "none"
return
setSoundList:(files)->
if files.length>0
document.getElementById("project-contents-menu-sounds").style.display = "block"
else
document.getElementById("project-contents-menu-sounds").style.display = "none"
table = {}
manager =
folder: "sounds"
item: "sound"
openItem:(item)->
table[item].play()
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"sounds"
for f in files
s = new ProjectSound project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .sound-list")
view.editable = false
view.rebuildList folder
return
setMusicList:(files)->
if files.length>0
document.getElementById("project-contents-menu-music").style.display = "block"
else
document.getElementById("project-contents-menu-music").style.display = "none"
table = {}
manager =
folder: "music"
item: "music"
openItem:(item)->
table[item].play()
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()=>
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"sounds"
for f in files
s = new ProjectMusic project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .music-list")
view.editable = false
view.rebuildList folder
return
setAssetList:(files)->
if files.length>0
document.getElementById("project-contents-menu-assets").style.display = "block"
else
document.getElementById("project-contents-menu-assets").style.display = "none"
table = {}
manager =
folder: "assets"
item: "asset"
openItem:(item)->
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"assets"
for f in files
s = new ProjectAsset project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .asset-list")
view.editable = false
view.rebuildList folder
return
setMapList:(files)->
console.info files
setDocList:(files)->
if files.length>0
document.getElementById("project-contents-menu-doc").style.display = "block"
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "doc/#{files[0].file}"
},(msg)=>
@doc = msg.content
if @doc? and @doc.trim().length>0
document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize marked msg.content
else
document.getElementById("project-contents-menu-doc").style.display = "none"
else
document.getElementById("project-contents-menu-doc").style.display = "none"
#console.info files
updateComments:()->
@app.client.sendRequest {
name: "get_project_comments"
project: @project.id
},(msg)=>
e = document.getElementById("project-comment-list")
e.innerHTML = ""
if msg.comments?
for c in msg.comments
@createCommentBox(c)
return
createCommentBox:(c)->
console.info c
div = document.createElement("div")
div.classList.add "comment"
author = document.createElement("div")
author.classList.add "author"
i = document.createElement("i")
i.classList.add "fa"
i.classList.add "fa-user"
span = document.createElement "span"
span.innerText = c.user
author.appendChild i
author.appendChild span
author = @app.appui.createUserTag(c.user,c.user_info.tier,c.user_info.profile_image,12)
time = document.createElement "div"
time.classList.add "time"
t = (Date.now()-c.time)/60000
if t<2
tt = @app.translator.get("now")
else if t<120
tt = @app.translator.get("%NUM% minutes ago").replace("%NUM%",Math.round(t))
else
t /= 60
if t<48
tt = @app.translator.get("%NUM% hours ago").replace("%NUM%",Math.round(t))
else
t/= 24
if t<14
tt = @app.translator.get("%NUM% days ago").replace("%NUM%",Math.round(t))
else if t<30
tt = @app.translator.get("%NUM% weeks ago").replace("%NUM%",Math.round(t/7))
else
tt = new Date(c.time).toLocaleDateString(@app.translator.lang,{ year: 'numeric', month: 'long', day: 'numeric' })
time.innerText = tt
div.appendChild time
div.appendChild author
if @app.user? and (@app.user.nick == c.user or @app.user.flags.admin)
buttons = document.createElement "div"
buttons.classList.add "buttons"
#buttons.appendChild @createButton "edit","Edit","green",()=>
# @editComment c
#buttons.appendChild document.createElement "br"
buttons.appendChild @createButton "trash",@app.translator.get("Delete"),"red",()=>
@deleteComment c
div.appendChild buttons
contents = document.createElement "div"
contents.classList.add "contents"
contents.innerHTML = DOMPurify.sanitize marked c.text
div.appendChild contents
clear = document.createElement "div"
clear.style = "clear:both"
div.appendChild clear
document.getElementById("project-comment-list").appendChild div
createButton:(icon,text,color,callback)->
button = document.createElement "div"
button.classList.add "small"+color+"button"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-#{icon}"
button.appendChild i
span = document.createElement "span"
span.innerText = text
button.appendChild span
button.addEventListener "click",()=>callback()
button
postComment:(text)->
@app.client.sendRequest {
name: "add_project_comment"
project: @project.id
text: text
},(msg)=>
@updateComments()
editComment:(id,text)->
deleteComment:(c)->
ConfirmDialog.confirm @app.translator.get("Do you really want to delete this comment?"),@app.translator.get("Delete"),@app.translator.get("Cancel"),()=>
@app.client.sendRequest {
name: "delete_project_comment"
project: @project.id
id: c.id
},(msg)=>
@updateComments()
class @ExploreProjectSource
constructor:(@project,@file,@size=0)->
@name = @file.split(".")[0]
@ext = @file.split(".")[1]
@filename = @file
@file = "ms/#{@file}"
s = @name.split "-"
@shortname = s[s.length-1]
@path_prefix = if s.length>1 then s.splice(0,s.length-1).join("-")+"-" else ""
@content = ""
@fetched = false
@reload()
reload:()->
fetch(@project.getFullURL()+"ms/#{@name}.ms").then (result)=>
result.text().then (text)=>
@content = text
@fetched = true
@project.notifyListeners @
| true | class @ProjectDetails
constructor:(@app)->
@menu = ["code","sprites","sounds","music","assets","doc"]
for s in @menu
do (s)=>
document.getElementById("project-contents-menu-#{s}").addEventListener "click",()=>
@setSection s
@splitbar = new SplitBar("explore-project-details","horizontal")
@splitbar.setPosition(45)
@editor = ace.edit "project-contents-view-editor"
@editor.$blockScrolling = Infinity
@editor.setTheme("ace/theme/tomorrow_night_bright")
@editor.getSession().setMode("ace/mode/microscript")
@editor.setReadOnly(true)
@editor.getSession().setOptions
tabSize: 2
useSoftTabs: true
useWorker: false # disables lua autocorrection ; preserves syntax coloring
document.querySelector("#project-contents-source-import").addEventListener "click",()=>
return if not @app.project?
file = @selected_source
return if not file?
return if @imported_sources[file]
@imported_sources[file] = true
name = file.split(".")[0]
count = 1
while @app.project.getSource(name)?
count += 1
name = file.split(".")[0]+count
file = name+".ms"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "ms/#{file}"
content: @sources[@selected_source]
},(msg)=>
@app.project.updateSourceList()
@setSelectedSource(@selected_source)
document.getElementById("project-contents-sprite-import").addEventListener "click",()=>
return if not @app.project?
return if not @selected_sprite?
name = @selected_sprite.name
return if not name?
return if @imported_sprites[name]
@imported_sprites[name] = true
document.getElementById("project-contents-sprite-import").style.display = "none"
count = 1
base = name
while @app.project.getSprite(name)?
count += 1
name = base+count
data = @selected_sprite.saveData().split(",")[1]
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{name}.png"
properties:
frames: @selected_sprite.frames.length
fps: @selected_sprite.fps
content: data
},(msg)=>
@app.project.updateSpriteList()
document.querySelector("#project-contents-doc-import").addEventListener "click",()=>
return if not @app.project?
return if @imported_doc or not @doc?
@imported_doc = true
value = @app.doc_editor.editor.getValue()
if value? and value.length>0
value = value + "\n\n"+@doc
else
value = @doc
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "doc/doc.md"
content: value
},(msg)=>
@app.project.loadDoc()
document.querySelector("#project-contents-doc-import").classList.add "done"
document.querySelector("#project-contents-doc-import i").classList.add "fa-check"
document.querySelector("#project-contents-doc-import i").classList.remove "fa-download"
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get "Doc imported"
document.getElementById("post-project-comment-button").addEventListener "click",()=>
text = document.querySelector("#post-project-comment textarea").value
if text? and text.length>0
@postComment(text)
document.querySelector("#post-project-comment textarea").value = ""
document.getElementById("login-to-post-comment").addEventListener "click",()=>
@app.appui.showLoginPanel()
document.getElementById("validate-to-post-comment").addEventListener "click",()=>
@app.appui.setMainSection("usersettings")
set:(@project)->
@splitbar.update()
@sources = []
@sprites = []
@sounds = []
@music = []
@maps = []
@imported_sources = {}
@imported_sprites = {}
@imported_doc = false
document.querySelector("#project-contents-doc-import").classList.remove "done"
document.querySelector("#project-contents-doc-import").style.display = if @app.project? then "block" else "none"
document.querySelector("#project-contents-source-import").style.display = if @app.project? then "block" else "none"
if @app.project?
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get("Import doc to")+" "+@app.project.title
document.querySelector("#project-contents-view .code-list").innerHTML = ""
document.querySelector("#project-contents-view .sprite-list").innerHTML = ""
document.querySelector("#project-contents-view .sound-list").innerHTML = ""
document.querySelector("#project-contents-view .music-list").innerHTML = ""
document.querySelector("#project-contents-view .asset-list").innerHTML = ""
#document.querySelector("#project-contents-view .maps").innerHTML = ""
document.querySelector("#project-contents-view .doc-render").innerHTML = ""
section = "code"
for t in @project.tags
if t.indexOf("sprite")>=0
section = "sprites"
else if t.indexOf("tutorial")>=0 or t.indexOf("tutoriel")>=0
section = "doc"
if @project.type in ["tutorial","library"]
section = "doc"
@setSection(section)
@sources = {}
@selected_source = null
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "ms"
},(msg)=>
@setSourceList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sprites"
},(msg)=>
@setSpriteList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sounds"
},(msg)=>
@setSoundList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "music"
},(msg)=>
@setMusicList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "assets"
},(msg)=>
@setAssetList msg.files
#@PI:EMAIL:<EMAIL>END_PI.sendRequest {
# name: "list_public_project_files"
# project: @project.id
# folder: "maps"
#},(msg)=>
# @setMapList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "doc"
},(msg)=>
@setDocList msg.files
@updateComments()
@updateCredentials()
a = document.querySelector("#project-contents-view .sprites .export-panel a")
a.href = "/#{@project.owner}/#{@project.slug}/export/sprites/"
a.download = "#{@project.slug}_sprites.zip"
a = document.querySelector("#project-details-exportbutton")
a.href = "/#{@project.owner}/#{@project.slug}/export/project/"
a.download = "#{@project.slug}_files.zip"
updateCredentials:()->
if @app.user?
document.getElementById("login-to-post-comment").style.display = "none"
if @app.user.flags.validated
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "block"
else
document.getElementById("validate-to-post-comment").style.display = "inline-block"
document.getElementById("post-project-comment").style.display = "none"
else
document.getElementById("login-to-post-comment").style.display = "inline-block"
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "none"
loadFile:(url,callback)->
req = new XMLHttpRequest()
req.onreadystatechange = (event) =>
if req.readyState == XMLHttpRequest.DONE
if req.status == 200
callback(req.responseText)
req.open "GET",url
req.send()
setSection:(section)->
for s in @menu
if s == section
document.getElementById("project-contents-menu-#{s}").classList.add "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "block"
else
document.getElementById("project-contents-menu-#{s}").classList.remove "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "none"
return
createSourceEntry:(file)->
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "ms/#{file}"
},(msg)=>
@sources[file] = msg.content
div = document.createElement "div"
div.innerHTML = "<i class='fa fa-file-code'></i> #{file.split(".")[0]}"
document.querySelector("#project-contents-view .code-list").appendChild div
div.id = "project-contents-view-source-#{file}"
div.addEventListener "click",()=>@setSelectedSource(file)
if not @selected_source?
@setSelectedSource(file)
setSelectedSource:(file)->
@selected_source = file
@source_folder.setSelectedItem file
source = @project_sources[file]
if source? and source.parent?
source.parent.setOpen true
@editor.setValue @sources[file],-1
return if not @app.project?
if @imported_sources[file]
document.querySelector("#project-contents-source-import").classList.add "done"
document.querySelector("#project-contents-source-import i").classList.remove "fa-download"
document.querySelector("#project-contents-source-import i").classList.add "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Source file imported")
else
document.querySelector("#project-contents-source-import").classList.remove "done"
document.querySelector("#project-contents-source-import i").classList.add "fa-download"
document.querySelector("#project-contents-source-import i").classList.remove "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Import source file to")+" "+@app.project.title
setSourceList:(files)->
# for f in files
# @createSourceEntry(f.file)
# return
table = {}
manager =
folder: "ms"
item: "source"
openItem:(item)=>
@setSelectedSource item
# table[item].play()
@project_sources = {}
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.app = @app
project.notifyListeners = (source)=>
@sources[source.name] = source.content
if not @selected_source?
@setSelectedSource(source.name)
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"source"
for f in files
s = new ExploreProjectSource project,f.file
@project_sources[s.name] = s
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .code-list")
@source_folder = view
view.editable = false
view.rebuildList folder
return
setSpriteList:(files)->
table = {}
@sprites = {}
manager =
folder: "sprites"
item: "sprite"
openItem:(item)=>
@sprites_folder_view.setSelectedItem item
@selected_sprite = @sprites[item]
if @app.project? and not @imported_sprites[item]
document.querySelector("#project-contents-sprite-import span").innerText = @app.translator.get("Import %ITEM% to project %PROJECT%").replace("%ITEM%",item.replace(/-/g,"/")).replace("%PROJECT%",@app.project.title)
document.getElementById("project-contents-sprite-import").style.display = "block"
else
document.getElementById("project-contents-sprite-import").style.display = "none"
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
project.map_list = []
project.notifyListeners = ()->
folder = new ProjectFolder null,"sprites"
for f in files
s = new ProjectSprite project,f.file,null,null,f.properties
folder.push s
table[s.name] = s
@sprites[s.name] = s
@sprites_folder_view = new FolderView manager,document.querySelector("#project-contents-view .sprite-list")
@sprites_folder_view.editable = false
@sprites_folder_view.rebuildList folder
document.getElementById("project-contents-sprite-import").style.display = "none"
return
setSoundList:(files)->
if files.length>0
document.getElementById("project-contents-menu-sounds").style.display = "block"
else
document.getElementById("project-contents-menu-sounds").style.display = "none"
table = {}
manager =
folder: "sounds"
item: "sound"
openItem:(item)->
table[item].play()
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"sounds"
for f in files
s = new ProjectSound project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .sound-list")
view.editable = false
view.rebuildList folder
return
setMusicList:(files)->
if files.length>0
document.getElementById("project-contents-menu-music").style.display = "block"
else
document.getElementById("project-contents-menu-music").style.display = "none"
table = {}
manager =
folder: "music"
item: "music"
openItem:(item)->
table[item].play()
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()=>
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"sounds"
for f in files
s = new ProjectMusic project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .music-list")
view.editable = false
view.rebuildList folder
return
setAssetList:(files)->
if files.length>0
document.getElementById("project-contents-menu-assets").style.display = "block"
else
document.getElementById("project-contents-menu-assets").style.display = "none"
table = {}
manager =
folder: "assets"
item: "asset"
openItem:(item)->
project = JSON.parse(JSON.stringify(@project)) # create a clone
project.getFullURL = ()->
url = location.origin+"/#{project.owner}/#{project.slug}/"
folder = new ProjectFolder null,"assets"
for f in files
s = new ProjectAsset project,f.file
folder.push s
table[s.name] = s
view = new FolderView manager,document.querySelector("#project-contents-view .asset-list")
view.editable = false
view.rebuildList folder
return
setMapList:(files)->
console.info files
setDocList:(files)->
if files.length>0
document.getElementById("project-contents-menu-doc").style.display = "block"
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "doc/#{files[0].file}"
},(msg)=>
@doc = msg.content
if @doc? and @doc.trim().length>0
document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize marked msg.content
else
document.getElementById("project-contents-menu-doc").style.display = "none"
else
document.getElementById("project-contents-menu-doc").style.display = "none"
#console.info files
updateComments:()->
@app.client.sendRequest {
name: "get_project_comments"
project: @project.id
},(msg)=>
e = document.getElementById("project-comment-list")
e.innerHTML = ""
if msg.comments?
for c in msg.comments
@createCommentBox(c)
return
createCommentBox:(c)->
console.info c
div = document.createElement("div")
div.classList.add "comment"
author = document.createElement("div")
author.classList.add "author"
i = document.createElement("i")
i.classList.add "fa"
i.classList.add "fa-user"
span = document.createElement "span"
span.innerText = c.user
author.appendChild i
author.appendChild span
author = @app.appui.createUserTag(c.user,c.user_info.tier,c.user_info.profile_image,12)
time = document.createElement "div"
time.classList.add "time"
t = (Date.now()-c.time)/60000
if t<2
tt = @app.translator.get("now")
else if t<120
tt = @app.translator.get("%NUM% minutes ago").replace("%NUM%",Math.round(t))
else
t /= 60
if t<48
tt = @app.translator.get("%NUM% hours ago").replace("%NUM%",Math.round(t))
else
t/= 24
if t<14
tt = @app.translator.get("%NUM% days ago").replace("%NUM%",Math.round(t))
else if t<30
tt = @app.translator.get("%NUM% weeks ago").replace("%NUM%",Math.round(t/7))
else
tt = new Date(c.time).toLocaleDateString(@app.translator.lang,{ year: 'numeric', month: 'long', day: 'numeric' })
time.innerText = tt
div.appendChild time
div.appendChild author
if @app.user? and (@app.user.nick == c.user or @app.user.flags.admin)
buttons = document.createElement "div"
buttons.classList.add "buttons"
#buttons.appendChild @createButton "edit","Edit","green",()=>
# @editComment c
#buttons.appendChild document.createElement "br"
buttons.appendChild @createButton "trash",@app.translator.get("Delete"),"red",()=>
@deleteComment c
div.appendChild buttons
contents = document.createElement "div"
contents.classList.add "contents"
contents.innerHTML = DOMPurify.sanitize marked c.text
div.appendChild contents
clear = document.createElement "div"
clear.style = "clear:both"
div.appendChild clear
document.getElementById("project-comment-list").appendChild div
createButton:(icon,text,color,callback)->
button = document.createElement "div"
button.classList.add "small"+color+"button"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-#{icon}"
button.appendChild i
span = document.createElement "span"
span.innerText = text
button.appendChild span
button.addEventListener "click",()=>callback()
button
postComment:(text)->
@app.client.sendRequest {
name: "add_project_comment"
project: @project.id
text: text
},(msg)=>
@updateComments()
editComment:(id,text)->
deleteComment:(c)->
ConfirmDialog.confirm @app.translator.get("Do you really want to delete this comment?"),@app.translator.get("Delete"),@app.translator.get("Cancel"),()=>
@app.client.sendRequest {
name: "delete_project_comment"
project: @project.id
id: c.id
},(msg)=>
@updateComments()
class @ExploreProjectSource
constructor:(@project,@file,@size=0)->
@name = @file.split(".")[0]
@ext = @file.split(".")[1]
@filename = @file
@file = "ms/#{@file}"
s = @name.split "-"
@shortname = s[s.length-1]
@path_prefix = if s.length>1 then s.splice(0,s.length-1).join("-")+"-" else ""
@content = ""
@fetched = false
@reload()
reload:()->
fetch(@project.getFullURL()+"ms/#{@name}.ms").then (result)=>
result.text().then (text)=>
@content = text
@fetched = true
@project.notifyListeners @
|
[
{
"context": " add = require(\"calc/add\")\n person = new Person(\"John\", \"Doe\")\n person.age = 18\n person.age = add(per",
"end": 196,
"score": 0.9996503591537476,
"start": 192,
"tag": "NAME",
"value": "John"
},
{
"context": "equire(\"calc/add\")\n person = new Person(\"John\... | source/code/my-main.coffee | anodynos/urequire-example-testbed | 0 | # uRequire Module Configuration
(urequire: rootExports: ["urequireExample", "uEx"], noConflict: true)
define ["models/Person"], (Person) ->
add = require("calc/add")
person = new Person("John", "Doe")
person.age = 18
person.age = add(person.age, 2)
# load 'calc/index.js' like node does, but works on AMD also
calc = require './calc'
# Again './' resolves to './index' which in turn loads 'calc/index.js'
calc2 = require './'
throw "requiring `./index` as './' failed" if calc isnt calc2
person.age = calc.multiply(person.age, 2)
homeTemplate = require("markup/home")
if __isNode
nodeOnlyVar = require("nodeOnly/runsOnlyOnNode")
console.log "Runs only on node:", require("util").inspect(nodeOnlyVar)
# lodash `_` is injected whole bundle using `dependencies: imports`
_.clone
person: person
add: add
calc: calc
homeHTML: homeTemplate("Universe!")
# `var VERSION = 'xx';` injected by 'inject-version' RC
VERSION: VERSION | 38063 | # uRequire Module Configuration
(urequire: rootExports: ["urequireExample", "uEx"], noConflict: true)
define ["models/Person"], (Person) ->
add = require("calc/add")
person = new Person("<NAME>", "<NAME>")
person.age = 18
person.age = add(person.age, 2)
# load 'calc/index.js' like node does, but works on AMD also
calc = require './calc'
# Again './' resolves to './index' which in turn loads 'calc/index.js'
calc2 = require './'
throw "requiring `./index` as './' failed" if calc isnt calc2
person.age = calc.multiply(person.age, 2)
homeTemplate = require("markup/home")
if __isNode
nodeOnlyVar = require("nodeOnly/runsOnlyOnNode")
console.log "Runs only on node:", require("util").inspect(nodeOnlyVar)
# lodash `_` is injected whole bundle using `dependencies: imports`
_.clone
person: person
add: add
calc: calc
homeHTML: homeTemplate("Universe!")
# `var VERSION = 'xx';` injected by 'inject-version' RC
VERSION: VERSION | true | # uRequire Module Configuration
(urequire: rootExports: ["urequireExample", "uEx"], noConflict: true)
define ["models/Person"], (Person) ->
add = require("calc/add")
person = new Person("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI")
person.age = 18
person.age = add(person.age, 2)
# load 'calc/index.js' like node does, but works on AMD also
calc = require './calc'
# Again './' resolves to './index' which in turn loads 'calc/index.js'
calc2 = require './'
throw "requiring `./index` as './' failed" if calc isnt calc2
person.age = calc.multiply(person.age, 2)
homeTemplate = require("markup/home")
if __isNode
nodeOnlyVar = require("nodeOnly/runsOnlyOnNode")
console.log "Runs only on node:", require("util").inspect(nodeOnlyVar)
# lodash `_` is injected whole bundle using `dependencies: imports`
_.clone
person: person
add: add
calc: calc
homeHTML: homeTemplate("Universe!")
# `var VERSION = 'xx';` injected by 'inject-version' RC
VERSION: VERSION |
[
{
"context": "tion-backbone-relational.js 0.3.4\n (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/backbone-articulati",
"end": 88,
"score": 0.9998214840888977,
"start": 74,
"tag": "NAME",
"value": "Kevin Malakoff"
},
{
"context": "js 0.3.4\n (c) 2011, 2012 Kevin Malakof... | src/backbone-relational/backbone-articulation-backbone-relational.coffee | kmalakoff/backbone-articulation | 2 | ###
backbone-articulation-backbone-relational.js 0.3.4
(c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/backbone-articulation/
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, and Underscore.js.
###
# import Underscore (or Lo-Dash with precedence), Backbone, Backbone Articultion and Backbone.Relational
_ = if not window._ and (typeof(require) isnt 'undefined') then require('underscore') else window._
_ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY
Backbone = if not @Backbone and (typeof(require) != 'undefined') then require('backbone') else @Backbone
Articulation = if not @Backbone.Articulation and (typeof(require) != 'undefined') then require('backbone-articulation') else @Backbone.Articulation
require('backbone-relational') if (typeof(require) != 'undefined')
# export Articulation namespace
module.exports = Articulation if (typeof(exports) != 'undefined')
##########################
# Articulation.RelationalModel
##########################
Articulation.BackboneRelationalModel = Backbone.RelationalModel.extend({
toJSON: ->
# If this Model has already been fully serialized in this branch once, return to avoid loops
return @id if @isLocked()
@acquire()
json = if @__bba_toJSON then @__bba_toJSON.call(this) else (throw 'Articulation.RelationalModel is not configured correctly')
for rel in @_relations
value = json[rel.key]
if rel.options.includeInJSON is true and value and (typeof (value) is "object")
json[rel.key] = (if _.isFunction(value.toJSON) then value.toJSON() else value)
else if _.isString(rel.options.includeInJSON)
unless value
json[rel.key] = null
else if value instanceof Backbone.Collection
json[rel.key] = value.pluck(rel.options.includeInJSON)
else if value instanceof Backbone.Model
json[rel.key] = value.get(rel.options.includeInJSON)
# POD array (serialized collection)
else if _.isArray(value)
json[rel.key] = []
for model_json, index in value
json[rel.key].push model_json[rel.options.includeInJSON] unless _.isUndefined(model_json)
# POD object (serialized model)
else if value instanceof Object
json[rel.key] = value[rel.options.includeInJSON]
else
delete json[rel.key]
@release()
return json
_reset: ->
# memory clean up
(Relational.Relational.store.unregister(model) for model in @models) if @models
@constructor.__super__.constructor.__super__._reset.apply(this, arguments)
})
# add Articulation.Model into Articulation.RelationalModel
Articulation.Model.mixin(Articulation.BackboneRelationalModel)
##########################
# Articulation.RelationalCollection
##########################
class Articulation.BackboneRelationalCollection extends Articulation.Collection
model: Articulation.BackboneRelationalModel | 4048 | ###
backbone-articulation-backbone-relational.js 0.3.4
(c) 2011, 2012 <NAME> - http://kmalakoff.github.com/backbone-articulation/
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, and Underscore.js.
###
# import Underscore (or Lo-Dash with precedence), Backbone, Backbone Articultion and Backbone.Relational
_ = if not window._ and (typeof(require) isnt 'undefined') then require('underscore') else window._
_ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY
Backbone = if not @Backbone and (typeof(require) != 'undefined') then require('backbone') else @Backbone
Articulation = if not @Backbone.Articulation and (typeof(require) != 'undefined') then require('backbone-articulation') else @Backbone.Articulation
require('backbone-relational') if (typeof(require) != 'undefined')
# export Articulation namespace
module.exports = Articulation if (typeof(exports) != 'undefined')
##########################
# Articulation.RelationalModel
##########################
Articulation.BackboneRelationalModel = Backbone.RelationalModel.extend({
toJSON: ->
# If this Model has already been fully serialized in this branch once, return to avoid loops
return @id if @isLocked()
@acquire()
json = if @__bba_toJSON then @__bba_toJSON.call(this) else (throw 'Articulation.RelationalModel is not configured correctly')
for rel in @_relations
value = json[rel.key]
if rel.options.includeInJSON is true and value and (typeof (value) is "object")
json[rel.key] = (if _.isFunction(value.toJSON) then value.toJSON() else value)
else if _.isString(rel.options.includeInJSON)
unless value
json[rel.key] = null
else if value instanceof Backbone.Collection
json[rel.key] = value.pluck(rel.options.includeInJSON)
else if value instanceof Backbone.Model
json[rel.key] = value.get(rel.options.includeInJSON)
# POD array (serialized collection)
else if _.isArray(value)
json[rel.key] = []
for model_json, index in value
json[rel.key].push model_json[rel.options.includeInJSON] unless _.isUndefined(model_json)
# POD object (serialized model)
else if value instanceof Object
json[rel.key] = value[rel.options.includeInJSON]
else
delete json[rel.key]
@release()
return json
_reset: ->
# memory clean up
(Relational.Relational.store.unregister(model) for model in @models) if @models
@constructor.__super__.constructor.__super__._reset.apply(this, arguments)
})
# add Articulation.Model into Articulation.RelationalModel
Articulation.Model.mixin(Articulation.BackboneRelationalModel)
##########################
# Articulation.RelationalCollection
##########################
class Articulation.BackboneRelationalCollection extends Articulation.Collection
model: Articulation.BackboneRelationalModel | true | ###
backbone-articulation-backbone-relational.js 0.3.4
(c) 2011, 2012 PI:NAME:<NAME>END_PI - http://kmalakoff.github.com/backbone-articulation/
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, and Underscore.js.
###
# import Underscore (or Lo-Dash with precedence), Backbone, Backbone Articultion and Backbone.Relational
_ = if not window._ and (typeof(require) isnt 'undefined') then require('underscore') else window._
_ = _._ if _ and (_.hasOwnProperty('_')) # LEGACY
Backbone = if not @Backbone and (typeof(require) != 'undefined') then require('backbone') else @Backbone
Articulation = if not @Backbone.Articulation and (typeof(require) != 'undefined') then require('backbone-articulation') else @Backbone.Articulation
require('backbone-relational') if (typeof(require) != 'undefined')
# export Articulation namespace
module.exports = Articulation if (typeof(exports) != 'undefined')
##########################
# Articulation.RelationalModel
##########################
Articulation.BackboneRelationalModel = Backbone.RelationalModel.extend({
toJSON: ->
# If this Model has already been fully serialized in this branch once, return to avoid loops
return @id if @isLocked()
@acquire()
json = if @__bba_toJSON then @__bba_toJSON.call(this) else (throw 'Articulation.RelationalModel is not configured correctly')
for rel in @_relations
value = json[rel.key]
if rel.options.includeInJSON is true and value and (typeof (value) is "object")
json[rel.key] = (if _.isFunction(value.toJSON) then value.toJSON() else value)
else if _.isString(rel.options.includeInJSON)
unless value
json[rel.key] = null
else if value instanceof Backbone.Collection
json[rel.key] = value.pluck(rel.options.includeInJSON)
else if value instanceof Backbone.Model
json[rel.key] = value.get(rel.options.includeInJSON)
# POD array (serialized collection)
else if _.isArray(value)
json[rel.key] = []
for model_json, index in value
json[rel.key].push model_json[rel.options.includeInJSON] unless _.isUndefined(model_json)
# POD object (serialized model)
else if value instanceof Object
json[rel.key] = value[rel.options.includeInJSON]
else
delete json[rel.key]
@release()
return json
_reset: ->
# memory clean up
(Relational.Relational.store.unregister(model) for model in @models) if @models
@constructor.__super__.constructor.__super__._reset.apply(this, arguments)
})
# add Articulation.Model into Articulation.RelationalModel
Articulation.Model.mixin(Articulation.BackboneRelationalModel)
##########################
# Articulation.RelationalCollection
##########################
class Articulation.BackboneRelationalCollection extends Articulation.Collection
model: Articulation.BackboneRelationalModel |
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nmodule.exports =\n RootID:",
"end": 35,
"score": 0.9997588396072388,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/core/constants.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
module.exports =
RootID: 'FoldingText'
ObjectReplacementCharacter: '\ufffc'
LineSeparatorCharacter: '\u2028'
ParagraphSeparatorCharacter: '\u2029'
FTMLMimeType: 'text/ftml+html'
OPMLMimeType: 'text/opml+xml'
URIListMimeType: 'text/uri-list'
HTMLMimeType: 'text/html'
TEXTMimeType: 'text/plain' | 196705 | # Copyright (c) 2015 <NAME>. All rights reserved.
module.exports =
RootID: 'FoldingText'
ObjectReplacementCharacter: '\ufffc'
LineSeparatorCharacter: '\u2028'
ParagraphSeparatorCharacter: '\u2029'
FTMLMimeType: 'text/ftml+html'
OPMLMimeType: 'text/opml+xml'
URIListMimeType: 'text/uri-list'
HTMLMimeType: 'text/html'
TEXTMimeType: 'text/plain' | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
module.exports =
RootID: 'FoldingText'
ObjectReplacementCharacter: '\ufffc'
LineSeparatorCharacter: '\u2028'
ParagraphSeparatorCharacter: '\u2029'
FTMLMimeType: 'text/ftml+html'
OPMLMimeType: 'text/opml+xml'
URIListMimeType: 'text/uri-list'
HTMLMimeType: 'text/html'
TEXTMimeType: 'text/plain' |
[
{
"context": "nerateRandomString()\n password : 'testpass'\n passwordConfirm : 'testpass'\n\n prof",
"end": 1366,
"score": 0.9994670152664185,
"start": 1358,
"tag": "PASSWORD",
"value": "testpass"
},
{
"context": " : 'testpass'\n passwordConf... | servers/lib/server/handlers/getprofile.test.coffee | ezgikaysi/koding | 1 | { async
expect
request
generateRandomEmail
generateRandomString } = require '../../../testhelper'
{ generateRegisterRequestParams } = require '../../../testhelper/handler/registerhelper'
{ generateGetProfileRequestParams } = require '../../../testhelper/handler/getprofilehelper'
JUser = require '../../../models/user'
JAccount = require '../../../models/account'
# begin tests
describe 'server.handlers.getprofile', ->
it 'should send HTTP 404 if user is not found for the given email.', (done) ->
queue = []
methods = ['post', 'get', 'put', 'patch']
email = generateRandomEmail()
methods.forEach (method) ->
requestParams = generateGetProfileRequestParams { email, method }
queue.push (next) ->
request requestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 404
expect(body).to.be.equal 'no user found'
next()
async.series queue, done
it 'should send HTTP 200 if user is found for the given email.', (done) ->
queue = []
email = generateRandomEmail()
registerRequestParams = generateRegisterRequestParams
method : 'post'
body :
email : email
username : generateRandomString()
password : 'testpass'
passwordConfirm : 'testpass'
profileRequestParams = generateGetProfileRequestParams { email, method : 'post' }
queue.push (next) ->
request registerRequestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 200
next()
queue.push (next) ->
request profileRequestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 200
next()
async.series queue, done
| 7139 | { async
expect
request
generateRandomEmail
generateRandomString } = require '../../../testhelper'
{ generateRegisterRequestParams } = require '../../../testhelper/handler/registerhelper'
{ generateGetProfileRequestParams } = require '../../../testhelper/handler/getprofilehelper'
JUser = require '../../../models/user'
JAccount = require '../../../models/account'
# begin tests
describe 'server.handlers.getprofile', ->
it 'should send HTTP 404 if user is not found for the given email.', (done) ->
queue = []
methods = ['post', 'get', 'put', 'patch']
email = generateRandomEmail()
methods.forEach (method) ->
requestParams = generateGetProfileRequestParams { email, method }
queue.push (next) ->
request requestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 404
expect(body).to.be.equal 'no user found'
next()
async.series queue, done
it 'should send HTTP 200 if user is found for the given email.', (done) ->
queue = []
email = generateRandomEmail()
registerRequestParams = generateRegisterRequestParams
method : 'post'
body :
email : email
username : generateRandomString()
password : '<PASSWORD>'
passwordConfirm : '<PASSWORD>'
profileRequestParams = generateGetProfileRequestParams { email, method : 'post' }
queue.push (next) ->
request registerRequestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 200
next()
queue.push (next) ->
request profileRequestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 200
next()
async.series queue, done
| true | { async
expect
request
generateRandomEmail
generateRandomString } = require '../../../testhelper'
{ generateRegisterRequestParams } = require '../../../testhelper/handler/registerhelper'
{ generateGetProfileRequestParams } = require '../../../testhelper/handler/getprofilehelper'
JUser = require '../../../models/user'
JAccount = require '../../../models/account'
# begin tests
describe 'server.handlers.getprofile', ->
it 'should send HTTP 404 if user is not found for the given email.', (done) ->
queue = []
methods = ['post', 'get', 'put', 'patch']
email = generateRandomEmail()
methods.forEach (method) ->
requestParams = generateGetProfileRequestParams { email, method }
queue.push (next) ->
request requestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 404
expect(body).to.be.equal 'no user found'
next()
async.series queue, done
it 'should send HTTP 200 if user is found for the given email.', (done) ->
queue = []
email = generateRandomEmail()
registerRequestParams = generateRegisterRequestParams
method : 'post'
body :
email : email
username : generateRandomString()
password : 'PI:PASSWORD:<PASSWORD>END_PI'
passwordConfirm : 'PI:PASSWORD:<PASSWORD>END_PI'
profileRequestParams = generateGetProfileRequestParams { email, method : 'post' }
queue.push (next) ->
request registerRequestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 200
next()
queue.push (next) ->
request profileRequestParams, (err, res, body) ->
expect(err).to.not.exist
expect(res.statusCode).to.be.equal 200
next()
async.series queue, done
|
[
{
"context": "e = @Selectorablium(@$el, @options)\n @key = 10101\n @value = 'test'\n\n afterEach ->\n @s",
"end": 17643,
"score": 0.8986207842826843,
"start": 17640,
"tag": "KEY",
"value": "010"
}
] | spec/selectorablium_spec.coffee | skroutz/selectorablium | 7 | toggle_plugin_tests = ->
context 'when @state is "disabled"', ->
beforeEach ->
@instance.state = 'disabled'
@trigger()
it 'does not call hide', ->
expect(@hide_spy).to.not.be.called
it 'does not call show', ->
expect(@show_spy).to.not.be.called
context 'when @state is "visible"', ->
beforeEach ->
@instance.state = 'visible'
@trigger()
it 'hides the plugin', ->
expect(@hide_spy).to.be.calledOnce
context 'when @state is "ready"', ->
beforeEach ->
@instance.state = 'ready'
@trigger()
it 'shows the plugin', ->
expect(@show_spy).to.be.calledOnce
describe 'Selectorablium', ->
@timeout(0) # Disable the spec's timeout
before (done)->
## MOCK STORAGE
window.__requirejs__.clearRequireState()
# mock Session
requirejs.undef 'storage_freak'
@storage_init_deferred = storage_init_deferred = new $.Deferred()
class StorageFreak
constructor: ->
on: ->
init: -> return storage_init_deferred
searchByKey: ->
search: ->
cleanup: ->
add: ->
@storage_mock = StorageFreak
@storage_spy = sinon.spy this, 'storage_mock'
@storage_search_spy = sinon.spy StorageFreak::, 'search'
define 'storage_freak', [], =>
return @storage_mock
@respond_to_db_creates = ->
for request in @requests
if request.url is 'shops.json'
request.respond 200, { "Content-Type": "application/json" }, @shops_json
else if request.url is 'makers.json'
request.respond 200, { "Content-Type": "application/json" }, @makers_json
@options =
app_name: "selectorablium_test"
[@shops_obj, @makers_obj] = fixture.load('shops.json', 'makers.json')
fixture.load 'shops.html'
@makers_json = JSON.stringify @makers_obj
@shops_json = JSON.stringify @shops_obj
@$el = $(".selectorablium.shops")
@init = (el = @$el, options = @options, respond = true)=>
@instance = new @Selectorablium el, options
@$el.data 'Selectorablium', @instance
respond and @respond_to_db_creates()
require ['selectorablium'], (Selectorablium)=>
@Selectorablium = Selectorablium
done()
after ->
requirejs.undef 'storage_freak'
window.__requirejs__.clearRequireState()
beforeEach ->
@requests = []
@xhr = sinon.useFakeXMLHttpRequest()
@xhr.onCreate = (xhr)=> @requests.push xhr
@data = [
{
id: 4
name: 'zero1'
},
{
id: 5
name: 'zero2'
},
{
id: 6
name: 'zero3'
}
]
@data2 = [
{
id: 3
name: 'zero0'
},
{
id: 4
name: 'zero1'
},
{
id: 5
name: 'zero2'
},
{
id: 6
name: 'zero3'
}
]
afterEach ->
$(".selectorablium").each -> $(this).data('Selectorablium')?.cleanup()
@xhr.restore()
window.localStorage && localStorage.clear()
@storage_spy.reset()
@storage_search_spy.reset()
describe '.constructor', ->
it 'returns an instance when called without new', ->
instance = @Selectorablium(@$el, @options)
expect(instance).to.be.an.instanceof(@Selectorablium)
instance.cleanup()
it 'thows if no element is given', ->
expect(@Selectorablium).to.throw(/Element argument is required/)
it 'thows if not required options are given', ->
expect(=>@Selectorablium(@$el)).to.throw(/option is required/)
it 'initializes @state to "disabled"', ->
@init()
expect(@instance.state).to.equal('disabled')
it 'get a Storage instance', ->
@init()
expect(@storage_spy).to.be.calledWithNew
it 'creates HTML', ->
@init()
template = """<div class="selectorablium_outer_cont"><select class="selectorablium shops" name="eshop_id" data-url="shops.json" data-query="query" data-name="shops" data-default_value="" data-default_text="Choose eshop" data-selected_id="3"><option value="">Choose eshop</option></select><div class="selectorablium_cont">
<div class="top">
<div class="initial_loader">Loading initial data...</div>
<a class="clear_button">Clear</a>
</div>
<div class="inner_container">
<form>
<input autocomplete="off" name="var_name">
<span class="input_icon"></span>
<div class="loader"></div>
<div class="XHRCounter"></div>
</form>
<ul class="list_container"></ul>
</div>
</div></div>"""
expect($(fixture.el).html()).to.equal(template)
it 'registers handlers on HTML elements', ->
@init()
expect(@instance.events_handled).to.have.length(9)
it 'registers handlers for storage events', ->
spy = sinon.spy @storage_mock::, 'on'
@init()
expect(spy).to.have.callCount(8)
spy.restore()
it 'inits storage', ->
spy = sinon.spy @storage_mock::, 'init'
@init()
expect(spy).to.be.calledOnce
spy.restore()
describe 'HTML Events', ->
beforeEach ->
@init()
@show_spy = sinon.spy @instance, '_show'
@hide_spy = sinon.spy @instance, '_hide'
afterEach ->
@show_spy.restore()
@hide_spy.restore()
context '@$top element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$top.triggerHandler 'click'
toggle_plugin_tests()
context '@$el element', ->
context 'on focus', ->
beforeEach ->
@trigger = => @instance.$el.triggerHandler 'focus'
toggle_plugin_tests()
context '@$container element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$container.triggerHandler 'click'
it 'sets @do_not_hide_me to true', ->
@trigger()
expect(@instance.do_not_hide_me).to.be.true
context '@$clear_button element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$clear_button.triggerHandler 'click'
it 'resets the plugin', ->
spy = sinon.spy @instance, 'reset'
@trigger()
expect(spy).to.be.calledOnce
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger()
expect(spy).to.be.calledOnce
context 'html element', ->
context 'on click', ->
beforeEach ->
@trigger = => $('html').triggerHandler 'click'
context 'when @do_not_hide_me is true', ->
beforeEach ->
@instance.do_not_hide_me = true
it 'sets @do_not_hide_me to false', ->
@trigger()
expect(@instance.do_not_hide_me).to.be.false
context 'when @do_not_hide_me is false', ->
beforeEach ->
@instance.do_not_hide_me = false
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
context 'result element', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
context 'on mouseenter', ->
beforeEach ->
@$selected_element = @instance.selected_item
@$last_element = @instance.$result_items.last()
@trigger = => @$last_element.trigger 'mouseenter'
it 'deselects previously selected element', ->
@trigger()
expect(@instance.selected_item[0]).to.not.equal(@$selected_element[0])
it 'selects mouseentered element', ->
@trigger()
expect(@instance.selected_item[0]).to.equal(@$last_element[0])
context 'on click', ->
beforeEach ->
@$last_element = @instance.$result_items.last()
@trigger = =>
@$last_element.trigger 'mouseenter'
@$last_element.trigger 'click'
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger()
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="6">zero3</option>'
@trigger()
expect(@instance.$el.html()).to.equal expected_template
context '@$input element', ->
context 'on keyup', ->
beforeEach ->
@event = jQuery.Event 'keyup', { keyCode: 55 }
@trigger = => @instance.$input.triggerHandler @event
@clock = sinon.useFakeTimers()
afterEach ->
@clock.restore()
context 'when key is not a character', ->
beforeEach ->
@event = jQuery.Event 'keyup', { keyCode: 39 }
@trigger = => @instance.$input.triggerHandler @event
it 'returns false', ->
expect(@trigger()).to.be.false
context 'when key is shift', ->
beforeEach ->
@instance.shift_pressed = true
event = jQuery.Event 'keyup', { keyCode: 16 }
@trigger = => @instance.$input.triggerHandler event
it 'sets @shift_pressed to true', ->
@trigger()
expect(@instance.shift_pressed).to.be.false
context 'when key is a character', ->
beforeEach ->
@query = 'zz'
@instance.$input.val(@query)
it 'returns false', ->
expect(@trigger()).to.be.false
it 'calls @_resetContainer', ->
spy = sinon.spy @instance, '_resetContainer'
@trigger()
expect(spy).to.be.calledOnce
spy.restore()
it 'searches for the query in the storage', ->
@trigger()
@clock.tick(@instance.config.debounceInterval);
expect(@storage_search_spy).to.be.calledOnce
context 'on keypress', ->
beforeEach ->
@trigger = (keycode)=>
my_event = $.Event @instance._keyPressEventName(), { keyCode: keycode }
@instance.$input.triggerHandler my_event
context 'when key is shift', ->
it 'sets shift_pressed to true', ->
@instance.shift_pressed = false
@trigger(16)
expect(@instance.shift_pressed).to.be.true
it 'returns false', ->
expect(@trigger(16)).to.be.false
context 'when key is escape', ->
it 'hides plugin', ->
@trigger(27)
expect(@hide_spy).to.be.calledOnce
it 'returns false', ->
expect(@trigger(27)).to.be.false
context 'when key is up', ->
it 'selects result above', ->
spy = sinon.spy @instance, '_moveSelectedItem'
@trigger(38)
expect(spy.args[0][0]).to.equal 'up'
spy.restore()
it 'returns false', ->
expect(@trigger(38)).to.be.false
context 'when key is down', ->
it 'selects result below', ->
spy = sinon.spy @instance, '_moveSelectedItem'
@trigger(40)
expect(spy.args[0][0]).to.equal 'down'
spy.restore()
it 'returns false', ->
expect(@trigger(40)).to.be.false
context 'when key is enter', ->
it 'hides the plugin', ->
@trigger(13)
expect(@hide_spy).to.be.calledOnce
it 'returns false', ->
expect(@trigger(13)).to.be.false
context 'when there are results printed', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger(13)
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="4">zero1</option>'
@trigger(13)
expect(@instance.$el.html()).to.equal expected_template
context 'when key is tab', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
it 'hides the plugin', ->
@trigger(9)
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger(9)
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="4">zero1</option>'
@trigger(9)
expect(@instance.$el.html()).to.equal expected_template
it 'returns true', ->
expect(@trigger(9)).to.be.true
context 'when any other key is pressed', ->
it 'returns true', ->
expect(@trigger(55)).to.be.true
describe 'Storage Events', ->
beforeEach -> @init()
context 'on "dbcreate_start"', ->
beforeEach ->
@instance._onDBCreateStart()
it 'disables plugin state', ->
expect(@instance.state).to.equal('disabled')
it 'disables html state', ->
expect(@instance.$top.hasClass('disabled')).to.be.true
it 'shows loader', ->
expect(@instance.$top_loader.is(':visible')).to.be.true
context 'on "dbcreate_end"', ->
beforeEach ->
@instance._onDBCreateEnd()
it 'disables html state', ->
expect(@instance.$top.hasClass('disabled')).to.be.false
it 'hides loader', ->
expect(@instance.$top_loader.is(':visible')).to.be.false
context 'on "dbremote_search_in"', ->
it 'shows XHR countdown slider', ->
spy = sinon.spy @instance, '_showXHRCountdown'
@instance._onDBSearchIn()
expect(spy).to.be.calledOnce
spy.restore()
context 'on "dbremote_search_start"', ->
it 'hides XHR countdown slider', ->
spy = sinon.spy @instance, '_hideXHRCountdown'
@instance._onDBSearchStart()
expect(spy).to.be.calledOnce
spy.restore()
it 'shows XHR loader', ->
@instance._onDBSearchStart()
expect(@instance.$XHR_loader.css('display')).to.equal('block')
context 'on "dbremote_search_end"', ->
it 'hides XHR loader', ->
@instance._onDBSearchEnd()
expect(@instance.$XHR_loader.css('display')).to.equal('none')
context 'on "dbremote_search_error"', ->
context 'on "dbremote_search_reset"', ->
it 'hides XHR countdown slider', ->
spy = sinon.spy @instance, '_hideXHRCountdown'
@instance._onDBSearchReset()
expect(spy).to.be.calledOnce
spy.restore()
it 'hides XHR loader', ->
@instance._onDBSearchReset()
expect(@instance.$XHR_loader.css('display')).to.equal('none')
context 'on "dbsearch_results"', ->
beforeEach ->
@query = 'ze'
@init()
@instance.query = @query
@instance._show()
it 'creates html elements for results', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items).to.have.length(3)
it 'highlights query in each element\'s text', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items.first().html()).to.equal('<span class="highlight">ze</span>ro1')
context 'when previous query gave no results', ->
it 'selects first result', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$results_list.find('.item').index('.selected')).to.equal(0)
context 'when previous query gave results', ->
beforeEach ->
@instance._onDBSearchResults(@data, @query)
it 'adds "new" class to new results', ->
@instance._onDBSearchResults(@data2, @query, true)
expect(@instance.$results_list.find('.item.new').first().text()).to.equal('zero0')
it 'selects previously selected result', ->
$(@instance.$results_list.find('.item')[1]).trigger('mouseenter')
@instance._onDBSearchResults(@data2, @query, true)
$selected_el = @instance.$results_list.find('.selected')
expect(@instance.$results_list.find('.item').index($selected_el)).to.equal(2)
context 'when query contains special characters', ->
beforeEach ->
@query = 'pc++'
@instance.query = @query
@data = [
{
id: 7
name: 'pc++'
}
]
it 'creates html elements for results', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items).to.have.length(1)
it 'highlights query in each element\'s text', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items.first().html()).to.equal('<span class="highlight">pc++</span>')
describe 'add', ->
beforeEach ->
@storage_add_spy = sinon.spy @storage_mock::, 'add'
@instance = @Selectorablium(@$el, @options)
@key = 10101
@value = 'test'
afterEach ->
@storage_add_spy.restore()
it 'calls @db\'s add', ->
@instance.add @key, @value
expect(@storage_add_spy.args[0]).to.eql [@key, @value]
xdescribe '#_hideXHRCountdown', ->
xdescribe '#_showXHRCountdown', ->
xdescribe '#_moveSelectedItem', ->
xdescribe '#_resetContainer', ->
xdescribe '#reset', ->
xdescribe '#_hide', ->
xdescribe '#_show', ->
| 165236 | toggle_plugin_tests = ->
context 'when @state is "disabled"', ->
beforeEach ->
@instance.state = 'disabled'
@trigger()
it 'does not call hide', ->
expect(@hide_spy).to.not.be.called
it 'does not call show', ->
expect(@show_spy).to.not.be.called
context 'when @state is "visible"', ->
beforeEach ->
@instance.state = 'visible'
@trigger()
it 'hides the plugin', ->
expect(@hide_spy).to.be.calledOnce
context 'when @state is "ready"', ->
beforeEach ->
@instance.state = 'ready'
@trigger()
it 'shows the plugin', ->
expect(@show_spy).to.be.calledOnce
describe 'Selectorablium', ->
@timeout(0) # Disable the spec's timeout
before (done)->
## MOCK STORAGE
window.__requirejs__.clearRequireState()
# mock Session
requirejs.undef 'storage_freak'
@storage_init_deferred = storage_init_deferred = new $.Deferred()
class StorageFreak
constructor: ->
on: ->
init: -> return storage_init_deferred
searchByKey: ->
search: ->
cleanup: ->
add: ->
@storage_mock = StorageFreak
@storage_spy = sinon.spy this, 'storage_mock'
@storage_search_spy = sinon.spy StorageFreak::, 'search'
define 'storage_freak', [], =>
return @storage_mock
@respond_to_db_creates = ->
for request in @requests
if request.url is 'shops.json'
request.respond 200, { "Content-Type": "application/json" }, @shops_json
else if request.url is 'makers.json'
request.respond 200, { "Content-Type": "application/json" }, @makers_json
@options =
app_name: "selectorablium_test"
[@shops_obj, @makers_obj] = fixture.load('shops.json', 'makers.json')
fixture.load 'shops.html'
@makers_json = JSON.stringify @makers_obj
@shops_json = JSON.stringify @shops_obj
@$el = $(".selectorablium.shops")
@init = (el = @$el, options = @options, respond = true)=>
@instance = new @Selectorablium el, options
@$el.data 'Selectorablium', @instance
respond and @respond_to_db_creates()
require ['selectorablium'], (Selectorablium)=>
@Selectorablium = Selectorablium
done()
after ->
requirejs.undef 'storage_freak'
window.__requirejs__.clearRequireState()
beforeEach ->
@requests = []
@xhr = sinon.useFakeXMLHttpRequest()
@xhr.onCreate = (xhr)=> @requests.push xhr
@data = [
{
id: 4
name: 'zero1'
},
{
id: 5
name: 'zero2'
},
{
id: 6
name: 'zero3'
}
]
@data2 = [
{
id: 3
name: 'zero0'
},
{
id: 4
name: 'zero1'
},
{
id: 5
name: 'zero2'
},
{
id: 6
name: 'zero3'
}
]
afterEach ->
$(".selectorablium").each -> $(this).data('Selectorablium')?.cleanup()
@xhr.restore()
window.localStorage && localStorage.clear()
@storage_spy.reset()
@storage_search_spy.reset()
describe '.constructor', ->
it 'returns an instance when called without new', ->
instance = @Selectorablium(@$el, @options)
expect(instance).to.be.an.instanceof(@Selectorablium)
instance.cleanup()
it 'thows if no element is given', ->
expect(@Selectorablium).to.throw(/Element argument is required/)
it 'thows if not required options are given', ->
expect(=>@Selectorablium(@$el)).to.throw(/option is required/)
it 'initializes @state to "disabled"', ->
@init()
expect(@instance.state).to.equal('disabled')
it 'get a Storage instance', ->
@init()
expect(@storage_spy).to.be.calledWithNew
it 'creates HTML', ->
@init()
template = """<div class="selectorablium_outer_cont"><select class="selectorablium shops" name="eshop_id" data-url="shops.json" data-query="query" data-name="shops" data-default_value="" data-default_text="Choose eshop" data-selected_id="3"><option value="">Choose eshop</option></select><div class="selectorablium_cont">
<div class="top">
<div class="initial_loader">Loading initial data...</div>
<a class="clear_button">Clear</a>
</div>
<div class="inner_container">
<form>
<input autocomplete="off" name="var_name">
<span class="input_icon"></span>
<div class="loader"></div>
<div class="XHRCounter"></div>
</form>
<ul class="list_container"></ul>
</div>
</div></div>"""
expect($(fixture.el).html()).to.equal(template)
it 'registers handlers on HTML elements', ->
@init()
expect(@instance.events_handled).to.have.length(9)
it 'registers handlers for storage events', ->
spy = sinon.spy @storage_mock::, 'on'
@init()
expect(spy).to.have.callCount(8)
spy.restore()
it 'inits storage', ->
spy = sinon.spy @storage_mock::, 'init'
@init()
expect(spy).to.be.calledOnce
spy.restore()
describe 'HTML Events', ->
beforeEach ->
@init()
@show_spy = sinon.spy @instance, '_show'
@hide_spy = sinon.spy @instance, '_hide'
afterEach ->
@show_spy.restore()
@hide_spy.restore()
context '@$top element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$top.triggerHandler 'click'
toggle_plugin_tests()
context '@$el element', ->
context 'on focus', ->
beforeEach ->
@trigger = => @instance.$el.triggerHandler 'focus'
toggle_plugin_tests()
context '@$container element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$container.triggerHandler 'click'
it 'sets @do_not_hide_me to true', ->
@trigger()
expect(@instance.do_not_hide_me).to.be.true
context '@$clear_button element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$clear_button.triggerHandler 'click'
it 'resets the plugin', ->
spy = sinon.spy @instance, 'reset'
@trigger()
expect(spy).to.be.calledOnce
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger()
expect(spy).to.be.calledOnce
context 'html element', ->
context 'on click', ->
beforeEach ->
@trigger = => $('html').triggerHandler 'click'
context 'when @do_not_hide_me is true', ->
beforeEach ->
@instance.do_not_hide_me = true
it 'sets @do_not_hide_me to false', ->
@trigger()
expect(@instance.do_not_hide_me).to.be.false
context 'when @do_not_hide_me is false', ->
beforeEach ->
@instance.do_not_hide_me = false
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
context 'result element', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
context 'on mouseenter', ->
beforeEach ->
@$selected_element = @instance.selected_item
@$last_element = @instance.$result_items.last()
@trigger = => @$last_element.trigger 'mouseenter'
it 'deselects previously selected element', ->
@trigger()
expect(@instance.selected_item[0]).to.not.equal(@$selected_element[0])
it 'selects mouseentered element', ->
@trigger()
expect(@instance.selected_item[0]).to.equal(@$last_element[0])
context 'on click', ->
beforeEach ->
@$last_element = @instance.$result_items.last()
@trigger = =>
@$last_element.trigger 'mouseenter'
@$last_element.trigger 'click'
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger()
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="6">zero3</option>'
@trigger()
expect(@instance.$el.html()).to.equal expected_template
context '@$input element', ->
context 'on keyup', ->
beforeEach ->
@event = jQuery.Event 'keyup', { keyCode: 55 }
@trigger = => @instance.$input.triggerHandler @event
@clock = sinon.useFakeTimers()
afterEach ->
@clock.restore()
context 'when key is not a character', ->
beforeEach ->
@event = jQuery.Event 'keyup', { keyCode: 39 }
@trigger = => @instance.$input.triggerHandler @event
it 'returns false', ->
expect(@trigger()).to.be.false
context 'when key is shift', ->
beforeEach ->
@instance.shift_pressed = true
event = jQuery.Event 'keyup', { keyCode: 16 }
@trigger = => @instance.$input.triggerHandler event
it 'sets @shift_pressed to true', ->
@trigger()
expect(@instance.shift_pressed).to.be.false
context 'when key is a character', ->
beforeEach ->
@query = 'zz'
@instance.$input.val(@query)
it 'returns false', ->
expect(@trigger()).to.be.false
it 'calls @_resetContainer', ->
spy = sinon.spy @instance, '_resetContainer'
@trigger()
expect(spy).to.be.calledOnce
spy.restore()
it 'searches for the query in the storage', ->
@trigger()
@clock.tick(@instance.config.debounceInterval);
expect(@storage_search_spy).to.be.calledOnce
context 'on keypress', ->
beforeEach ->
@trigger = (keycode)=>
my_event = $.Event @instance._keyPressEventName(), { keyCode: keycode }
@instance.$input.triggerHandler my_event
context 'when key is shift', ->
it 'sets shift_pressed to true', ->
@instance.shift_pressed = false
@trigger(16)
expect(@instance.shift_pressed).to.be.true
it 'returns false', ->
expect(@trigger(16)).to.be.false
context 'when key is escape', ->
it 'hides plugin', ->
@trigger(27)
expect(@hide_spy).to.be.calledOnce
it 'returns false', ->
expect(@trigger(27)).to.be.false
context 'when key is up', ->
it 'selects result above', ->
spy = sinon.spy @instance, '_moveSelectedItem'
@trigger(38)
expect(spy.args[0][0]).to.equal 'up'
spy.restore()
it 'returns false', ->
expect(@trigger(38)).to.be.false
context 'when key is down', ->
it 'selects result below', ->
spy = sinon.spy @instance, '_moveSelectedItem'
@trigger(40)
expect(spy.args[0][0]).to.equal 'down'
spy.restore()
it 'returns false', ->
expect(@trigger(40)).to.be.false
context 'when key is enter', ->
it 'hides the plugin', ->
@trigger(13)
expect(@hide_spy).to.be.calledOnce
it 'returns false', ->
expect(@trigger(13)).to.be.false
context 'when there are results printed', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger(13)
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="4">zero1</option>'
@trigger(13)
expect(@instance.$el.html()).to.equal expected_template
context 'when key is tab', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
it 'hides the plugin', ->
@trigger(9)
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger(9)
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="4">zero1</option>'
@trigger(9)
expect(@instance.$el.html()).to.equal expected_template
it 'returns true', ->
expect(@trigger(9)).to.be.true
context 'when any other key is pressed', ->
it 'returns true', ->
expect(@trigger(55)).to.be.true
describe 'Storage Events', ->
beforeEach -> @init()
context 'on "dbcreate_start"', ->
beforeEach ->
@instance._onDBCreateStart()
it 'disables plugin state', ->
expect(@instance.state).to.equal('disabled')
it 'disables html state', ->
expect(@instance.$top.hasClass('disabled')).to.be.true
it 'shows loader', ->
expect(@instance.$top_loader.is(':visible')).to.be.true
context 'on "dbcreate_end"', ->
beforeEach ->
@instance._onDBCreateEnd()
it 'disables html state', ->
expect(@instance.$top.hasClass('disabled')).to.be.false
it 'hides loader', ->
expect(@instance.$top_loader.is(':visible')).to.be.false
context 'on "dbremote_search_in"', ->
it 'shows XHR countdown slider', ->
spy = sinon.spy @instance, '_showXHRCountdown'
@instance._onDBSearchIn()
expect(spy).to.be.calledOnce
spy.restore()
context 'on "dbremote_search_start"', ->
it 'hides XHR countdown slider', ->
spy = sinon.spy @instance, '_hideXHRCountdown'
@instance._onDBSearchStart()
expect(spy).to.be.calledOnce
spy.restore()
it 'shows XHR loader', ->
@instance._onDBSearchStart()
expect(@instance.$XHR_loader.css('display')).to.equal('block')
context 'on "dbremote_search_end"', ->
it 'hides XHR loader', ->
@instance._onDBSearchEnd()
expect(@instance.$XHR_loader.css('display')).to.equal('none')
context 'on "dbremote_search_error"', ->
context 'on "dbremote_search_reset"', ->
it 'hides XHR countdown slider', ->
spy = sinon.spy @instance, '_hideXHRCountdown'
@instance._onDBSearchReset()
expect(spy).to.be.calledOnce
spy.restore()
it 'hides XHR loader', ->
@instance._onDBSearchReset()
expect(@instance.$XHR_loader.css('display')).to.equal('none')
context 'on "dbsearch_results"', ->
beforeEach ->
@query = 'ze'
@init()
@instance.query = @query
@instance._show()
it 'creates html elements for results', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items).to.have.length(3)
it 'highlights query in each element\'s text', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items.first().html()).to.equal('<span class="highlight">ze</span>ro1')
context 'when previous query gave no results', ->
it 'selects first result', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$results_list.find('.item').index('.selected')).to.equal(0)
context 'when previous query gave results', ->
beforeEach ->
@instance._onDBSearchResults(@data, @query)
it 'adds "new" class to new results', ->
@instance._onDBSearchResults(@data2, @query, true)
expect(@instance.$results_list.find('.item.new').first().text()).to.equal('zero0')
it 'selects previously selected result', ->
$(@instance.$results_list.find('.item')[1]).trigger('mouseenter')
@instance._onDBSearchResults(@data2, @query, true)
$selected_el = @instance.$results_list.find('.selected')
expect(@instance.$results_list.find('.item').index($selected_el)).to.equal(2)
context 'when query contains special characters', ->
beforeEach ->
@query = 'pc++'
@instance.query = @query
@data = [
{
id: 7
name: 'pc++'
}
]
it 'creates html elements for results', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items).to.have.length(1)
it 'highlights query in each element\'s text', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items.first().html()).to.equal('<span class="highlight">pc++</span>')
describe 'add', ->
beforeEach ->
@storage_add_spy = sinon.spy @storage_mock::, 'add'
@instance = @Selectorablium(@$el, @options)
@key = 1<KEY>1
@value = 'test'
afterEach ->
@storage_add_spy.restore()
it 'calls @db\'s add', ->
@instance.add @key, @value
expect(@storage_add_spy.args[0]).to.eql [@key, @value]
xdescribe '#_hideXHRCountdown', ->
xdescribe '#_showXHRCountdown', ->
xdescribe '#_moveSelectedItem', ->
xdescribe '#_resetContainer', ->
xdescribe '#reset', ->
xdescribe '#_hide', ->
xdescribe '#_show', ->
| true | toggle_plugin_tests = ->
context 'when @state is "disabled"', ->
beforeEach ->
@instance.state = 'disabled'
@trigger()
it 'does not call hide', ->
expect(@hide_spy).to.not.be.called
it 'does not call show', ->
expect(@show_spy).to.not.be.called
context 'when @state is "visible"', ->
beforeEach ->
@instance.state = 'visible'
@trigger()
it 'hides the plugin', ->
expect(@hide_spy).to.be.calledOnce
context 'when @state is "ready"', ->
beforeEach ->
@instance.state = 'ready'
@trigger()
it 'shows the plugin', ->
expect(@show_spy).to.be.calledOnce
describe 'Selectorablium', ->
@timeout(0) # Disable the spec's timeout
before (done)->
## MOCK STORAGE
window.__requirejs__.clearRequireState()
# mock Session
requirejs.undef 'storage_freak'
@storage_init_deferred = storage_init_deferred = new $.Deferred()
class StorageFreak
constructor: ->
on: ->
init: -> return storage_init_deferred
searchByKey: ->
search: ->
cleanup: ->
add: ->
@storage_mock = StorageFreak
@storage_spy = sinon.spy this, 'storage_mock'
@storage_search_spy = sinon.spy StorageFreak::, 'search'
define 'storage_freak', [], =>
return @storage_mock
@respond_to_db_creates = ->
for request in @requests
if request.url is 'shops.json'
request.respond 200, { "Content-Type": "application/json" }, @shops_json
else if request.url is 'makers.json'
request.respond 200, { "Content-Type": "application/json" }, @makers_json
@options =
app_name: "selectorablium_test"
[@shops_obj, @makers_obj] = fixture.load('shops.json', 'makers.json')
fixture.load 'shops.html'
@makers_json = JSON.stringify @makers_obj
@shops_json = JSON.stringify @shops_obj
@$el = $(".selectorablium.shops")
@init = (el = @$el, options = @options, respond = true)=>
@instance = new @Selectorablium el, options
@$el.data 'Selectorablium', @instance
respond and @respond_to_db_creates()
require ['selectorablium'], (Selectorablium)=>
@Selectorablium = Selectorablium
done()
after ->
requirejs.undef 'storage_freak'
window.__requirejs__.clearRequireState()
beforeEach ->
@requests = []
@xhr = sinon.useFakeXMLHttpRequest()
@xhr.onCreate = (xhr)=> @requests.push xhr
@data = [
{
id: 4
name: 'zero1'
},
{
id: 5
name: 'zero2'
},
{
id: 6
name: 'zero3'
}
]
@data2 = [
{
id: 3
name: 'zero0'
},
{
id: 4
name: 'zero1'
},
{
id: 5
name: 'zero2'
},
{
id: 6
name: 'zero3'
}
]
afterEach ->
$(".selectorablium").each -> $(this).data('Selectorablium')?.cleanup()
@xhr.restore()
window.localStorage && localStorage.clear()
@storage_spy.reset()
@storage_search_spy.reset()
describe '.constructor', ->
it 'returns an instance when called without new', ->
instance = @Selectorablium(@$el, @options)
expect(instance).to.be.an.instanceof(@Selectorablium)
instance.cleanup()
it 'thows if no element is given', ->
expect(@Selectorablium).to.throw(/Element argument is required/)
it 'thows if not required options are given', ->
expect(=>@Selectorablium(@$el)).to.throw(/option is required/)
it 'initializes @state to "disabled"', ->
@init()
expect(@instance.state).to.equal('disabled')
it 'get a Storage instance', ->
@init()
expect(@storage_spy).to.be.calledWithNew
it 'creates HTML', ->
@init()
template = """<div class="selectorablium_outer_cont"><select class="selectorablium shops" name="eshop_id" data-url="shops.json" data-query="query" data-name="shops" data-default_value="" data-default_text="Choose eshop" data-selected_id="3"><option value="">Choose eshop</option></select><div class="selectorablium_cont">
<div class="top">
<div class="initial_loader">Loading initial data...</div>
<a class="clear_button">Clear</a>
</div>
<div class="inner_container">
<form>
<input autocomplete="off" name="var_name">
<span class="input_icon"></span>
<div class="loader"></div>
<div class="XHRCounter"></div>
</form>
<ul class="list_container"></ul>
</div>
</div></div>"""
expect($(fixture.el).html()).to.equal(template)
it 'registers handlers on HTML elements', ->
@init()
expect(@instance.events_handled).to.have.length(9)
it 'registers handlers for storage events', ->
spy = sinon.spy @storage_mock::, 'on'
@init()
expect(spy).to.have.callCount(8)
spy.restore()
it 'inits storage', ->
spy = sinon.spy @storage_mock::, 'init'
@init()
expect(spy).to.be.calledOnce
spy.restore()
describe 'HTML Events', ->
beforeEach ->
@init()
@show_spy = sinon.spy @instance, '_show'
@hide_spy = sinon.spy @instance, '_hide'
afterEach ->
@show_spy.restore()
@hide_spy.restore()
context '@$top element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$top.triggerHandler 'click'
toggle_plugin_tests()
context '@$el element', ->
context 'on focus', ->
beforeEach ->
@trigger = => @instance.$el.triggerHandler 'focus'
toggle_plugin_tests()
context '@$container element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$container.triggerHandler 'click'
it 'sets @do_not_hide_me to true', ->
@trigger()
expect(@instance.do_not_hide_me).to.be.true
context '@$clear_button element', ->
context 'on click', ->
beforeEach ->
@trigger = => @instance.$clear_button.triggerHandler 'click'
it 'resets the plugin', ->
spy = sinon.spy @instance, 'reset'
@trigger()
expect(spy).to.be.calledOnce
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger()
expect(spy).to.be.calledOnce
context 'html element', ->
context 'on click', ->
beforeEach ->
@trigger = => $('html').triggerHandler 'click'
context 'when @do_not_hide_me is true', ->
beforeEach ->
@instance.do_not_hide_me = true
it 'sets @do_not_hide_me to false', ->
@trigger()
expect(@instance.do_not_hide_me).to.be.false
context 'when @do_not_hide_me is false', ->
beforeEach ->
@instance.do_not_hide_me = false
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
context 'result element', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
context 'on mouseenter', ->
beforeEach ->
@$selected_element = @instance.selected_item
@$last_element = @instance.$result_items.last()
@trigger = => @$last_element.trigger 'mouseenter'
it 'deselects previously selected element', ->
@trigger()
expect(@instance.selected_item[0]).to.not.equal(@$selected_element[0])
it 'selects mouseentered element', ->
@trigger()
expect(@instance.selected_item[0]).to.equal(@$last_element[0])
context 'on click', ->
beforeEach ->
@$last_element = @instance.$result_items.last()
@trigger = =>
@$last_element.trigger 'mouseenter'
@$last_element.trigger 'click'
it 'hides the plugin', ->
@trigger()
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger()
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="6">zero3</option>'
@trigger()
expect(@instance.$el.html()).to.equal expected_template
context '@$input element', ->
context 'on keyup', ->
beforeEach ->
@event = jQuery.Event 'keyup', { keyCode: 55 }
@trigger = => @instance.$input.triggerHandler @event
@clock = sinon.useFakeTimers()
afterEach ->
@clock.restore()
context 'when key is not a character', ->
beforeEach ->
@event = jQuery.Event 'keyup', { keyCode: 39 }
@trigger = => @instance.$input.triggerHandler @event
it 'returns false', ->
expect(@trigger()).to.be.false
context 'when key is shift', ->
beforeEach ->
@instance.shift_pressed = true
event = jQuery.Event 'keyup', { keyCode: 16 }
@trigger = => @instance.$input.triggerHandler event
it 'sets @shift_pressed to true', ->
@trigger()
expect(@instance.shift_pressed).to.be.false
context 'when key is a character', ->
beforeEach ->
@query = 'zz'
@instance.$input.val(@query)
it 'returns false', ->
expect(@trigger()).to.be.false
it 'calls @_resetContainer', ->
spy = sinon.spy @instance, '_resetContainer'
@trigger()
expect(spy).to.be.calledOnce
spy.restore()
it 'searches for the query in the storage', ->
@trigger()
@clock.tick(@instance.config.debounceInterval);
expect(@storage_search_spy).to.be.calledOnce
context 'on keypress', ->
beforeEach ->
@trigger = (keycode)=>
my_event = $.Event @instance._keyPressEventName(), { keyCode: keycode }
@instance.$input.triggerHandler my_event
context 'when key is shift', ->
it 'sets shift_pressed to true', ->
@instance.shift_pressed = false
@trigger(16)
expect(@instance.shift_pressed).to.be.true
it 'returns false', ->
expect(@trigger(16)).to.be.false
context 'when key is escape', ->
it 'hides plugin', ->
@trigger(27)
expect(@hide_spy).to.be.calledOnce
it 'returns false', ->
expect(@trigger(27)).to.be.false
context 'when key is up', ->
it 'selects result above', ->
spy = sinon.spy @instance, '_moveSelectedItem'
@trigger(38)
expect(spy.args[0][0]).to.equal 'up'
spy.restore()
it 'returns false', ->
expect(@trigger(38)).to.be.false
context 'when key is down', ->
it 'selects result below', ->
spy = sinon.spy @instance, '_moveSelectedItem'
@trigger(40)
expect(spy.args[0][0]).to.equal 'down'
spy.restore()
it 'returns false', ->
expect(@trigger(40)).to.be.false
context 'when key is enter', ->
it 'hides the plugin', ->
@trigger(13)
expect(@hide_spy).to.be.calledOnce
it 'returns false', ->
expect(@trigger(13)).to.be.false
context 'when there are results printed', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger(13)
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="4">zero1</option>'
@trigger(13)
expect(@instance.$el.html()).to.equal expected_template
context 'when key is tab', ->
beforeEach ->
@query = 'ze'
@instance.query = @query
@instance._show()
@instance._onDBSearchResults(@data, @query)
it 'hides the plugin', ->
@trigger(9)
expect(@hide_spy).to.be.calledOnce
it 'triggers the change event on the select element', ->
spy = sinon.spy()
@instance.$el.one 'change', spy
@trigger(9)
expect(spy).to.be.calledOnce
it 'creates option with selected items attributes', ->
expected_template = '<option value="4">zero1</option>'
@trigger(9)
expect(@instance.$el.html()).to.equal expected_template
it 'returns true', ->
expect(@trigger(9)).to.be.true
context 'when any other key is pressed', ->
it 'returns true', ->
expect(@trigger(55)).to.be.true
describe 'Storage Events', ->
beforeEach -> @init()
context 'on "dbcreate_start"', ->
beforeEach ->
@instance._onDBCreateStart()
it 'disables plugin state', ->
expect(@instance.state).to.equal('disabled')
it 'disables html state', ->
expect(@instance.$top.hasClass('disabled')).to.be.true
it 'shows loader', ->
expect(@instance.$top_loader.is(':visible')).to.be.true
context 'on "dbcreate_end"', ->
beforeEach ->
@instance._onDBCreateEnd()
it 'disables html state', ->
expect(@instance.$top.hasClass('disabled')).to.be.false
it 'hides loader', ->
expect(@instance.$top_loader.is(':visible')).to.be.false
context 'on "dbremote_search_in"', ->
it 'shows XHR countdown slider', ->
spy = sinon.spy @instance, '_showXHRCountdown'
@instance._onDBSearchIn()
expect(spy).to.be.calledOnce
spy.restore()
context 'on "dbremote_search_start"', ->
it 'hides XHR countdown slider', ->
spy = sinon.spy @instance, '_hideXHRCountdown'
@instance._onDBSearchStart()
expect(spy).to.be.calledOnce
spy.restore()
it 'shows XHR loader', ->
@instance._onDBSearchStart()
expect(@instance.$XHR_loader.css('display')).to.equal('block')
context 'on "dbremote_search_end"', ->
it 'hides XHR loader', ->
@instance._onDBSearchEnd()
expect(@instance.$XHR_loader.css('display')).to.equal('none')
context 'on "dbremote_search_error"', ->
context 'on "dbremote_search_reset"', ->
it 'hides XHR countdown slider', ->
spy = sinon.spy @instance, '_hideXHRCountdown'
@instance._onDBSearchReset()
expect(spy).to.be.calledOnce
spy.restore()
it 'hides XHR loader', ->
@instance._onDBSearchReset()
expect(@instance.$XHR_loader.css('display')).to.equal('none')
context 'on "dbsearch_results"', ->
beforeEach ->
@query = 'ze'
@init()
@instance.query = @query
@instance._show()
it 'creates html elements for results', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items).to.have.length(3)
it 'highlights query in each element\'s text', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items.first().html()).to.equal('<span class="highlight">ze</span>ro1')
context 'when previous query gave no results', ->
it 'selects first result', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$results_list.find('.item').index('.selected')).to.equal(0)
context 'when previous query gave results', ->
beforeEach ->
@instance._onDBSearchResults(@data, @query)
it 'adds "new" class to new results', ->
@instance._onDBSearchResults(@data2, @query, true)
expect(@instance.$results_list.find('.item.new').first().text()).to.equal('zero0')
it 'selects previously selected result', ->
$(@instance.$results_list.find('.item')[1]).trigger('mouseenter')
@instance._onDBSearchResults(@data2, @query, true)
$selected_el = @instance.$results_list.find('.selected')
expect(@instance.$results_list.find('.item').index($selected_el)).to.equal(2)
context 'when query contains special characters', ->
beforeEach ->
@query = 'pc++'
@instance.query = @query
@data = [
{
id: 7
name: 'pc++'
}
]
it 'creates html elements for results', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items).to.have.length(1)
it 'highlights query in each element\'s text', ->
@instance._onDBSearchResults(@data, @query)
expect(@instance.$result_items.first().html()).to.equal('<span class="highlight">pc++</span>')
describe 'add', ->
beforeEach ->
@storage_add_spy = sinon.spy @storage_mock::, 'add'
@instance = @Selectorablium(@$el, @options)
@key = 1PI:KEY:<KEY>END_PI1
@value = 'test'
afterEach ->
@storage_add_spy.restore()
it 'calls @db\'s add', ->
@instance.add @key, @value
expect(@storage_add_spy.args[0]).to.eql [@key, @value]
xdescribe '#_hideXHRCountdown', ->
xdescribe '#_showXHRCountdown', ->
xdescribe '#_moveSelectedItem', ->
xdescribe '#_resetContainer', ->
xdescribe '#reset', ->
xdescribe '#_hide', ->
xdescribe '#_show', ->
|
[
{
"context": "ne:\n https://docs.google.com/spreadsheet/ccc?key=0AgpC5gsTSm_4dDRVOEprRkVuSFZUWTlvclJ6UFRvdFE#gid=0\n###\nXLF.defaultSurveyDetails =\n start_time",
"end": 13252,
"score": 0.9997416734695435,
"start": 13208,
"tag": "KEY",
"value": "0AgpC5gsTSm_4dDRVOEprRkVuSFZUWTlvclJ6UFRvdFE... | source/javascripts/src/model_xlform.coffee | dorey/xlform-builder | 1 | ###
Refactoring to consider:
------------------------
SurveyFragment extends Backbone.Collection (to get rid of @rows)
Get rid of XLF.Options
Get rid of XLF.ChoiceLists (?)
Get rid of XLF.SurveyDetails ( maybe ?)
Add "popover text" (or something similar) to XLF.defaultsForType
###
###
@XLF holds much of the models/collections of the XL(s)Form survey
representation in the browser.
###
@XLF = {}
# @log function for debugging
@log = (args...)-> console?.log?.apply console, args
###
XLF.Survey and associated Backbone Model
and Collection definitions
###
class BaseModel extends Backbone.Model
constructor: (arg)->
if "object" is typeof arg and "_parent" of arg
@_parent = arg._parent
delete arg._parent
super arg
class SurveyFragment extends BaseModel
forEachRow: (cb, ctx={})->
@rows.each (r, index, list)->
if r instanceof XLF.SurveyDetail
``
else if r instanceof XLF.Group
context = {}
cb(r.groupStart())
r.forEachRow(cb, context)
cb(r.groupEnd())
``
else
cb(r)
addRow: (r)->
r._parent = @
@rows.add r
addRowAtIndex: (r, index)->
r._parent = @
@rows.add r, at: index
###
XLF...
"Survey",
###
class XLF.Survey extends SurveyFragment
initialize: (options={})->
@rows = new XLF.Rows()
@settings = new XLF.Settings(options.settings)
if (sname = @settings.get("name"))
@set("name", sname)
@newRowDetails = options.newRowDetails || XLF.newRowDetails
@defaultsForType = options.defaultsForType || XLF.defaultsForType
@surveyDetails = new XLF.SurveyDetails(_.values(XLF.defaultSurveyDetails))
passedChoices = options.choices || []
@choices = do ->
choices = new XLF.ChoiceLists()
tmp = {}
choiceNames = []
for choiceRow in passedChoices
lName = choiceRow["list name"]
unless tmp[lName]
tmp[lName] = []
choiceNames.push(lName)
tmp[lName].push(choiceRow)
for cn in choiceNames
choices.add(name: cn, options: tmp[cn])
choices
if options.survey
surveyRows = for r in options.survey
r._parent = @
r
@rows.add surveyRows, collection: @rows, silent: true
toCsvJson: ()->
# build an object that can be easily passed to the "csv" library
# to generate the XL(S)Form spreadsheet
surveyCsvJson = do =>
oCols = ["name", "type", "label"]
oRows = []
addRowToORows = (r)->
colJson = r.toJSON()
for own key, val of colJson when key not in oCols
oCols.push key
oRows.push colJson
@forEachRow addRowToORows
for sd in @surveyDetails.models when sd.get("value")
addRowToORows(sd)
columns: oCols
rowObjects: oRows
choicesCsvJson = do =>
lists = []
@forEachRow (r)->
if (list = r.getList())
lists.push(list)
rows = []
cols = ["list name", "name", "label"]
for choiceList in lists
choiceList.set("name", txtid(), silent: true) unless choiceList.get("name")
clName = choiceList.get("name")
for option in choiceList.options.models
rows.push _.extend {}, option.toJSON(), "list name": choiceList.get("name")
columns: cols
rowObjects: rows
survey: surveyCsvJson
choices: choicesCsvJson
settings: @settings.toCsvJson()
toCSV: ->
sheeted = csv.sheeted()
for shtName, content of @toCsvJson()
sheeted.sheet shtName, csv(content)
sheeted.toString()
###
XLF...
"lookupRowType",
"columnOrder",
"Group",
"Row",
"Rows",
###
XLF.lookupRowType = do->
typeLabels = [
["note", "Note", preventRequired: true],
["text", "Text"], # expects text
["integer", "Integer"], #e.g. 42
["decimal", "Decimal"], #e.g. 3.14
["geopoint", "Geopoint (GPS)"], # Can use satelite GPS coordinates
["image", "Image", isMedia: true], # Can use phone camera, for example
["barcode", "Barcode"], # Can scan a barcode using the phone camera
["date", "Date"], #e.g. (4 July, 1776)
["datetime", "Date and Time"], #e.g. (2012-Jan-4 3:04PM)
["audio", "Audio", isMedia: true], # Can use phone microphone to record audio
["video", "Video", isMedia: true], # Can use phone camera to record video
# ["calculate", "Calculate"],
["select_one", "Select", orOtherOption: true, specifyChoice: true],
["select_multiple", "Multiple choice", orOtherOption: true, specifyChoice: true]
]
class Type
constructor: ([@name, @label, opts])->
opts = {} unless opts
_.extend(@, opts)
types = (new Type(arr) for arr in typeLabels)
exp = (typeId)->
for tp in types when tp.name is typeId
output = tp
output
exp.typeSelectList = do ->
() -> types
exp
XLF.columnOrder = do ->
warned = []
warn = (key)->
unless key in warned
warend.push(key)
console?.error("Order not set for key: #{key}")
(key)->
ki = XLF.columns.indexOf key
warn(key) if ki is -1
if ki is -1 then 100 else ki
class XLF.Group extends SurveyFragment
initialize: ()->
@set "type", "begin group"
@rows = new XLF.Rows()
groupStart: ->
toJSON: => @attributes
inGroupStart: true
groupEnd: ->
toJSON: ()-> type: "end group"
class XLF.Row extends BaseModel
initialize: ->
###
The best way to understand the @details collection is
that it is a list of cells of the XLSForm spreadsheet.
The column name is the "key" and the value is the "value".
We opted for a collection (rather than just saving in the attributes of
this model) because of the various state-related attributes
that need to be saved for each cell and allowing room to grow.
E.g.: {"key": "type", "value": "select_one from colors"}
needs to keep track of how the value was built
###
if @_parent
defaultsUnlessDefined = @_parent.newRowDetails || XLF.newRowDetails
defaultsForType = @_parent.defaultsForType || XLF.defaultsForType
else
console?.error "Row not linked to parent survey."
defaultsUnlessDefined = XLF.newRowDetails
defaultsForType = XLF.defaultsForType
if @attributes.type and @attributes.type of defaultsForType
curTypeDefaults = defaultsForType[@attributes.type]
else
curTypeDefaults = {}
defaults = _.extend {}, defaultsUnlessDefined, curTypeDefaults
for key, vals of defaults
unless key of @attributes
newVals = {}
for vk, vv of vals
newVals[vk] = if ("function" is typeof vv) then vv() else vv
@set key, newVals
@isValid()
typeDetail = @get("type")
tpVal = typeDetail.get("value")
processType = (rd, newType, ctxt)=>
# if value changes, it could be set from an initialization value
# or it could be changed elsewhere.
# we need to keep typeId, listName, and orOther in sync.
[tpid, p2, p3] = newType.split(" ")
typeDetail.set("typeId", tpid, silent: true)
if p2
typeDetail.set("listName", p2, silent: true)
matchedList = @_parent.choices.get(p2)
if matchedList
typeDetail.set("list", matchedList)
typeDetail.set("orOther", p3, silent: true) if p3 is "or_other"
if (rtp = XLF.lookupRowType(tpid))
typeDetail.set("rowType", rtp, silent: true)
else
throw new Error "Type not found: #{tpid}"
processType(typeDetail, tpVal, {})
typeDetail.on "change:value", processType
typeDetail.on "change:listName", (rd, listName, ctx)->
rtp = typeDetail.get("rowType")
typeStr = "#{typeDetail.get("typeId")}"
if rtp.specifyChoice and listName
typeStr += " #{listName}"
if rtp.orOtherOption and typeDetail.get("orOther")
typeStr += " or_other"
typeDetail.set({value: typeStr}, silent: true)
typeDetail.on "change:list", (rd, cl, ctx)->
if typeDetail.get("rowType").specifyChoice
clname = cl.get("name")
unless clname
clname = txtid()
cl.set("name", clname, silent: true)
@set("value", "#{@get('typeId')} #{clname}")
getValue: (what)->
@get(what).get("value")
getList: ->
@get("type")?.get("list")
setList: (list)->
listToSet = @_parent.choices.get(list)
unless listToSet
@_parent.choices.add(list)
listToSet = @_parent.choices.get(list)
throw new Error("List not found: #{list}") unless listToSet
@get("type").set("list", listToSet)
validate: ->
for key, val of @attributes
unless val instanceof XLF.RowDetail
@set key, new XLF.RowDetail(key, val, @), {silent: true}
``
attributesArray: ()->
arr = ([k, v] for k, v of @attributes)
arr.sort (a,b)-> if a[1]._order < b[1]._order then -1 else 1
arr
toJSON: ->
outObj = {}
for [key, val] in @attributesArray() when !val.hidden
outObj[key] = @getValue(key)
outObj
class XLF.Rows extends Backbone.Collection
model: (obj, ctxt)->
type = obj?.type
if type in ["start", "end"]
new XLF.SurveyDetail(obj)
else if type is "group"
new XLF.Group(obj)
else
new XLF.Row(obj)
class XLF.RowDetail extends BaseModel
idAttribute: "name"
constructor: (@key, valOrObj={}, @parentRow)->
super()
vals2set = {}
if _.isString(valOrObj)
vals2set.value = valOrObj
else if "value" of valOrObj
_.extend vals2set, valOrObj
else
vals2set.value = valOrObj
@set(vals2set)
@_order = XLF.columnOrder(@key)
initialize: ()->
if @get("_hideUnlessChanged")
@hidden = true
@_oValue = @get("value")
@on "change", ()->
@hidden = @get("value") is @_oValue
@on "change:value", (rd, val, ctxt)=>
@parentRow.trigger "change", @key, val, ctxt
if @key is "type"
@on "change:list", (rd, val, ctxt)=>
@parentRow.trigger "change", @key, val, ctxt
###
XLF...
"Option",
"Options",
"ChoiceList",
"ChoiceLists",
###
class XLF.Option extends BaseModel
idAttribute: "name"
initialize: -> @unset("list name")
destroy: ->
log "destroy me", @
list: -> @collection
class XLF.Options extends Backbone.Collection
model: XLF.Option
class XLF.ChoiceList extends BaseModel
idAttribute: "name"
constructor: (opts={}, context)->
options = opts.options || []
super name: opts.name, context
@options = new XLF.Options(options || [])
@options.parentList = @
summaryObj: ->
name: @get("name")
options: do =>
opt.attributes for opt in @options.models
class XLF.ChoiceLists extends Backbone.Collection
model: XLF.ChoiceList
summaryObj: ()->
out = {}
for model in @models
out[model.get("name")] = model.summaryObj()
out
###
XLF...
"createSurveyFromCsv"
###
XLF.createSurveyFromCsv = (csv_repr)->
opts = {}
$settings = opts.settings || {}
# $launchEditor = if "launchEditor" in opts then opts.launchEditor else true
$elemWrap = $(opts.elemWrap || '#main')
$publishCb = opts.publish || ->
if csv_repr
if opts.survey or opts.choices
throw new XlformError """
[csv_repr] will cause other options to be ignored: [survey, choices]
"""
cobj = csv.sheeted(csv_repr)
$survey = if (sht = cobj.sheet "survey") then sht.toObjects() else []
$choices = if (sht = cobj.sheet "choices") then sht.toObjects() else []
if (settingsSheet = cobj.sheet "settings")
importedStgns = settingsSheet.toObjects()[0]
else
$survey = opts.survey || []
$choices = opts.choices || [] # settings: $settings
new XLF.Survey(survey: $survey, choices: $choices, settings: $settings)
###
XLF...
"SurveyDetail",
"SurveyDetails"
"Settings",
###
class XLF.SurveyDetail extends BaseModel
idAttribute: "name"
initialize: ()->
@set("value", !!@get("default"))
@unset("default")
if jsonVal = @get("asJson")
@toJSON = ()-> jsonVal
class XLF.SurveyDetails extends Backbone.Collection
model: XLF.SurveyDetail
class XLF.Settings extends BaseModel
defaults:
form_title: "New survey"
toCsvJson: ->
columns = _.keys(@attributes)
rowObjects = [@toJSON()]
columns: columns
rowObjects: rowObjects
###
misc helper methods
###
txtid = ()->
# a is text
# b is numeric or text
# c is mishmash
o = 'AAnCAnn'.replace /[AaCn]/g, (c)->
randChar= ()->
charI = Math.floor(Math.random()*52)
charI += (if charI <= 25 then 65 else 71)
String.fromCharCode charI
r = Math.random()
if c is 'a'
randChar()
else if c is 'A'
String.fromCharCode 65+(r*26|0)
else if c is 'C'
newI = Math.floor(r*62)
if newI > 52 then (newI - 52) else randChar()
else if c is 'n'
Math.floor(r*10)
o.toLowerCase()
###
defaultSurveyDetails
--------------------
These values will be populated in the form builder and the user
will have the option to turn them on or off.
When exported, if the checkbox was selected, the "asJson" value
gets passed to the CSV builder and appended to the end of the
survey.
Details pulled from ODK documents / google docs. Notably this one:
https://docs.google.com/spreadsheet/ccc?key=0AgpC5gsTSm_4dDRVOEprRkVuSFZUWTlvclJ6UFRvdFE#gid=0
###
XLF.defaultSurveyDetails =
start_time:
name: "start"
label: "Start time"
description: "Records when the survey was begun"
default: true
asJson:
type: "start"
name: "start"
end_time:
name: "end"
label: "End time"
description: "Records when the survey was marked as completed"
default: true
asJson:
type: "end"
name: "end"
today:
name: "today"
label: "Today"
description: "Includes todays date"
default: false
asJson:
type: "today"
name: "today"
imei:
name: "imei"
label: "Device ID number"
description: "Records the internal device ID number (works on Android phones)"
default: false
asJson:
type: "imei"
name: "imei"
phoneNumber:
name: "phonenumber"
label: "Phone number"
description: "Records the device's phone number, when available"
default: false
asJson:
type: "phonenumber"
name: "phonenumber"
###
XLF.columns is used to determine the order that the elements
are added into the page and the final CSV.
###
XLF.columns = ["type", "name", "label", "hint", "required"]
###
XLF.newRowDetails are the default values that are assigned to a new
row when it is created.
###
XLF.newRowDetails =
name:
value: txtid
randomId: true
label:
value: "new question"
type:
value: "text"
hint:
value: ""
_hideUnlessChanged: true
required:
value: false
_hideUnlessChanged: true
XLF.defaultsForType =
geopoint:
label:
value: "Record your current location"
image:
label:
value: "Point and shoot! Use the camera to take a photo"
video:
label:
value: "Use the camera to record a video"
audio:
label:
value: "Use the camera's microphone to record a sound"
note:
label:
value: "This note can be read out loud"
integer:
label:
value: "Enter a number"
barcode:
hint:
value: "Use the camera to scan a barcode"
decimal:
label:
value: "Enter a number"
date:
label:
value: "Enter a date"
datetime:
label:
value: "Enter a date and time"
| 204343 | ###
Refactoring to consider:
------------------------
SurveyFragment extends Backbone.Collection (to get rid of @rows)
Get rid of XLF.Options
Get rid of XLF.ChoiceLists (?)
Get rid of XLF.SurveyDetails ( maybe ?)
Add "popover text" (or something similar) to XLF.defaultsForType
###
###
@XLF holds much of the models/collections of the XL(s)Form survey
representation in the browser.
###
@XLF = {}
# @log function for debugging
@log = (args...)-> console?.log?.apply console, args
###
XLF.Survey and associated Backbone Model
and Collection definitions
###
class BaseModel extends Backbone.Model
constructor: (arg)->
if "object" is typeof arg and "_parent" of arg
@_parent = arg._parent
delete arg._parent
super arg
class SurveyFragment extends BaseModel
forEachRow: (cb, ctx={})->
@rows.each (r, index, list)->
if r instanceof XLF.SurveyDetail
``
else if r instanceof XLF.Group
context = {}
cb(r.groupStart())
r.forEachRow(cb, context)
cb(r.groupEnd())
``
else
cb(r)
addRow: (r)->
r._parent = @
@rows.add r
addRowAtIndex: (r, index)->
r._parent = @
@rows.add r, at: index
###
XLF...
"Survey",
###
class XLF.Survey extends SurveyFragment
initialize: (options={})->
@rows = new XLF.Rows()
@settings = new XLF.Settings(options.settings)
if (sname = @settings.get("name"))
@set("name", sname)
@newRowDetails = options.newRowDetails || XLF.newRowDetails
@defaultsForType = options.defaultsForType || XLF.defaultsForType
@surveyDetails = new XLF.SurveyDetails(_.values(XLF.defaultSurveyDetails))
passedChoices = options.choices || []
@choices = do ->
choices = new XLF.ChoiceLists()
tmp = {}
choiceNames = []
for choiceRow in passedChoices
lName = choiceRow["list name"]
unless tmp[lName]
tmp[lName] = []
choiceNames.push(lName)
tmp[lName].push(choiceRow)
for cn in choiceNames
choices.add(name: cn, options: tmp[cn])
choices
if options.survey
surveyRows = for r in options.survey
r._parent = @
r
@rows.add surveyRows, collection: @rows, silent: true
toCsvJson: ()->
# build an object that can be easily passed to the "csv" library
# to generate the XL(S)Form spreadsheet
surveyCsvJson = do =>
oCols = ["name", "type", "label"]
oRows = []
addRowToORows = (r)->
colJson = r.toJSON()
for own key, val of colJson when key not in oCols
oCols.push key
oRows.push colJson
@forEachRow addRowToORows
for sd in @surveyDetails.models when sd.get("value")
addRowToORows(sd)
columns: oCols
rowObjects: oRows
choicesCsvJson = do =>
lists = []
@forEachRow (r)->
if (list = r.getList())
lists.push(list)
rows = []
cols = ["list name", "name", "label"]
for choiceList in lists
choiceList.set("name", txtid(), silent: true) unless choiceList.get("name")
clName = choiceList.get("name")
for option in choiceList.options.models
rows.push _.extend {}, option.toJSON(), "list name": choiceList.get("name")
columns: cols
rowObjects: rows
survey: surveyCsvJson
choices: choicesCsvJson
settings: @settings.toCsvJson()
toCSV: ->
sheeted = csv.sheeted()
for shtName, content of @toCsvJson()
sheeted.sheet shtName, csv(content)
sheeted.toString()
###
XLF...
"lookupRowType",
"columnOrder",
"Group",
"Row",
"Rows",
###
XLF.lookupRowType = do->
typeLabels = [
["note", "Note", preventRequired: true],
["text", "Text"], # expects text
["integer", "Integer"], #e.g. 42
["decimal", "Decimal"], #e.g. 3.14
["geopoint", "Geopoint (GPS)"], # Can use satelite GPS coordinates
["image", "Image", isMedia: true], # Can use phone camera, for example
["barcode", "Barcode"], # Can scan a barcode using the phone camera
["date", "Date"], #e.g. (4 July, 1776)
["datetime", "Date and Time"], #e.g. (2012-Jan-4 3:04PM)
["audio", "Audio", isMedia: true], # Can use phone microphone to record audio
["video", "Video", isMedia: true], # Can use phone camera to record video
# ["calculate", "Calculate"],
["select_one", "Select", orOtherOption: true, specifyChoice: true],
["select_multiple", "Multiple choice", orOtherOption: true, specifyChoice: true]
]
class Type
constructor: ([@name, @label, opts])->
opts = {} unless opts
_.extend(@, opts)
types = (new Type(arr) for arr in typeLabels)
exp = (typeId)->
for tp in types when tp.name is typeId
output = tp
output
exp.typeSelectList = do ->
() -> types
exp
XLF.columnOrder = do ->
warned = []
warn = (key)->
unless key in warned
warend.push(key)
console?.error("Order not set for key: #{key}")
(key)->
ki = XLF.columns.indexOf key
warn(key) if ki is -1
if ki is -1 then 100 else ki
class XLF.Group extends SurveyFragment
initialize: ()->
@set "type", "begin group"
@rows = new XLF.Rows()
groupStart: ->
toJSON: => @attributes
inGroupStart: true
groupEnd: ->
toJSON: ()-> type: "end group"
class XLF.Row extends BaseModel
initialize: ->
###
The best way to understand the @details collection is
that it is a list of cells of the XLSForm spreadsheet.
The column name is the "key" and the value is the "value".
We opted for a collection (rather than just saving in the attributes of
this model) because of the various state-related attributes
that need to be saved for each cell and allowing room to grow.
E.g.: {"key": "type", "value": "select_one from colors"}
needs to keep track of how the value was built
###
if @_parent
defaultsUnlessDefined = @_parent.newRowDetails || XLF.newRowDetails
defaultsForType = @_parent.defaultsForType || XLF.defaultsForType
else
console?.error "Row not linked to parent survey."
defaultsUnlessDefined = XLF.newRowDetails
defaultsForType = XLF.defaultsForType
if @attributes.type and @attributes.type of defaultsForType
curTypeDefaults = defaultsForType[@attributes.type]
else
curTypeDefaults = {}
defaults = _.extend {}, defaultsUnlessDefined, curTypeDefaults
for key, vals of defaults
unless key of @attributes
newVals = {}
for vk, vv of vals
newVals[vk] = if ("function" is typeof vv) then vv() else vv
@set key, newVals
@isValid()
typeDetail = @get("type")
tpVal = typeDetail.get("value")
processType = (rd, newType, ctxt)=>
# if value changes, it could be set from an initialization value
# or it could be changed elsewhere.
# we need to keep typeId, listName, and orOther in sync.
[tpid, p2, p3] = newType.split(" ")
typeDetail.set("typeId", tpid, silent: true)
if p2
typeDetail.set("listName", p2, silent: true)
matchedList = @_parent.choices.get(p2)
if matchedList
typeDetail.set("list", matchedList)
typeDetail.set("orOther", p3, silent: true) if p3 is "or_other"
if (rtp = XLF.lookupRowType(tpid))
typeDetail.set("rowType", rtp, silent: true)
else
throw new Error "Type not found: #{tpid}"
processType(typeDetail, tpVal, {})
typeDetail.on "change:value", processType
typeDetail.on "change:listName", (rd, listName, ctx)->
rtp = typeDetail.get("rowType")
typeStr = "#{typeDetail.get("typeId")}"
if rtp.specifyChoice and listName
typeStr += " #{listName}"
if rtp.orOtherOption and typeDetail.get("orOther")
typeStr += " or_other"
typeDetail.set({value: typeStr}, silent: true)
typeDetail.on "change:list", (rd, cl, ctx)->
if typeDetail.get("rowType").specifyChoice
clname = cl.get("name")
unless clname
clname = txtid()
cl.set("name", clname, silent: true)
@set("value", "#{@get('typeId')} #{clname}")
getValue: (what)->
@get(what).get("value")
getList: ->
@get("type")?.get("list")
setList: (list)->
listToSet = @_parent.choices.get(list)
unless listToSet
@_parent.choices.add(list)
listToSet = @_parent.choices.get(list)
throw new Error("List not found: #{list}") unless listToSet
@get("type").set("list", listToSet)
validate: ->
for key, val of @attributes
unless val instanceof XLF.RowDetail
@set key, new XLF.RowDetail(key, val, @), {silent: true}
``
attributesArray: ()->
arr = ([k, v] for k, v of @attributes)
arr.sort (a,b)-> if a[1]._order < b[1]._order then -1 else 1
arr
toJSON: ->
outObj = {}
for [key, val] in @attributesArray() when !val.hidden
outObj[key] = @getValue(key)
outObj
class XLF.Rows extends Backbone.Collection
model: (obj, ctxt)->
type = obj?.type
if type in ["start", "end"]
new XLF.SurveyDetail(obj)
else if type is "group"
new XLF.Group(obj)
else
new XLF.Row(obj)
class XLF.RowDetail extends BaseModel
idAttribute: "name"
constructor: (@key, valOrObj={}, @parentRow)->
super()
vals2set = {}
if _.isString(valOrObj)
vals2set.value = valOrObj
else if "value" of valOrObj
_.extend vals2set, valOrObj
else
vals2set.value = valOrObj
@set(vals2set)
@_order = XLF.columnOrder(@key)
initialize: ()->
if @get("_hideUnlessChanged")
@hidden = true
@_oValue = @get("value")
@on "change", ()->
@hidden = @get("value") is @_oValue
@on "change:value", (rd, val, ctxt)=>
@parentRow.trigger "change", @key, val, ctxt
if @key is "type"
@on "change:list", (rd, val, ctxt)=>
@parentRow.trigger "change", @key, val, ctxt
###
XLF...
"Option",
"Options",
"ChoiceList",
"ChoiceLists",
###
class XLF.Option extends BaseModel
idAttribute: "name"
initialize: -> @unset("list name")
destroy: ->
log "destroy me", @
list: -> @collection
class XLF.Options extends Backbone.Collection
model: XLF.Option
class XLF.ChoiceList extends BaseModel
idAttribute: "name"
constructor: (opts={}, context)->
options = opts.options || []
super name: opts.name, context
@options = new XLF.Options(options || [])
@options.parentList = @
summaryObj: ->
name: @get("name")
options: do =>
opt.attributes for opt in @options.models
class XLF.ChoiceLists extends Backbone.Collection
model: XLF.ChoiceList
summaryObj: ()->
out = {}
for model in @models
out[model.get("name")] = model.summaryObj()
out
###
XLF...
"createSurveyFromCsv"
###
XLF.createSurveyFromCsv = (csv_repr)->
opts = {}
$settings = opts.settings || {}
# $launchEditor = if "launchEditor" in opts then opts.launchEditor else true
$elemWrap = $(opts.elemWrap || '#main')
$publishCb = opts.publish || ->
if csv_repr
if opts.survey or opts.choices
throw new XlformError """
[csv_repr] will cause other options to be ignored: [survey, choices]
"""
cobj = csv.sheeted(csv_repr)
$survey = if (sht = cobj.sheet "survey") then sht.toObjects() else []
$choices = if (sht = cobj.sheet "choices") then sht.toObjects() else []
if (settingsSheet = cobj.sheet "settings")
importedStgns = settingsSheet.toObjects()[0]
else
$survey = opts.survey || []
$choices = opts.choices || [] # settings: $settings
new XLF.Survey(survey: $survey, choices: $choices, settings: $settings)
###
XLF...
"SurveyDetail",
"SurveyDetails"
"Settings",
###
class XLF.SurveyDetail extends BaseModel
idAttribute: "name"
initialize: ()->
@set("value", !!@get("default"))
@unset("default")
if jsonVal = @get("asJson")
@toJSON = ()-> jsonVal
class XLF.SurveyDetails extends Backbone.Collection
model: XLF.SurveyDetail
class XLF.Settings extends BaseModel
defaults:
form_title: "New survey"
toCsvJson: ->
columns = _.keys(@attributes)
rowObjects = [@toJSON()]
columns: columns
rowObjects: rowObjects
###
misc helper methods
###
txtid = ()->
# a is text
# b is numeric or text
# c is mishmash
o = 'AAnCAnn'.replace /[AaCn]/g, (c)->
randChar= ()->
charI = Math.floor(Math.random()*52)
charI += (if charI <= 25 then 65 else 71)
String.fromCharCode charI
r = Math.random()
if c is 'a'
randChar()
else if c is 'A'
String.fromCharCode 65+(r*26|0)
else if c is 'C'
newI = Math.floor(r*62)
if newI > 52 then (newI - 52) else randChar()
else if c is 'n'
Math.floor(r*10)
o.toLowerCase()
###
defaultSurveyDetails
--------------------
These values will be populated in the form builder and the user
will have the option to turn them on or off.
When exported, if the checkbox was selected, the "asJson" value
gets passed to the CSV builder and appended to the end of the
survey.
Details pulled from ODK documents / google docs. Notably this one:
https://docs.google.com/spreadsheet/ccc?key=<KEY>#gid=0
###
XLF.defaultSurveyDetails =
start_time:
name: "start"
label: "Start time"
description: "Records when the survey was begun"
default: true
asJson:
type: "start"
name: "start"
end_time:
name: "end"
label: "End time"
description: "Records when the survey was marked as completed"
default: true
asJson:
type: "end"
name: "end"
today:
name: "today"
label: "Today"
description: "Includes todays date"
default: false
asJson:
type: "today"
name: "today"
imei:
name: "imei"
label: "Device ID number"
description: "Records the internal device ID number (works on Android phones)"
default: false
asJson:
type: "imei"
name: "imei"
phoneNumber:
name: "phonenumber"
label: "Phone number"
description: "Records the device's phone number, when available"
default: false
asJson:
type: "phonenumber"
name: "phonenumber"
###
XLF.columns is used to determine the order that the elements
are added into the page and the final CSV.
###
XLF.columns = ["type", "name", "label", "hint", "required"]
###
XLF.newRowDetails are the default values that are assigned to a new
row when it is created.
###
XLF.newRowDetails =
name:
value: txtid
randomId: true
label:
value: "new question"
type:
value: "text"
hint:
value: ""
_hideUnlessChanged: true
required:
value: false
_hideUnlessChanged: true
XLF.defaultsForType =
geopoint:
label:
value: "Record your current location"
image:
label:
value: "Point and shoot! Use the camera to take a photo"
video:
label:
value: "Use the camera to record a video"
audio:
label:
value: "Use the camera's microphone to record a sound"
note:
label:
value: "This note can be read out loud"
integer:
label:
value: "Enter a number"
barcode:
hint:
value: "Use the camera to scan a barcode"
decimal:
label:
value: "Enter a number"
date:
label:
value: "Enter a date"
datetime:
label:
value: "Enter a date and time"
| true | ###
Refactoring to consider:
------------------------
SurveyFragment extends Backbone.Collection (to get rid of @rows)
Get rid of XLF.Options
Get rid of XLF.ChoiceLists (?)
Get rid of XLF.SurveyDetails ( maybe ?)
Add "popover text" (or something similar) to XLF.defaultsForType
###
###
@XLF holds much of the models/collections of the XL(s)Form survey
representation in the browser.
###
@XLF = {}
# @log function for debugging
@log = (args...)-> console?.log?.apply console, args
###
XLF.Survey and associated Backbone Model
and Collection definitions
###
class BaseModel extends Backbone.Model
constructor: (arg)->
if "object" is typeof arg and "_parent" of arg
@_parent = arg._parent
delete arg._parent
super arg
class SurveyFragment extends BaseModel
forEachRow: (cb, ctx={})->
@rows.each (r, index, list)->
if r instanceof XLF.SurveyDetail
``
else if r instanceof XLF.Group
context = {}
cb(r.groupStart())
r.forEachRow(cb, context)
cb(r.groupEnd())
``
else
cb(r)
addRow: (r)->
r._parent = @
@rows.add r
addRowAtIndex: (r, index)->
r._parent = @
@rows.add r, at: index
###
XLF...
"Survey",
###
class XLF.Survey extends SurveyFragment
initialize: (options={})->
@rows = new XLF.Rows()
@settings = new XLF.Settings(options.settings)
if (sname = @settings.get("name"))
@set("name", sname)
@newRowDetails = options.newRowDetails || XLF.newRowDetails
@defaultsForType = options.defaultsForType || XLF.defaultsForType
@surveyDetails = new XLF.SurveyDetails(_.values(XLF.defaultSurveyDetails))
passedChoices = options.choices || []
@choices = do ->
choices = new XLF.ChoiceLists()
tmp = {}
choiceNames = []
for choiceRow in passedChoices
lName = choiceRow["list name"]
unless tmp[lName]
tmp[lName] = []
choiceNames.push(lName)
tmp[lName].push(choiceRow)
for cn in choiceNames
choices.add(name: cn, options: tmp[cn])
choices
if options.survey
surveyRows = for r in options.survey
r._parent = @
r
@rows.add surveyRows, collection: @rows, silent: true
toCsvJson: ()->
# build an object that can be easily passed to the "csv" library
# to generate the XL(S)Form spreadsheet
surveyCsvJson = do =>
oCols = ["name", "type", "label"]
oRows = []
addRowToORows = (r)->
colJson = r.toJSON()
for own key, val of colJson when key not in oCols
oCols.push key
oRows.push colJson
@forEachRow addRowToORows
for sd in @surveyDetails.models when sd.get("value")
addRowToORows(sd)
columns: oCols
rowObjects: oRows
choicesCsvJson = do =>
lists = []
@forEachRow (r)->
if (list = r.getList())
lists.push(list)
rows = []
cols = ["list name", "name", "label"]
for choiceList in lists
choiceList.set("name", txtid(), silent: true) unless choiceList.get("name")
clName = choiceList.get("name")
for option in choiceList.options.models
rows.push _.extend {}, option.toJSON(), "list name": choiceList.get("name")
columns: cols
rowObjects: rows
survey: surveyCsvJson
choices: choicesCsvJson
settings: @settings.toCsvJson()
toCSV: ->
sheeted = csv.sheeted()
for shtName, content of @toCsvJson()
sheeted.sheet shtName, csv(content)
sheeted.toString()
###
XLF...
"lookupRowType",
"columnOrder",
"Group",
"Row",
"Rows",
###
XLF.lookupRowType = do->
typeLabels = [
["note", "Note", preventRequired: true],
["text", "Text"], # expects text
["integer", "Integer"], #e.g. 42
["decimal", "Decimal"], #e.g. 3.14
["geopoint", "Geopoint (GPS)"], # Can use satelite GPS coordinates
["image", "Image", isMedia: true], # Can use phone camera, for example
["barcode", "Barcode"], # Can scan a barcode using the phone camera
["date", "Date"], #e.g. (4 July, 1776)
["datetime", "Date and Time"], #e.g. (2012-Jan-4 3:04PM)
["audio", "Audio", isMedia: true], # Can use phone microphone to record audio
["video", "Video", isMedia: true], # Can use phone camera to record video
# ["calculate", "Calculate"],
["select_one", "Select", orOtherOption: true, specifyChoice: true],
["select_multiple", "Multiple choice", orOtherOption: true, specifyChoice: true]
]
class Type
constructor: ([@name, @label, opts])->
opts = {} unless opts
_.extend(@, opts)
types = (new Type(arr) for arr in typeLabels)
exp = (typeId)->
for tp in types when tp.name is typeId
output = tp
output
exp.typeSelectList = do ->
() -> types
exp
XLF.columnOrder = do ->
warned = []
warn = (key)->
unless key in warned
warend.push(key)
console?.error("Order not set for key: #{key}")
(key)->
ki = XLF.columns.indexOf key
warn(key) if ki is -1
if ki is -1 then 100 else ki
class XLF.Group extends SurveyFragment
initialize: ()->
@set "type", "begin group"
@rows = new XLF.Rows()
groupStart: ->
toJSON: => @attributes
inGroupStart: true
groupEnd: ->
toJSON: ()-> type: "end group"
class XLF.Row extends BaseModel
initialize: ->
###
The best way to understand the @details collection is
that it is a list of cells of the XLSForm spreadsheet.
The column name is the "key" and the value is the "value".
We opted for a collection (rather than just saving in the attributes of
this model) because of the various state-related attributes
that need to be saved for each cell and allowing room to grow.
E.g.: {"key": "type", "value": "select_one from colors"}
needs to keep track of how the value was built
###
if @_parent
defaultsUnlessDefined = @_parent.newRowDetails || XLF.newRowDetails
defaultsForType = @_parent.defaultsForType || XLF.defaultsForType
else
console?.error "Row not linked to parent survey."
defaultsUnlessDefined = XLF.newRowDetails
defaultsForType = XLF.defaultsForType
if @attributes.type and @attributes.type of defaultsForType
curTypeDefaults = defaultsForType[@attributes.type]
else
curTypeDefaults = {}
defaults = _.extend {}, defaultsUnlessDefined, curTypeDefaults
for key, vals of defaults
unless key of @attributes
newVals = {}
for vk, vv of vals
newVals[vk] = if ("function" is typeof vv) then vv() else vv
@set key, newVals
@isValid()
typeDetail = @get("type")
tpVal = typeDetail.get("value")
processType = (rd, newType, ctxt)=>
# if value changes, it could be set from an initialization value
# or it could be changed elsewhere.
# we need to keep typeId, listName, and orOther in sync.
[tpid, p2, p3] = newType.split(" ")
typeDetail.set("typeId", tpid, silent: true)
if p2
typeDetail.set("listName", p2, silent: true)
matchedList = @_parent.choices.get(p2)
if matchedList
typeDetail.set("list", matchedList)
typeDetail.set("orOther", p3, silent: true) if p3 is "or_other"
if (rtp = XLF.lookupRowType(tpid))
typeDetail.set("rowType", rtp, silent: true)
else
throw new Error "Type not found: #{tpid}"
processType(typeDetail, tpVal, {})
typeDetail.on "change:value", processType
typeDetail.on "change:listName", (rd, listName, ctx)->
rtp = typeDetail.get("rowType")
typeStr = "#{typeDetail.get("typeId")}"
if rtp.specifyChoice and listName
typeStr += " #{listName}"
if rtp.orOtherOption and typeDetail.get("orOther")
typeStr += " or_other"
typeDetail.set({value: typeStr}, silent: true)
typeDetail.on "change:list", (rd, cl, ctx)->
if typeDetail.get("rowType").specifyChoice
clname = cl.get("name")
unless clname
clname = txtid()
cl.set("name", clname, silent: true)
@set("value", "#{@get('typeId')} #{clname}")
getValue: (what)->
@get(what).get("value")
getList: ->
@get("type")?.get("list")
setList: (list)->
listToSet = @_parent.choices.get(list)
unless listToSet
@_parent.choices.add(list)
listToSet = @_parent.choices.get(list)
throw new Error("List not found: #{list}") unless listToSet
@get("type").set("list", listToSet)
validate: ->
for key, val of @attributes
unless val instanceof XLF.RowDetail
@set key, new XLF.RowDetail(key, val, @), {silent: true}
``
attributesArray: ()->
arr = ([k, v] for k, v of @attributes)
arr.sort (a,b)-> if a[1]._order < b[1]._order then -1 else 1
arr
toJSON: ->
outObj = {}
for [key, val] in @attributesArray() when !val.hidden
outObj[key] = @getValue(key)
outObj
class XLF.Rows extends Backbone.Collection
model: (obj, ctxt)->
type = obj?.type
if type in ["start", "end"]
new XLF.SurveyDetail(obj)
else if type is "group"
new XLF.Group(obj)
else
new XLF.Row(obj)
class XLF.RowDetail extends BaseModel
idAttribute: "name"
constructor: (@key, valOrObj={}, @parentRow)->
super()
vals2set = {}
if _.isString(valOrObj)
vals2set.value = valOrObj
else if "value" of valOrObj
_.extend vals2set, valOrObj
else
vals2set.value = valOrObj
@set(vals2set)
@_order = XLF.columnOrder(@key)
initialize: ()->
if @get("_hideUnlessChanged")
@hidden = true
@_oValue = @get("value")
@on "change", ()->
@hidden = @get("value") is @_oValue
@on "change:value", (rd, val, ctxt)=>
@parentRow.trigger "change", @key, val, ctxt
if @key is "type"
@on "change:list", (rd, val, ctxt)=>
@parentRow.trigger "change", @key, val, ctxt
###
XLF...
"Option",
"Options",
"ChoiceList",
"ChoiceLists",
###
class XLF.Option extends BaseModel
idAttribute: "name"
initialize: -> @unset("list name")
destroy: ->
log "destroy me", @
list: -> @collection
class XLF.Options extends Backbone.Collection
model: XLF.Option
class XLF.ChoiceList extends BaseModel
idAttribute: "name"
constructor: (opts={}, context)->
options = opts.options || []
super name: opts.name, context
@options = new XLF.Options(options || [])
@options.parentList = @
summaryObj: ->
name: @get("name")
options: do =>
opt.attributes for opt in @options.models
class XLF.ChoiceLists extends Backbone.Collection
model: XLF.ChoiceList
summaryObj: ()->
out = {}
for model in @models
out[model.get("name")] = model.summaryObj()
out
###
XLF...
"createSurveyFromCsv"
###
XLF.createSurveyFromCsv = (csv_repr)->
opts = {}
$settings = opts.settings || {}
# $launchEditor = if "launchEditor" in opts then opts.launchEditor else true
$elemWrap = $(opts.elemWrap || '#main')
$publishCb = opts.publish || ->
if csv_repr
if opts.survey or opts.choices
throw new XlformError """
[csv_repr] will cause other options to be ignored: [survey, choices]
"""
cobj = csv.sheeted(csv_repr)
$survey = if (sht = cobj.sheet "survey") then sht.toObjects() else []
$choices = if (sht = cobj.sheet "choices") then sht.toObjects() else []
if (settingsSheet = cobj.sheet "settings")
importedStgns = settingsSheet.toObjects()[0]
else
$survey = opts.survey || []
$choices = opts.choices || [] # settings: $settings
new XLF.Survey(survey: $survey, choices: $choices, settings: $settings)
###
XLF...
"SurveyDetail",
"SurveyDetails"
"Settings",
###
class XLF.SurveyDetail extends BaseModel
idAttribute: "name"
initialize: ()->
@set("value", !!@get("default"))
@unset("default")
if jsonVal = @get("asJson")
@toJSON = ()-> jsonVal
class XLF.SurveyDetails extends Backbone.Collection
model: XLF.SurveyDetail
class XLF.Settings extends BaseModel
defaults:
form_title: "New survey"
toCsvJson: ->
columns = _.keys(@attributes)
rowObjects = [@toJSON()]
columns: columns
rowObjects: rowObjects
###
misc helper methods
###
txtid = ()->
# a is text
# b is numeric or text
# c is mishmash
o = 'AAnCAnn'.replace /[AaCn]/g, (c)->
randChar= ()->
charI = Math.floor(Math.random()*52)
charI += (if charI <= 25 then 65 else 71)
String.fromCharCode charI
r = Math.random()
if c is 'a'
randChar()
else if c is 'A'
String.fromCharCode 65+(r*26|0)
else if c is 'C'
newI = Math.floor(r*62)
if newI > 52 then (newI - 52) else randChar()
else if c is 'n'
Math.floor(r*10)
o.toLowerCase()
###
defaultSurveyDetails
--------------------
These values will be populated in the form builder and the user
will have the option to turn them on or off.
When exported, if the checkbox was selected, the "asJson" value
gets passed to the CSV builder and appended to the end of the
survey.
Details pulled from ODK documents / google docs. Notably this one:
https://docs.google.com/spreadsheet/ccc?key=PI:KEY:<KEY>END_PI#gid=0
###
XLF.defaultSurveyDetails =
start_time:
name: "start"
label: "Start time"
description: "Records when the survey was begun"
default: true
asJson:
type: "start"
name: "start"
end_time:
name: "end"
label: "End time"
description: "Records when the survey was marked as completed"
default: true
asJson:
type: "end"
name: "end"
today:
name: "today"
label: "Today"
description: "Includes todays date"
default: false
asJson:
type: "today"
name: "today"
imei:
name: "imei"
label: "Device ID number"
description: "Records the internal device ID number (works on Android phones)"
default: false
asJson:
type: "imei"
name: "imei"
phoneNumber:
name: "phonenumber"
label: "Phone number"
description: "Records the device's phone number, when available"
default: false
asJson:
type: "phonenumber"
name: "phonenumber"
###
XLF.columns is used to determine the order that the elements
are added into the page and the final CSV.
###
XLF.columns = ["type", "name", "label", "hint", "required"]
###
XLF.newRowDetails are the default values that are assigned to a new
row when it is created.
###
XLF.newRowDetails =
name:
value: txtid
randomId: true
label:
value: "new question"
type:
value: "text"
hint:
value: ""
_hideUnlessChanged: true
required:
value: false
_hideUnlessChanged: true
XLF.defaultsForType =
geopoint:
label:
value: "Record your current location"
image:
label:
value: "Point and shoot! Use the camera to take a photo"
video:
label:
value: "Use the camera to record a video"
audio:
label:
value: "Use the camera's microphone to record a sound"
note:
label:
value: "This note can be read out loud"
integer:
label:
value: "Enter a number"
barcode:
hint:
value: "Use the camera to scan a barcode"
decimal:
label:
value: "Enter a number"
date:
label:
value: "Enter a date"
datetime:
label:
value: "Enter a date and time"
|
[
{
"context": "epos are in */\n const GITHUB_ACCESS_TOKEN = 'f1d5f369b79a97646a0935c4e34010938ab4d7a0'; /* Create an access token here: https://github.",
"end": 496,
"score": 0.6226474046707153,
"start": 456,
"tag": "PASSWORD",
"value": "f1d5f369b79a97646a0935c4e34010938ab4d7a0"
}
] | notes/baff2ed4-88f7-4358-b5d5-add6b454441d.cson | runesam/dev-notes | 0 | createdAt: "2020-07-08T18:53:52.898Z"
updatedAt: "2020-07-08T18:54:39.332Z"
type: "SNIPPET_NOTE"
folder: "ab21d9b8c8f4ac7cf2d1"
title: "add user to team for multible repos"
description: "add user to team for multible repos"
snippets: [
{
name: "js"
mode: "text"
content: '''
const GITHUB_ORG = 'fresh-energy'; /* Name of the github organization the team is under and the repos are in */
const GITHUB_ACCESS_TOKEN = 'f1d5f369b79a97646a0935c4e34010938ab4d7a0'; /* Create an access token here: https://github.com/settings/tokens */
const TEAM_ID = 'pc-dd'; /* Github team ID, not the same as the name, get it from the API */
const TEAM_PERMISSION = 'pull'; /* 'pull' or 'push' or 'admin' */
const { exec } = require('child_process');
function execPromise(command) {
return new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => {
if (err) {
return reject(err);
}
resolve([stdout, stderr]);
});
});
}
async function fetchReposPage(org, page) {
const [response] = await execPromise(
`curl -i -H "Authorization: token ${GITHUB_ACCESS_TOKEN}" https://api.github.com/orgs/${org}/teams`
);
console.log(response);
}
fetchReposPage(GITHUB_ORG)
'''
}
]
tags: [
"github"
]
isStarred: false
isTrashed: false
| 153702 | createdAt: "2020-07-08T18:53:52.898Z"
updatedAt: "2020-07-08T18:54:39.332Z"
type: "SNIPPET_NOTE"
folder: "ab21d9b8c8f4ac7cf2d1"
title: "add user to team for multible repos"
description: "add user to team for multible repos"
snippets: [
{
name: "js"
mode: "text"
content: '''
const GITHUB_ORG = 'fresh-energy'; /* Name of the github organization the team is under and the repos are in */
const GITHUB_ACCESS_TOKEN = '<PASSWORD>'; /* Create an access token here: https://github.com/settings/tokens */
const TEAM_ID = 'pc-dd'; /* Github team ID, not the same as the name, get it from the API */
const TEAM_PERMISSION = 'pull'; /* 'pull' or 'push' or 'admin' */
const { exec } = require('child_process');
function execPromise(command) {
return new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => {
if (err) {
return reject(err);
}
resolve([stdout, stderr]);
});
});
}
async function fetchReposPage(org, page) {
const [response] = await execPromise(
`curl -i -H "Authorization: token ${GITHUB_ACCESS_TOKEN}" https://api.github.com/orgs/${org}/teams`
);
console.log(response);
}
fetchReposPage(GITHUB_ORG)
'''
}
]
tags: [
"github"
]
isStarred: false
isTrashed: false
| true | createdAt: "2020-07-08T18:53:52.898Z"
updatedAt: "2020-07-08T18:54:39.332Z"
type: "SNIPPET_NOTE"
folder: "ab21d9b8c8f4ac7cf2d1"
title: "add user to team for multible repos"
description: "add user to team for multible repos"
snippets: [
{
name: "js"
mode: "text"
content: '''
const GITHUB_ORG = 'fresh-energy'; /* Name of the github organization the team is under and the repos are in */
const GITHUB_ACCESS_TOKEN = 'PI:PASSWORD:<PASSWORD>END_PI'; /* Create an access token here: https://github.com/settings/tokens */
const TEAM_ID = 'pc-dd'; /* Github team ID, not the same as the name, get it from the API */
const TEAM_PERMISSION = 'pull'; /* 'pull' or 'push' or 'admin' */
const { exec } = require('child_process');
function execPromise(command) {
return new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => {
if (err) {
return reject(err);
}
resolve([stdout, stderr]);
});
});
}
async function fetchReposPage(org, page) {
const [response] = await execPromise(
`curl -i -H "Authorization: token ${GITHUB_ACCESS_TOKEN}" https://api.github.com/orgs/${org}/teams`
);
console.log(response);
}
fetchReposPage(GITHUB_ORG)
'''
}
]
tags: [
"github"
]
isStarred: false
isTrashed: false
|
[
{
"context": " UserModel.add({userid:req_param.userid, password:req_param.password, name:req_param.name , description:req_param.desc",
"end": 565,
"score": 0.9818074107170105,
"start": 547,
"tag": "PASSWORD",
"value": "req_param.password"
}
] | controller/user/user_controller.coffee | rirufa/roomchat-server | 0 | ApiBaseController = require('../api_base_controller')
UserModel = require('../../model/user')
class UserController extends ApiBaseController
@ENTRYPOINT = '/api/v1/user'
onGetAsync: (req,res)->
req_param = req.body
if typeof req_param.id == "undefined"
users = await UserModel.get_all()
else
users = await UserModel.get({id:req_param.id})
return {
sucess: true,
content: users
}
onPostAsync: (req,res)->
req_param = req.body
user = await UserModel.add({userid:req_param.userid, password:req_param.password, name:req_param.name , description:req_param.description})
return {
sucess: true
content: user
}
module.exports = UserController | 2170 | ApiBaseController = require('../api_base_controller')
UserModel = require('../../model/user')
class UserController extends ApiBaseController
@ENTRYPOINT = '/api/v1/user'
onGetAsync: (req,res)->
req_param = req.body
if typeof req_param.id == "undefined"
users = await UserModel.get_all()
else
users = await UserModel.get({id:req_param.id})
return {
sucess: true,
content: users
}
onPostAsync: (req,res)->
req_param = req.body
user = await UserModel.add({userid:req_param.userid, password:<PASSWORD>, name:req_param.name , description:req_param.description})
return {
sucess: true
content: user
}
module.exports = UserController | true | ApiBaseController = require('../api_base_controller')
UserModel = require('../../model/user')
class UserController extends ApiBaseController
@ENTRYPOINT = '/api/v1/user'
onGetAsync: (req,res)->
req_param = req.body
if typeof req_param.id == "undefined"
users = await UserModel.get_all()
else
users = await UserModel.get({id:req_param.id})
return {
sucess: true,
content: users
}
onPostAsync: (req,res)->
req_param = req.body
user = await UserModel.add({userid:req_param.userid, password:PI:PASSWORD:<PASSWORD>END_PI, name:req_param.name , description:req_param.description})
return {
sucess: true
content: user
}
module.exports = UserController |
[
{
"context": "e generated from a given string\n# \n#\n# Author:\n# chris woodham\n\nmodule.exports = (robot) ->\n\n robot.hear /(.+)/",
"end": 495,
"score": 0.9996669292449951,
"start": 482,
"tag": "NAME",
"value": "chris woodham"
}
] | scripts/jason.coffee | Woodham/hubot-jason | 0 | # Description:
# Jason's intelligence
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot hear <something> say <something else> - if hubot hears <something>, he has a chance of saying <something else> (note that regex capture groups can be replaced with e.g. [1], [2] etc and the person who triggerd the response can be replaced with [who])
# hubot say for <something> - list the responses that can be generated from a given string
#
#
# Author:
# chris woodham
module.exports = (robot) ->
robot.hear /(.+)/i, (msg) ->
sender = msg.message.user.name.split(" ")[0]
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[1]
unless trigger.toLowerCase().slice(0, robot.name.length) == robot.name.toLowerCase() # don't trigger on bot commands
possResponses = []
responseKeys = {}
for k,v of robot.brain.data.jason.response
rex = new RegExp k, 'i'
if rex.test trigger
for resp in v
responseKeys[resp] = rex
possResponses.push resp
if possResponses.length > 0
selected = Math.floor(Math.random() * (possResponses.length * 4)) # make the choice of response 4 times longer than the number of them to give a smaller chance of responding
if possResponses[selected]?
response = possResponses[selected]
test = responseKeys[response]
replacements = test.exec(trigger)
response = response.replace /\[[0-9]+\]/g, (match) ->
mi = match.replace('[', '')
mi = mi.replace(']', '')
mi = +mi
if replacements[mi]?
return replacements[mi]
else
return match
response = response.replace /\[who\]/g, (match) ->
return sender
msg.send response
robot.respond /say for (.+)/i, (msg) ->
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[2]
possResponses = []
responseKeys = {}
for k,v of robot.brain.data.jason.response
rex = new RegExp k, 'i'
if rex.test trigger
for resp in v
msg.send k + " -> " + resp
robot.respond /hear (.+) say (.+)/i, (msg) ->
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[1]
trigger = trigger.trim()
resp = msg.match[2]
resp = resp.trim()
meth = if /hear (.+) don't say (.+)/i.test msg.message.text then "don't say" else "say"
if meth == 'say'
try
test = RegExp trigger, 'i'
robot.brain.data.jason.response[trigger] ||= []
robot.brain.data.jason.response[trigger].push resp
msg.send "okay"
catch e
msg.send "That's no regex fool!"
else if meth == "don't say"
dind = trigger.lastIndexOf "don't"
trigger = trigger.slice 0, dind
trigger = trigger.trim()
if robot.brain.data.jason.response[trigger]? and resp in robot.brain.data.jason.response[trigger]
ind = robot.brain.data.jason.response[trigger].indexOf trigger
robot.brain.data.jason.response[trigger].splice ind, 1
msg.send "okay, I won't"
else
msg.send "I wasn't going to anyway"
| 106917 | # Description:
# Jason's intelligence
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot hear <something> say <something else> - if hubot hears <something>, he has a chance of saying <something else> (note that regex capture groups can be replaced with e.g. [1], [2] etc and the person who triggerd the response can be replaced with [who])
# hubot say for <something> - list the responses that can be generated from a given string
#
#
# Author:
# <NAME>
module.exports = (robot) ->
robot.hear /(.+)/i, (msg) ->
sender = msg.message.user.name.split(" ")[0]
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[1]
unless trigger.toLowerCase().slice(0, robot.name.length) == robot.name.toLowerCase() # don't trigger on bot commands
possResponses = []
responseKeys = {}
for k,v of robot.brain.data.jason.response
rex = new RegExp k, 'i'
if rex.test trigger
for resp in v
responseKeys[resp] = rex
possResponses.push resp
if possResponses.length > 0
selected = Math.floor(Math.random() * (possResponses.length * 4)) # make the choice of response 4 times longer than the number of them to give a smaller chance of responding
if possResponses[selected]?
response = possResponses[selected]
test = responseKeys[response]
replacements = test.exec(trigger)
response = response.replace /\[[0-9]+\]/g, (match) ->
mi = match.replace('[', '')
mi = mi.replace(']', '')
mi = +mi
if replacements[mi]?
return replacements[mi]
else
return match
response = response.replace /\[who\]/g, (match) ->
return sender
msg.send response
robot.respond /say for (.+)/i, (msg) ->
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[2]
possResponses = []
responseKeys = {}
for k,v of robot.brain.data.jason.response
rex = new RegExp k, 'i'
if rex.test trigger
for resp in v
msg.send k + " -> " + resp
robot.respond /hear (.+) say (.+)/i, (msg) ->
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[1]
trigger = trigger.trim()
resp = msg.match[2]
resp = resp.trim()
meth = if /hear (.+) don't say (.+)/i.test msg.message.text then "don't say" else "say"
if meth == 'say'
try
test = RegExp trigger, 'i'
robot.brain.data.jason.response[trigger] ||= []
robot.brain.data.jason.response[trigger].push resp
msg.send "okay"
catch e
msg.send "That's no regex fool!"
else if meth == "don't say"
dind = trigger.lastIndexOf "don't"
trigger = trigger.slice 0, dind
trigger = trigger.trim()
if robot.brain.data.jason.response[trigger]? and resp in robot.brain.data.jason.response[trigger]
ind = robot.brain.data.jason.response[trigger].indexOf trigger
robot.brain.data.jason.response[trigger].splice ind, 1
msg.send "okay, I won't"
else
msg.send "I wasn't going to anyway"
| true | # Description:
# Jason's intelligence
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot hear <something> say <something else> - if hubot hears <something>, he has a chance of saying <something else> (note that regex capture groups can be replaced with e.g. [1], [2] etc and the person who triggerd the response can be replaced with [who])
# hubot say for <something> - list the responses that can be generated from a given string
#
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.hear /(.+)/i, (msg) ->
sender = msg.message.user.name.split(" ")[0]
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[1]
unless trigger.toLowerCase().slice(0, robot.name.length) == robot.name.toLowerCase() # don't trigger on bot commands
possResponses = []
responseKeys = {}
for k,v of robot.brain.data.jason.response
rex = new RegExp k, 'i'
if rex.test trigger
for resp in v
responseKeys[resp] = rex
possResponses.push resp
if possResponses.length > 0
selected = Math.floor(Math.random() * (possResponses.length * 4)) # make the choice of response 4 times longer than the number of them to give a smaller chance of responding
if possResponses[selected]?
response = possResponses[selected]
test = responseKeys[response]
replacements = test.exec(trigger)
response = response.replace /\[[0-9]+\]/g, (match) ->
mi = match.replace('[', '')
mi = mi.replace(']', '')
mi = +mi
if replacements[mi]?
return replacements[mi]
else
return match
response = response.replace /\[who\]/g, (match) ->
return sender
msg.send response
robot.respond /say for (.+)/i, (msg) ->
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[2]
possResponses = []
responseKeys = {}
for k,v of robot.brain.data.jason.response
rex = new RegExp k, 'i'
if rex.test trigger
for resp in v
msg.send k + " -> " + resp
robot.respond /hear (.+) say (.+)/i, (msg) ->
robot.brain.data.jason ||= {}
robot.brain.data.jason.response ||= {}
trigger = msg.match[1]
trigger = trigger.trim()
resp = msg.match[2]
resp = resp.trim()
meth = if /hear (.+) don't say (.+)/i.test msg.message.text then "don't say" else "say"
if meth == 'say'
try
test = RegExp trigger, 'i'
robot.brain.data.jason.response[trigger] ||= []
robot.brain.data.jason.response[trigger].push resp
msg.send "okay"
catch e
msg.send "That's no regex fool!"
else if meth == "don't say"
dind = trigger.lastIndexOf "don't"
trigger = trigger.slice 0, dind
trigger = trigger.trim()
if robot.brain.data.jason.response[trigger]? and resp in robot.brain.data.jason.response[trigger]
ind = robot.brain.data.jason.response[trigger].indexOf trigger
robot.brain.data.jason.response[trigger].splice ind, 1
msg.send "okay, I won't"
else
msg.send "I wasn't going to anyway"
|
[
{
"context": "launch this project, please email <a href=\"mailto:contact@zooniverse.org\">contact@zooniverse.org</a> to submit your reques",
"end": 3377,
"score": 0.9999261498451233,
"start": 3355,
"tag": "EMAIL",
"value": "contact@zooniverse.org"
},
{
"context": "ase email <a href=\... | app/pages/lab/visibility.cjsx | LLiprandi/Panoptes-Front-End | 72 | React = require 'react'
PropTypes = require 'prop-types'
{Link} = require 'react-router'
createReactClass = require 'create-react-class'
apiClient = require 'panoptes-client/lib/api-client'
SetToggle = require '../../lib/set-toggle'
uniq = require 'lodash/uniq'
Paginator = require '../../talk/lib/paginator'
ApplyForBetaForm = require('./apply-for-beta').default
module.exports = createReactClass
displayName: 'EditProjectVisibility'
getDefaultProps: ->
project: null
getInitialState: ->
error: null
setting:
private: false
beta_requested: false
launch_requested: false
mixins: [SetToggle]
setterProperty: 'project'
setRadio: (property, value) ->
@set property, value
render: ->
looksDisabled =
opacity: 0.7
pointerEvents: 'none'
<div>
<p className="form-label">Project state and visibility</p>
{if @state.error
<p className="form-help error">{@state.error.toString()}</p>}
<p>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="private" value={true} data-json-value={true} checked={@props.project.private} disabled={@state.setting.private} onChange={@setRadio.bind this, 'private', true} />
Private
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="private" value={false} data-json-value={true} checked={not @props.project.private} disabled={@state.setting.private} onChange={@setRadio.bind this, 'private', false} />
Public
</label>
</p>
<p className="form-help">Only the assigned <strong>collaborators</strong> can view a private project. Anyone with the URL can access a public project.</p>
<hr/>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="live" value={true} data-json-value={true} checked={not @props.project.live} disabled={@state.setting.live} onChange={@setRadio.bind this, 'live', false} />
Development
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="live" value={false} data-json-value={true} checked={@props.project.live} disabled={@state.setting.live} onChange={@setRadio.bind this, 'live', true} />
Live
</label>
<p className="form-help">
All workflows can be edited during development, and subjects will never retire.<br />
In a live project, active workflows are locked and can no longer be edited.<br />
<small>
<strong>
Take care changing a project to development as classifications will not count towards your project.
</strong>
</small>
</p>
<div>
<hr />
<p className="form-label">Beta status</p>
{if @props.project.beta_approved
<span>
<div className="approval-status">
<span>Beta Approval Status: </span>
<span className="color-label green">Approved</span>
</div>
<p>
Review status for this project has been approved. To end the review and make changes, switch back to <em>development</em> mode.
{unless @props.project.launch_requested or @props.project.launch_approved
<span>If you’re ready to launch this project, please email <a href="mailto:contact@zooniverse.org">contact@zooniverse.org</a> to submit your request.</span>}
</p>
</span>
else if @props.project.beta_requested
<div className="approval-status">
<span>Beta Approval Status: </span>
<span className="color-label orange">Pending</span>
</div>
<span>Review status has been applied for. <button type="button" disabled={@state.setting.beta_requested} onClick={@set.bind this, 'beta_requested', false}>Cancel application</button></span>
else
<ApplyForBetaForm project={@props.project} applyFn={@set.bind this, 'beta_requested', true} />
}
</div>
</div>
| 133564 | React = require 'react'
PropTypes = require 'prop-types'
{Link} = require 'react-router'
createReactClass = require 'create-react-class'
apiClient = require 'panoptes-client/lib/api-client'
SetToggle = require '../../lib/set-toggle'
uniq = require 'lodash/uniq'
Paginator = require '../../talk/lib/paginator'
ApplyForBetaForm = require('./apply-for-beta').default
module.exports = createReactClass
displayName: 'EditProjectVisibility'
getDefaultProps: ->
project: null
getInitialState: ->
error: null
setting:
private: false
beta_requested: false
launch_requested: false
mixins: [SetToggle]
setterProperty: 'project'
setRadio: (property, value) ->
@set property, value
render: ->
looksDisabled =
opacity: 0.7
pointerEvents: 'none'
<div>
<p className="form-label">Project state and visibility</p>
{if @state.error
<p className="form-help error">{@state.error.toString()}</p>}
<p>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="private" value={true} data-json-value={true} checked={@props.project.private} disabled={@state.setting.private} onChange={@setRadio.bind this, 'private', true} />
Private
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="private" value={false} data-json-value={true} checked={not @props.project.private} disabled={@state.setting.private} onChange={@setRadio.bind this, 'private', false} />
Public
</label>
</p>
<p className="form-help">Only the assigned <strong>collaborators</strong> can view a private project. Anyone with the URL can access a public project.</p>
<hr/>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="live" value={true} data-json-value={true} checked={not @props.project.live} disabled={@state.setting.live} onChange={@setRadio.bind this, 'live', false} />
Development
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="live" value={false} data-json-value={true} checked={@props.project.live} disabled={@state.setting.live} onChange={@setRadio.bind this, 'live', true} />
Live
</label>
<p className="form-help">
All workflows can be edited during development, and subjects will never retire.<br />
In a live project, active workflows are locked and can no longer be edited.<br />
<small>
<strong>
Take care changing a project to development as classifications will not count towards your project.
</strong>
</small>
</p>
<div>
<hr />
<p className="form-label">Beta status</p>
{if @props.project.beta_approved
<span>
<div className="approval-status">
<span>Beta Approval Status: </span>
<span className="color-label green">Approved</span>
</div>
<p>
Review status for this project has been approved. To end the review and make changes, switch back to <em>development</em> mode.
{unless @props.project.launch_requested or @props.project.launch_approved
<span>If you’re ready to launch this project, please email <a href="mailto:<EMAIL>"><EMAIL></a> to submit your request.</span>}
</p>
</span>
else if @props.project.beta_requested
<div className="approval-status">
<span>Beta Approval Status: </span>
<span className="color-label orange">Pending</span>
</div>
<span>Review status has been applied for. <button type="button" disabled={@state.setting.beta_requested} onClick={@set.bind this, 'beta_requested', false}>Cancel application</button></span>
else
<ApplyForBetaForm project={@props.project} applyFn={@set.bind this, 'beta_requested', true} />
}
</div>
</div>
| true | React = require 'react'
PropTypes = require 'prop-types'
{Link} = require 'react-router'
createReactClass = require 'create-react-class'
apiClient = require 'panoptes-client/lib/api-client'
SetToggle = require '../../lib/set-toggle'
uniq = require 'lodash/uniq'
Paginator = require '../../talk/lib/paginator'
ApplyForBetaForm = require('./apply-for-beta').default
module.exports = createReactClass
displayName: 'EditProjectVisibility'
getDefaultProps: ->
project: null
getInitialState: ->
error: null
setting:
private: false
beta_requested: false
launch_requested: false
mixins: [SetToggle]
setterProperty: 'project'
setRadio: (property, value) ->
@set property, value
render: ->
looksDisabled =
opacity: 0.7
pointerEvents: 'none'
<div>
<p className="form-label">Project state and visibility</p>
{if @state.error
<p className="form-help error">{@state.error.toString()}</p>}
<p>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="private" value={true} data-json-value={true} checked={@props.project.private} disabled={@state.setting.private} onChange={@setRadio.bind this, 'private', true} />
Private
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="private" value={false} data-json-value={true} checked={not @props.project.private} disabled={@state.setting.private} onChange={@setRadio.bind this, 'private', false} />
Public
</label>
</p>
<p className="form-help">Only the assigned <strong>collaborators</strong> can view a private project. Anyone with the URL can access a public project.</p>
<hr/>
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="live" value={true} data-json-value={true} checked={not @props.project.live} disabled={@state.setting.live} onChange={@setRadio.bind this, 'live', false} />
Development
</label>
 
<label style={whiteSpace: 'nowrap'}>
<input type="radio" name="live" value={false} data-json-value={true} checked={@props.project.live} disabled={@state.setting.live} onChange={@setRadio.bind this, 'live', true} />
Live
</label>
<p className="form-help">
All workflows can be edited during development, and subjects will never retire.<br />
In a live project, active workflows are locked and can no longer be edited.<br />
<small>
<strong>
Take care changing a project to development as classifications will not count towards your project.
</strong>
</small>
</p>
<div>
<hr />
<p className="form-label">Beta status</p>
{if @props.project.beta_approved
<span>
<div className="approval-status">
<span>Beta Approval Status: </span>
<span className="color-label green">Approved</span>
</div>
<p>
Review status for this project has been approved. To end the review and make changes, switch back to <em>development</em> mode.
{unless @props.project.launch_requested or @props.project.launch_approved
<span>If you’re ready to launch this project, please email <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a> to submit your request.</span>}
</p>
</span>
else if @props.project.beta_requested
<div className="approval-status">
<span>Beta Approval Status: </span>
<span className="color-label orange">Pending</span>
</div>
<span>Review status has been applied for. <button type="button" disabled={@state.setting.beta_requested} onClick={@set.bind this, 'beta_requested', false}>Cancel application</button></span>
else
<ApplyForBetaForm project={@props.project} applyFn={@set.bind this, 'beta_requested', true} />
}
</div>
</div>
|
[
{
"context": "_bind: (el, key = '', options = {}) ->\n key = \"='#{key}'\" if key\n\n rules = {\n 'src': (node, value) ",
"end": 3259,
"score": 0.9655653238296509,
"start": 3251,
"tag": "KEY",
"value": "#{key}'\""
},
{
"context": " for event in lemon.browser_events\n ... | src/Component.coffee | lemon/lemonjs-browser | 0 |
# Component class
class lemon.Component
# default spec properties
_defaults: {
class: ''
computed: {}
contents: null
data: {}
lifecycle: {}
methods: {}
mounted: false
routes: {}
template: ->
watch: {}
}
constructor: (spec, data, contents) ->
# if being called without "new", in a template, render a dom stub
# which can be loaded after the current component is finished rendering
if not (this instanceof lemon.Component)
attrs = {}
for k, v of data
if k in ['id', 'class']
attrs[k] = v
if k in ['style', 'data', 'on', 'bind'] or k[0] in ['$', '_']
attrs[k] = v
delete data[k]
attrs['lemon-component'] = "#{spec.package}.#{spec.name}"
attrs['lemon-contents'] = contents if contents
attrs['lemon-data'] = data
tag (spec.element or 'div'), attrs
return
# spec
spec = Object.assign {}, @_defaults, spec
for k, v of spec
@["_#{k}"] = v
# lifecycle hook
@_hook 'beforeCreate'
# el, data, contents
@_data = Object.assign {}, spec.data, data
@_contents = contents or spec.contents or ->
@_id ?= @_data.id
@_class ?= @_data.class
@_uid = @_id or @_data.id or lemon.uid()
@_ref = @_data.ref
# expose el
Object.defineProperty this, 'el', {
get: ->
return @_el
}
# add to component map
lemon.Components[@_uid] = this
# default ref to uid
@_ref ?= @_uid
# dom modifications
# add uid, ref, id, class to dom
# is @el is document, setAttribute doesn't exist
if @el
@el.setAttribute? 'lemon-uid', @_uid
@el.setAttribute? 'lemon-ref', @_ref if @_ref
@el.setAttribute? 'id', @_id if @_id
lemon.addClass @el, @_class if @_class
# make methods easier to access
@[name] ?= fn.bind this for name, fn of @_methods
# container for child components
@_children = []
# container for refs
@_refs = {}
# event listeners
@_listeners = []
# add observers to watch for data changes
@_observe key for key of @_data
# computed fields
for key of @_computed
do (key) =>
self = this
# for use in event handlers
Object.defineProperty self, key, {
get: ->
self._apply self._computed[key]
}
# for us in template
Object.defineProperty @_data, key, {
get: ->
self._apply self._computed[key]
}
# lifecycle hook
@_hook 'created'
###
# PRIVATE METHODS
###
# add new event listener
_addEventListener: (el, event, handler) ->
[el, event, handler] = [@el, el, event] if not handler
for x in @_listeners when x[0] is el and x[1] is event
return
@_listeners.push [el, event, handler]
el.addEventListener event, handler
# call a function if it exists
_apply: (fn, args) ->
if typeof fn is 'string'
if @_methods[fn]
@_methods[fn].apply @, args
else
@_warn "#{fn} is not defined"
else if typeof fn is 'function'
fn.apply @, args
else
return true
# update the dom based on property bindings
_bind: (el, key = '', options = {}) ->
key = "='#{key}'" if key
rules = {
'src': (node, value) ->
node.setAttribute 'src', value
'href': (node, value) ->
node.setAttribute 'href', value
'text': (node, value) ->
node.textContent = "#{value}"
'html': (node, value) ->
node.innerHTML = "#{value}"
'on': (node, value, options) =>
node.innerHTML = ''
@_bindListRule node, [value], options
'list': @_bindListRule.bind this
}
for prop, fn of rules
attr = "lemon-bind:#{prop}"
for node in @_find el, "[#{attr.replace ':', '\\:'}#{key}]"
value = @[node.getAttribute attr]
fn node, value, options
# update arrays in the dom based on property bindings
_bindListRule: (node, items, options = {}) ->
{method, args} = options
temp = node.getAttribute "lemon-bind:template"
comp = node.getAttribute "lemon-bind:component"
fn = lemoncup._data[temp] or lemoncup._data[comp]
data = @_data
if temp
template = ({fn, item, data}) ->
div 'lemon-data': item, ->
fn item, data
else
template = ({fn, item, data}) ->
fn item, data
switch method
when 'pop'
if node.lastChild
node.removeChild node.lastChild
when 'push', undefined
node.innerHTML = null if not method
for item in args or items
el = @_render {
data: {fn, item, data}
el: node
method: 'append'
template: template
}
@_hydrate el
when 'reverse'
for el in node.children
node.insertBefore el, node.firstChild
when 'shift'
if node.firstChild
node.removeChild node.firstChild
when 'sort'
fn = args[0] or (a, b) -> if a < b then -1 else 1
children = (child for child in node.children)
children = children.sort (a, b) ->
value_a = lemoncup._data[a.getAttribute 'lemon-data']
value_b = lemoncup._data[b.getAttribute 'lemon-data']
return fn value_a, value_b
for child in children
node.appendChild child
when 'splice'
if args[0] is 0 and args.length is 1
node.innerHTML = ''
else
@_warn "splice not supported"
when 'unshift'
for item in args.reverse()
el = @_render {
data: {fn, item, data}
el: node
method: 'prepend'
template: template
}
@_hydrate el
# destroy this component
_destroy: ->
# lifecycle hook
@_hook 'beforeDestroy'
# cleanup router
lemon.off 'url_change', @_onUrlChange
# remove listeners
@_removeEventListeners()
# destroy children
for child in @_children
child._destroy()
# delete from component map
delete lemon.Components[@_uid]
# remove the element
@el.parentNode?.removeChild @el
# lifecycle hook
@_hook 'destroyed'
# find elements in my component, but not in child components
_find: (target, selector) ->
[target, selector] = [@el, target] if typeof target is 'string'
elements = target.querySelectorAll selector
mine = []
for el in elements
is_mine = true
parent = el.parentNode
while parent isnt target
if parent.getAttribute 'lemon-component'
is_mine = false
break
parent = parent.parentNode
mine.push el if is_mine
return mine
# call a lifecycle hook
_hook: (name) ->
@_apply @_lifecycle[name]
# hydrate a dom element
_hydrate: (el, opt={}) ->
el ?= @el
# event listeners
for event in lemon.browser_events
key = "lemon-on:#{event}"
nodes = @_find el, "[#{key.replace ':', '\\:'}]"
for node in nodes
do (node, event, key) =>
@addEventListener node, event, (e) =>
value = node.getAttribute key
fn = lemoncup._data[value] or @[value]
@_apply fn, [e]
# child components
for node in @_find el, "[lemon-component]"
component = lemon.loadElement node, opt
component._parent = this
if component
@_children.push component
# find references
for node in @_find el, "[lemon-ref]"
ref = node.getAttribute 'lemon-ref'
uid = node.getAttribute 'lemon-uid'
@_refs[ref] = if uid then lemon.get(uid) else node
@[ref] = @_refs[ref]
# property binding
@_bind el, null, opt
# intercept internal links
links = @_find el, "a[href^='/'],a[href^='?'],a[href^='#']"
for link in links
do (link) =>
@addEventListener link, 'click', (e) =>
e.preventDefault()
lemon.route link.getAttribute('href')
# mount component
_mount: (opt={}) ->
# defaults
opt.render ?= true
opt.render = true if @el.innerHTML is ''
# lifecycle hook
@_hook 'beforeMount'
# remove listeners
@_removeEventListeners()
# write to the dom
# render option allows us to render server-side and not re-render in the
# browser. some elements may not have been rendered server-side, so if
# innerHtml is empty, force a render
if opt.render
@_render {
el: @el
template: @_template
data: @_data
contents: @_contents
}
# hydrate result
@_hydrate @el, opt
# lifecycle hook
@_hook 'mounted'
# routing
@_startRouter()
# set mounted property
@_mounted = true
# add listeners for data property changes
_observe: (key) ->
Object.defineProperty this, key, {
get: ->
return @_data[key]
set: (value) ->
return if @_data[key] is value
@_data[key] = value
@_apply @_watch[key], [value]
@_bind @el, key
if Array.isArray value
@_observeArray key
}
if Array.isArray @_data[key]
@_observeArray key
# add listeners for data property changes (for arrays)
_observeArray: (key) ->
return if @_data[key]._observer
self = this
Object.defineProperty @_data[key], '_observer', {
enumerable: false
value: ({method, args}) ->
self._bind self.el, key, {method, args}
}
# remove all event listeners
_removeEventListeners: ->
for listener in @_listeners
[el, name, handler] = listener
el.removeEventListener name, handler
@_listeners = []
# render the template to the dom
_render: (options) ->
{el, method, template, data, contents} = options
# render html
html = lemoncup.render template, data, contents
# update dom
return lemon.updateDOMElement el, method, html
# start this component's router
_startRouter: ->
return if @_onUrlChange
return if (k for k of @_routes).length is 0
# define url_change handler
onUrlChange = ->
match = lemon.checkRoutes @_routes
if match
@_apply match.action, [match]
# bind context and add listener
@_onUrlChange = onUrlChange.bind this
lemon.on 'url_change', @_onUrlChange
@_onUrlChange()
# warning log
_warn: ->
console.warn "[#{@_package}.#{@_name}]", arguments...
###
# PUBLIC METHODS
###
addEventListener: -> @_addEventListener arguments...
find: -> @_find arguments...
findOne: -> @_find(arguments...)[0]
hydrate: -> @_hydrate arguments...
mount: -> @_mount arguments...
render: -> @_render arguments...
warn: -> @_warn arguments...
| 87959 |
# Component class
class lemon.Component
# default spec properties
_defaults: {
class: ''
computed: {}
contents: null
data: {}
lifecycle: {}
methods: {}
mounted: false
routes: {}
template: ->
watch: {}
}
constructor: (spec, data, contents) ->
# if being called without "new", in a template, render a dom stub
# which can be loaded after the current component is finished rendering
if not (this instanceof lemon.Component)
attrs = {}
for k, v of data
if k in ['id', 'class']
attrs[k] = v
if k in ['style', 'data', 'on', 'bind'] or k[0] in ['$', '_']
attrs[k] = v
delete data[k]
attrs['lemon-component'] = "#{spec.package}.#{spec.name}"
attrs['lemon-contents'] = contents if contents
attrs['lemon-data'] = data
tag (spec.element or 'div'), attrs
return
# spec
spec = Object.assign {}, @_defaults, spec
for k, v of spec
@["_#{k}"] = v
# lifecycle hook
@_hook 'beforeCreate'
# el, data, contents
@_data = Object.assign {}, spec.data, data
@_contents = contents or spec.contents or ->
@_id ?= @_data.id
@_class ?= @_data.class
@_uid = @_id or @_data.id or lemon.uid()
@_ref = @_data.ref
# expose el
Object.defineProperty this, 'el', {
get: ->
return @_el
}
# add to component map
lemon.Components[@_uid] = this
# default ref to uid
@_ref ?= @_uid
# dom modifications
# add uid, ref, id, class to dom
# is @el is document, setAttribute doesn't exist
if @el
@el.setAttribute? 'lemon-uid', @_uid
@el.setAttribute? 'lemon-ref', @_ref if @_ref
@el.setAttribute? 'id', @_id if @_id
lemon.addClass @el, @_class if @_class
# make methods easier to access
@[name] ?= fn.bind this for name, fn of @_methods
# container for child components
@_children = []
# container for refs
@_refs = {}
# event listeners
@_listeners = []
# add observers to watch for data changes
@_observe key for key of @_data
# computed fields
for key of @_computed
do (key) =>
self = this
# for use in event handlers
Object.defineProperty self, key, {
get: ->
self._apply self._computed[key]
}
# for us in template
Object.defineProperty @_data, key, {
get: ->
self._apply self._computed[key]
}
# lifecycle hook
@_hook 'created'
###
# PRIVATE METHODS
###
# add new event listener
_addEventListener: (el, event, handler) ->
[el, event, handler] = [@el, el, event] if not handler
for x in @_listeners when x[0] is el and x[1] is event
return
@_listeners.push [el, event, handler]
el.addEventListener event, handler
# call a function if it exists
_apply: (fn, args) ->
if typeof fn is 'string'
if @_methods[fn]
@_methods[fn].apply @, args
else
@_warn "#{fn} is not defined"
else if typeof fn is 'function'
fn.apply @, args
else
return true
# update the dom based on property bindings
_bind: (el, key = '', options = {}) ->
key = "='<KEY> if key
rules = {
'src': (node, value) ->
node.setAttribute 'src', value
'href': (node, value) ->
node.setAttribute 'href', value
'text': (node, value) ->
node.textContent = "#{value}"
'html': (node, value) ->
node.innerHTML = "#{value}"
'on': (node, value, options) =>
node.innerHTML = ''
@_bindListRule node, [value], options
'list': @_bindListRule.bind this
}
for prop, fn of rules
attr = "lemon-bind:#{prop}"
for node in @_find el, "[#{attr.replace ':', '\\:'}#{key}]"
value = @[node.getAttribute attr]
fn node, value, options
# update arrays in the dom based on property bindings
_bindListRule: (node, items, options = {}) ->
{method, args} = options
temp = node.getAttribute "lemon-bind:template"
comp = node.getAttribute "lemon-bind:component"
fn = lemoncup._data[temp] or lemoncup._data[comp]
data = @_data
if temp
template = ({fn, item, data}) ->
div 'lemon-data': item, ->
fn item, data
else
template = ({fn, item, data}) ->
fn item, data
switch method
when 'pop'
if node.lastChild
node.removeChild node.lastChild
when 'push', undefined
node.innerHTML = null if not method
for item in args or items
el = @_render {
data: {fn, item, data}
el: node
method: 'append'
template: template
}
@_hydrate el
when 'reverse'
for el in node.children
node.insertBefore el, node.firstChild
when 'shift'
if node.firstChild
node.removeChild node.firstChild
when 'sort'
fn = args[0] or (a, b) -> if a < b then -1 else 1
children = (child for child in node.children)
children = children.sort (a, b) ->
value_a = lemoncup._data[a.getAttribute 'lemon-data']
value_b = lemoncup._data[b.getAttribute 'lemon-data']
return fn value_a, value_b
for child in children
node.appendChild child
when 'splice'
if args[0] is 0 and args.length is 1
node.innerHTML = ''
else
@_warn "splice not supported"
when 'unshift'
for item in args.reverse()
el = @_render {
data: {fn, item, data}
el: node
method: 'prepend'
template: template
}
@_hydrate el
# destroy this component
_destroy: ->
# lifecycle hook
@_hook 'beforeDestroy'
# cleanup router
lemon.off 'url_change', @_onUrlChange
# remove listeners
@_removeEventListeners()
# destroy children
for child in @_children
child._destroy()
# delete from component map
delete lemon.Components[@_uid]
# remove the element
@el.parentNode?.removeChild @el
# lifecycle hook
@_hook 'destroyed'
# find elements in my component, but not in child components
_find: (target, selector) ->
[target, selector] = [@el, target] if typeof target is 'string'
elements = target.querySelectorAll selector
mine = []
for el in elements
is_mine = true
parent = el.parentNode
while parent isnt target
if parent.getAttribute 'lemon-component'
is_mine = false
break
parent = parent.parentNode
mine.push el if is_mine
return mine
# call a lifecycle hook
_hook: (name) ->
@_apply @_lifecycle[name]
# hydrate a dom element
_hydrate: (el, opt={}) ->
el ?= @el
# event listeners
for event in lemon.browser_events
key = "<KEY>
nodes = @_find el, "[#{key.replace ':', '\\:'}]"
for node in nodes
do (node, event, key) =>
@addEventListener node, event, (e) =>
value = node.getAttribute key
fn = lemoncup._data[value] or @[value]
@_apply fn, [e]
# child components
for node in @_find el, "[lemon-component]"
component = lemon.loadElement node, opt
component._parent = this
if component
@_children.push component
# find references
for node in @_find el, "[lemon-ref]"
ref = node.getAttribute 'lemon-ref'
uid = node.getAttribute 'lemon-uid'
@_refs[ref] = if uid then lemon.get(uid) else node
@[ref] = @_refs[ref]
# property binding
@_bind el, null, opt
# intercept internal links
links = @_find el, "a[href^='/'],a[href^='?'],a[href^='#']"
for link in links
do (link) =>
@addEventListener link, 'click', (e) =>
e.preventDefault()
lemon.route link.getAttribute('href')
# mount component
_mount: (opt={}) ->
# defaults
opt.render ?= true
opt.render = true if @el.innerHTML is ''
# lifecycle hook
@_hook 'beforeMount'
# remove listeners
@_removeEventListeners()
# write to the dom
# render option allows us to render server-side and not re-render in the
# browser. some elements may not have been rendered server-side, so if
# innerHtml is empty, force a render
if opt.render
@_render {
el: @el
template: @_template
data: @_data
contents: @_contents
}
# hydrate result
@_hydrate @el, opt
# lifecycle hook
@_hook 'mounted'
# routing
@_startRouter()
# set mounted property
@_mounted = true
# add listeners for data property changes
_observe: (key) ->
Object.defineProperty this, key, {
get: ->
return @_data[key]
set: (value) ->
return if @_data[key] is value
@_data[key] = value
@_apply @_watch[key], [value]
@_bind @el, key
if Array.isArray value
@_observeArray key
}
if Array.isArray @_data[key]
@_observeArray key
# add listeners for data property changes (for arrays)
_observeArray: (key) ->
return if @_data[key]._observer
self = this
Object.defineProperty @_data[key], '_observer', {
enumerable: false
value: ({method, args}) ->
self._bind self.el, key, {method, args}
}
# remove all event listeners
_removeEventListeners: ->
for listener in @_listeners
[el, name, handler] = listener
el.removeEventListener name, handler
@_listeners = []
# render the template to the dom
_render: (options) ->
{el, method, template, data, contents} = options
# render html
html = lemoncup.render template, data, contents
# update dom
return lemon.updateDOMElement el, method, html
# start this component's router
_startRouter: ->
return if @_onUrlChange
return if (k for k of @_routes).length is 0
# define url_change handler
onUrlChange = ->
match = lemon.checkRoutes @_routes
if match
@_apply match.action, [match]
# bind context and add listener
@_onUrlChange = onUrlChange.bind this
lemon.on 'url_change', @_onUrlChange
@_onUrlChange()
# warning log
_warn: ->
console.warn "[#{@_package}.#{@_name}]", arguments...
###
# PUBLIC METHODS
###
addEventListener: -> @_addEventListener arguments...
find: -> @_find arguments...
findOne: -> @_find(arguments...)[0]
hydrate: -> @_hydrate arguments...
mount: -> @_mount arguments...
render: -> @_render arguments...
warn: -> @_warn arguments...
| true |
# Component class
class lemon.Component
# default spec properties
_defaults: {
class: ''
computed: {}
contents: null
data: {}
lifecycle: {}
methods: {}
mounted: false
routes: {}
template: ->
watch: {}
}
constructor: (spec, data, contents) ->
# if being called without "new", in a template, render a dom stub
# which can be loaded after the current component is finished rendering
if not (this instanceof lemon.Component)
attrs = {}
for k, v of data
if k in ['id', 'class']
attrs[k] = v
if k in ['style', 'data', 'on', 'bind'] or k[0] in ['$', '_']
attrs[k] = v
delete data[k]
attrs['lemon-component'] = "#{spec.package}.#{spec.name}"
attrs['lemon-contents'] = contents if contents
attrs['lemon-data'] = data
tag (spec.element or 'div'), attrs
return
# spec
spec = Object.assign {}, @_defaults, spec
for k, v of spec
@["_#{k}"] = v
# lifecycle hook
@_hook 'beforeCreate'
# el, data, contents
@_data = Object.assign {}, spec.data, data
@_contents = contents or spec.contents or ->
@_id ?= @_data.id
@_class ?= @_data.class
@_uid = @_id or @_data.id or lemon.uid()
@_ref = @_data.ref
# expose el
Object.defineProperty this, 'el', {
get: ->
return @_el
}
# add to component map
lemon.Components[@_uid] = this
# default ref to uid
@_ref ?= @_uid
# dom modifications
# add uid, ref, id, class to dom
# is @el is document, setAttribute doesn't exist
if @el
@el.setAttribute? 'lemon-uid', @_uid
@el.setAttribute? 'lemon-ref', @_ref if @_ref
@el.setAttribute? 'id', @_id if @_id
lemon.addClass @el, @_class if @_class
# make methods easier to access
@[name] ?= fn.bind this for name, fn of @_methods
# container for child components
@_children = []
# container for refs
@_refs = {}
# event listeners
@_listeners = []
# add observers to watch for data changes
@_observe key for key of @_data
# computed fields
for key of @_computed
do (key) =>
self = this
# for use in event handlers
Object.defineProperty self, key, {
get: ->
self._apply self._computed[key]
}
# for us in template
Object.defineProperty @_data, key, {
get: ->
self._apply self._computed[key]
}
# lifecycle hook
@_hook 'created'
###
# PRIVATE METHODS
###
# add new event listener
_addEventListener: (el, event, handler) ->
[el, event, handler] = [@el, el, event] if not handler
for x in @_listeners when x[0] is el and x[1] is event
return
@_listeners.push [el, event, handler]
el.addEventListener event, handler
# call a function if it exists
_apply: (fn, args) ->
if typeof fn is 'string'
if @_methods[fn]
@_methods[fn].apply @, args
else
@_warn "#{fn} is not defined"
else if typeof fn is 'function'
fn.apply @, args
else
return true
# update the dom based on property bindings
_bind: (el, key = '', options = {}) ->
key = "='PI:KEY:<KEY>END_PI if key
rules = {
'src': (node, value) ->
node.setAttribute 'src', value
'href': (node, value) ->
node.setAttribute 'href', value
'text': (node, value) ->
node.textContent = "#{value}"
'html': (node, value) ->
node.innerHTML = "#{value}"
'on': (node, value, options) =>
node.innerHTML = ''
@_bindListRule node, [value], options
'list': @_bindListRule.bind this
}
for prop, fn of rules
attr = "lemon-bind:#{prop}"
for node in @_find el, "[#{attr.replace ':', '\\:'}#{key}]"
value = @[node.getAttribute attr]
fn node, value, options
# update arrays in the dom based on property bindings
_bindListRule: (node, items, options = {}) ->
{method, args} = options
temp = node.getAttribute "lemon-bind:template"
comp = node.getAttribute "lemon-bind:component"
fn = lemoncup._data[temp] or lemoncup._data[comp]
data = @_data
if temp
template = ({fn, item, data}) ->
div 'lemon-data': item, ->
fn item, data
else
template = ({fn, item, data}) ->
fn item, data
switch method
when 'pop'
if node.lastChild
node.removeChild node.lastChild
when 'push', undefined
node.innerHTML = null if not method
for item in args or items
el = @_render {
data: {fn, item, data}
el: node
method: 'append'
template: template
}
@_hydrate el
when 'reverse'
for el in node.children
node.insertBefore el, node.firstChild
when 'shift'
if node.firstChild
node.removeChild node.firstChild
when 'sort'
fn = args[0] or (a, b) -> if a < b then -1 else 1
children = (child for child in node.children)
children = children.sort (a, b) ->
value_a = lemoncup._data[a.getAttribute 'lemon-data']
value_b = lemoncup._data[b.getAttribute 'lemon-data']
return fn value_a, value_b
for child in children
node.appendChild child
when 'splice'
if args[0] is 0 and args.length is 1
node.innerHTML = ''
else
@_warn "splice not supported"
when 'unshift'
for item in args.reverse()
el = @_render {
data: {fn, item, data}
el: node
method: 'prepend'
template: template
}
@_hydrate el
# destroy this component
_destroy: ->
# lifecycle hook
@_hook 'beforeDestroy'
# cleanup router
lemon.off 'url_change', @_onUrlChange
# remove listeners
@_removeEventListeners()
# destroy children
for child in @_children
child._destroy()
# delete from component map
delete lemon.Components[@_uid]
# remove the element
@el.parentNode?.removeChild @el
# lifecycle hook
@_hook 'destroyed'
# find elements in my component, but not in child components
_find: (target, selector) ->
[target, selector] = [@el, target] if typeof target is 'string'
elements = target.querySelectorAll selector
mine = []
for el in elements
is_mine = true
parent = el.parentNode
while parent isnt target
if parent.getAttribute 'lemon-component'
is_mine = false
break
parent = parent.parentNode
mine.push el if is_mine
return mine
# call a lifecycle hook
_hook: (name) ->
@_apply @_lifecycle[name]
# hydrate a dom element
_hydrate: (el, opt={}) ->
el ?= @el
# event listeners
for event in lemon.browser_events
key = "PI:KEY:<KEY>END_PI
nodes = @_find el, "[#{key.replace ':', '\\:'}]"
for node in nodes
do (node, event, key) =>
@addEventListener node, event, (e) =>
value = node.getAttribute key
fn = lemoncup._data[value] or @[value]
@_apply fn, [e]
# child components
for node in @_find el, "[lemon-component]"
component = lemon.loadElement node, opt
component._parent = this
if component
@_children.push component
# find references
for node in @_find el, "[lemon-ref]"
ref = node.getAttribute 'lemon-ref'
uid = node.getAttribute 'lemon-uid'
@_refs[ref] = if uid then lemon.get(uid) else node
@[ref] = @_refs[ref]
# property binding
@_bind el, null, opt
# intercept internal links
links = @_find el, "a[href^='/'],a[href^='?'],a[href^='#']"
for link in links
do (link) =>
@addEventListener link, 'click', (e) =>
e.preventDefault()
lemon.route link.getAttribute('href')
# mount component
_mount: (opt={}) ->
# defaults
opt.render ?= true
opt.render = true if @el.innerHTML is ''
# lifecycle hook
@_hook 'beforeMount'
# remove listeners
@_removeEventListeners()
# write to the dom
# render option allows us to render server-side and not re-render in the
# browser. some elements may not have been rendered server-side, so if
# innerHtml is empty, force a render
if opt.render
@_render {
el: @el
template: @_template
data: @_data
contents: @_contents
}
# hydrate result
@_hydrate @el, opt
# lifecycle hook
@_hook 'mounted'
# routing
@_startRouter()
# set mounted property
@_mounted = true
# add listeners for data property changes
_observe: (key) ->
Object.defineProperty this, key, {
get: ->
return @_data[key]
set: (value) ->
return if @_data[key] is value
@_data[key] = value
@_apply @_watch[key], [value]
@_bind @el, key
if Array.isArray value
@_observeArray key
}
if Array.isArray @_data[key]
@_observeArray key
# add listeners for data property changes (for arrays)
_observeArray: (key) ->
return if @_data[key]._observer
self = this
Object.defineProperty @_data[key], '_observer', {
enumerable: false
value: ({method, args}) ->
self._bind self.el, key, {method, args}
}
# remove all event listeners
_removeEventListeners: ->
for listener in @_listeners
[el, name, handler] = listener
el.removeEventListener name, handler
@_listeners = []
# render the template to the dom
_render: (options) ->
{el, method, template, data, contents} = options
# render html
html = lemoncup.render template, data, contents
# update dom
return lemon.updateDOMElement el, method, html
# start this component's router
_startRouter: ->
return if @_onUrlChange
return if (k for k of @_routes).length is 0
# define url_change handler
onUrlChange = ->
match = lemon.checkRoutes @_routes
if match
@_apply match.action, [match]
# bind context and add listener
@_onUrlChange = onUrlChange.bind this
lemon.on 'url_change', @_onUrlChange
@_onUrlChange()
# warning log
_warn: ->
console.warn "[#{@_package}.#{@_name}]", arguments...
###
# PUBLIC METHODS
###
addEventListener: -> @_addEventListener arguments...
find: -> @_find arguments...
findOne: -> @_find(arguments...)[0]
hydrate: -> @_hydrate arguments...
mount: -> @_mount arguments...
render: -> @_render arguments...
warn: -> @_warn arguments...
|
[
{
"context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#",
"end": 166,
"score": 0.9855328798294067,
"start": 152,
"tag": "USERNAME",
"value": "programmfabrik"
},
{
"context": "\n\t\tswitch direction\n\t\t\twhe... | src/base/Layout/Layout.coffee | programmfabrik/coffeescript-ui | 10 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# {Layout} is used for all layout related stuff, like {HorizontalLayout},
# {VerticalLayout}, {BorderLayout}, {Toolbar}, {Pane}, etc.
#
# It features an automatic {Buttonbar} generation for all panes (see {Layout#append})
class CUI.Layout extends CUI.DOMElement
#Construct a new Layout.
#
# @param [Object] options for layout creation
# @option options [String] maximize the center so that it pushes top pane to top and bottom pane to the bottom of the parent element
# @option options [Object] pane name of the pane on its options, check {Layout.initPane} for the options.
# TODO document other options
# TODO create a Pane Class
constructor: (opts) ->
super(opts)
@__isInit = false
@init()
initOpts: ->
super()
@addOpts
absolute:
check: Boolean
maximize:
check: Boolean
maximize_horizontal:
check: Boolean
maximize_vertical:
check: Boolean
auto_buttonbar:
default: true
mandatory: true
check: Boolean
center:
default: {}
check: "PlainObject"
for pn in @getSupportedPanes()
@addOpt(pn,
check: (v) ->
CUI.util.isPlainObject(v) or v == false
)
readOpts: ->
# DEBUG
# without absolute "help", FF and Safari perform badly, Chrome & IE (Edge) are fine
@initDefaultPanes()
super()
@maximizeReadOpts()
if @_absolute
CUI.util.assert(@__maximize, "new "+@__cls, "opts.absolute needs opts.maximize to be set.", opts: @opts)
@
maximizeAddClasses: ->
if @__maximize
@addClass("cui-maximize")
if @__maximize_horizontal
@addClass("cui-maximize-horizontal")
if @__maximize_vertical
@addClass("cui-maximize-vertical")
@
maximizeReadOpts: ->
if CUI.util.isNull(@_maximize) and
CUI.util.isNull(@_maximize_horizontal) and
CUI.util.isNull(@_maximize_vertical)
@_maximize = true
if @_maximize
CUI.util.assert(not @_maximize_horizontal and not @_maximize_vertical, "new "+CUI.util.getObjectClass(@), "opts.maximize cannot be set together with opts.maximize_horizontal or opts.maximize_vertical", opts: @opts)
@__maximize_horizontal = true
@__maximize_vertical = true
else
if @_maximize_horizontal
@__maximize_horizontal = true
if @_maximize_vertical
@__maximize_vertical = true
if @__maximize_vertical and @__maximize_horizontal
@__maximize = true
@
init: ->
@__init()
getTemplateMap: ->
map = {}
for pn in @__panes
map[pn] = true
map
__init: ->
CUI.util.assert(not(@_maximize == false and @_absolute == true), "Layout.__init", "opts.maximize == false and opts.absolute == true is not allowed.", opts: @opts)
@__panes = @getPanes()
@__panes.push("center")
@__name = @getName()
@__layout = new CUI.Template
name: @__name
map_prefix: @getMapPrefix()
map: @getTemplateMap()
@registerTemplate(@__layout)
# if @__maximize_horizontal and @__maximize_vertical
# CUI.Events.listen
# type: "content-resize"
# instance: @
# node: @DOM
# call: (ev) =>
# console.debug "context-resizse stopped"
# if CUI.dom.closest(ev.getTarget(), '.cui-absolute')
# # no stopping inside absolute layouts
# return
# ev.stopPropagation()
@maximizeAddClasses()
@addClass(@getMapPrefix())
if @_absolute
@addClass("cui-absolute")
CUI.util.assert(CUI.dom.getAttribute(@DOM, "data-cui-absolute-container") in ["row","column"], "new CUI.Layout", "opts.absolute: template must include a cui-absolute-container attribute set to \"row\" or \"column\".")
CUI.dom.waitForDOMInsert(node: @DOM)
.done =>
# console.debug "Layout[absolute] inserted", @__uniqueId
CUI.Layout.all()
# _call = (event) =>
# console.error "Layout.setAbsolute[#{event.getDebug()}]:", @DOM[0]
# # console.error "Layout[viewport-resize] received", @DOM[0]
# #
# event.stopPropagation()
# Layout.setAbsolute(@DOM)
# CUI.Events.listen
# type: "viewport-resize"
# node: @DOM
# instance: @
# call: _call
# CUI.Events.listen
# type: "content-resize"
# node: @DOM
# instance: @
# call: _call
else
CUI.dom.removeAttribute(@DOM, "data-cui-absolute-container")
for child in @DOM.children
CUI.dom.removeAttribute(child, "data-cui-absolute-set")
@__buttonbars = {}
if @hasFlexHandles()
has_flex_handles = true
# console.warn(CUI.util.getObjectClass(@)+".initFlexHandles", @opts, @__layout.__uniqueId, @DOM[0])
pane_opts = {}
for pn in @__panes
pane = @["_#{pn}"]
if pane?.flexHandle
pane_opts[pn] = pane.flexHandle
@__layout.initFlexHandles(pane_opts)
else
has_flex_handles = false
# every pane gets a method "<pane>: ->" to retrieve
# the DOM element from the template
for pn in @__panes
do (pn) =>
@[pn] = =>
CUI.util.assert(@["_#{pn}"], "#{@__cls}.#{pn}", "Pane \"#{pn}\" not initialized.", opts: @opts)
CUI.util.assert(not @__layout.isDestroyed(), "Layout already destroyed, cannot get pane \"#{pn}\".")
@__layout.map[pn]
pane = @["_#{pn}"]
if pane
@__initPane(pane, pn)
if has_flex_handles and pn != "center" and not pane.flexHandle
@__layout.getFlexHandle(pn).destroy()
else
# console.debug(CUI.util.getObjectClass(@), "removing uninitialized pane", pn, @)
CUI.dom.remove(@__layout.map[pn])
if has_flex_handles
@__layout.getFlexHandle(pn).destroy()
@__isInit = true
destroy: ->
CUI.Events.ignore(instance: @)
super()
getMapPrefix: ->
undefined
#initialive pane option
__initPane: (options, pane_name) ->
CUI.util.assert(pane_name, "Layout.initPane", "pane_name must be set", options: options, pane_name: pane_name)
opts = CUI.Element.readOpts(options, "new CUI.Layout.__initPane",
class:
check: String
ui:
check: String
content: {}
flexHandle: {}
)
@append(opts.content, pane_name)
if opts.class
@__layout.addClass(opts.class, pane_name)
if opts.ui
CUI.dom.setAttribute(@__layout.get(pane_name), "ui", opts.ui)
return
# returns true if this Layout has at least one
# flexHandle
hasFlexHandles: ->
true
# init default panes, so that they are in markup
initDefaultPanes: ->
for pn in @getPanes()
if not @opts.hasOwnProperty(pn)
@opts[pn] = {}
@
getPanes: ->
CUI.util.assert(false, "#{@__cls}.getPanes", "Needs implementation")
getSupportedPanes: ->
CUI.util.assert(false, "#{@__cls}.getSupportedPanes", "Needs implementation")
getLayout: ->
@__layout
getButtonbar: (key) ->
if not @__buttonbars[key]
@__buttonbars[key] = new CUI.Buttonbar()
# console.info("#{@__cls}: automatically generated Buttonbar for #{key}.")
CUI.DOMElement::append.call(@, @__buttonbars[key], key)
@__buttonbars[key]
__callAutoButtonbar: (value, key) ->
if CUI.util.isFunction(value)
value = value(@)
get_value = (v) ->
if CUI.util.isPlainObject(v)
return new CUI.defaults.class.Button(v)
else
return v
value = get_value(value)
if CUI.util.isArray(value)
for _v in value
v = get_value(_v)
if v instanceof CUI.Button
@getButtonbar(key).addButton(v)
else
CUI.DOMElement::append.call(@, _v, key)
else if value instanceof CUI.Button
@getButtonbar(key).addButton(value)
else
return CUI.DOMElement::append.call(@, value, key)
# @param [jQuery, Function, Array, ...] value the value to append to the layer
# @param [String] key the name of the pane
# @param [Boolean] auto_buttonbar if set to true (default), automatically generate a {Buttonbar} for Buttons passed directly, in an Array or thru a Function
#
# @return [jQuery] the DOM node (created and) appended
append: (value, key, auto_buttonbar = @_auto_buttonbar) ->
if auto_buttonbar
return @__callAutoButtonbar(value, key)
else
return super(value, key)
replace: (value, key, auto_buttonbar = @_auto_buttonbar) ->
if auto_buttonbar
delete(@__buttonbars[key])
@empty(key)
return @__callAutoButtonbar(value, key)
else
return super(value, key)
setAbsolute: ->
@addClass("cui-absolute")
CUI.Layout.__all()
unsetAbsolute: ->
@DOM.removeAttribute("data-cui-absolute-check-value")
@DOM.removeAttribute("data-cui-absolute-values")
for child in CUI.dom.children(@DOM)
CUI.dom.setStyle child,
top: ""
left: ""
right: ""
bottom: ""
@removeClass("cui-absolute")
@
getName: ->
CUI.util.assert(false, "#{@__cls}.getName", "Needs to be overwritten.")
@setAbsolute: (layout) ->
# console.error "Layout.setAbsolute", layout[0]
CUI.util.assert(CUI.util.isElement(layout), "Layout.setAbsolute", "layout needs to be HTMLElement", layout: layout)
direction = CUI.dom.getAttribute(layout, "data-cui-absolute-container")
switch direction
when "row"
rect_key = "marginBoxWidth"
rect_check_key = "marginBoxHeight"
when "column"
rect_key = "marginBoxHeight"
rect_check_key = "marginBoxWidth"
else
CUI.util.assert(false, "Layout.setAbsolute", "cui-absolute-container is not set for .cui-absolute container or not set to row or column.", container: layout, direction: direction)
# measure all children
values = []
children = CUI.dom.children(layout)
for child, idx in children
values[idx] = CUI.dom.getDimensions(child)[rect_key]
abs_values = values.join(",")
check_value = CUI.dom.getDimensions(layout)[rect_check_key]+""
# console.debug layout, abs_values, CUI.dom.getAttribute(layout, "data-cui-absolute-values")
# console.debug layout, check_value, CUI.dom.getAttribute(layout, "data-cui-absolute-check-value")
if CUI.dom.getAttribute(layout, "data-cui-absolute-values") == abs_values and
CUI.dom.getAttribute(layout, "data-cui-absolute-check-value") == check_value
# nothing to do
return false
if CUI.dom.getAttribute(layout, "data-cui-absolute-check-value") != check_value
CUI.dom.setAttribute(layout, "data-cui-absolute-check-value", check_value)
if CUI.dom.getAttribute(layout, "data-cui-absolute-values") != abs_values
CUI.dom.setAttribute(layout, "data-cui-absolute-values", abs_values)
# console.debug(txt, values)
for child, idx in children
set = CUI.dom.getAttribute(child, "data-cui-absolute-set")
if not set
continue
css = {}
for key in set.split(",")
switch key
when "left", "top"
# this is left hand
if idx > 0
value = values.slice(0, idx).reduce((a,b) -> a+b)
else
value = 0
when "right", "bottom"
if idx + 1 < values.length
value = values.slice(idx+1).reduce((a,b) -> a+b)
else
value = 0
else
CUI.util.assert(false, "Layout.setAbsolute: Unknown key #{key} in data-cui-absolute-set.")
# console.debug idx, key, value
css[key] = value
CUI.dom.setStyle(child, css)
# CUI.Events.trigger
# type: "viewport-resize"
# exclude_self: true
# node: layout
return true
@__all: ->
layouts = []
changed = 0
for layout, idx in CUI.dom.matchSelector(document.documentElement, ".cui-absolute")
if CUI.Layout.setAbsolute(layout)
changed++
if changed > 0
# console.info("Layout.setAbsolute[all]: changed: ", changed)
# console.debug "triggering viewport resize"
CUI.Events.trigger(type: "viewport-resize")
@
@all: ->
CUI.scheduleCallback(call: CUI.Layout.__all)
CUI.ready ->
CUI.Events.listen
type: ["viewport-resize", "content-resize"]
call: (ev, info) ->
if info.FlexHandle
CUI.Layout.__all()
else
CUI.Layout.all()
| 13454 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# {Layout} is used for all layout related stuff, like {HorizontalLayout},
# {VerticalLayout}, {BorderLayout}, {Toolbar}, {Pane}, etc.
#
# It features an automatic {Buttonbar} generation for all panes (see {Layout#append})
class CUI.Layout extends CUI.DOMElement
#Construct a new Layout.
#
# @param [Object] options for layout creation
# @option options [String] maximize the center so that it pushes top pane to top and bottom pane to the bottom of the parent element
# @option options [Object] pane name of the pane on its options, check {Layout.initPane} for the options.
# TODO document other options
# TODO create a Pane Class
constructor: (opts) ->
super(opts)
@__isInit = false
@init()
initOpts: ->
super()
@addOpts
absolute:
check: Boolean
maximize:
check: Boolean
maximize_horizontal:
check: Boolean
maximize_vertical:
check: Boolean
auto_buttonbar:
default: true
mandatory: true
check: Boolean
center:
default: {}
check: "PlainObject"
for pn in @getSupportedPanes()
@addOpt(pn,
check: (v) ->
CUI.util.isPlainObject(v) or v == false
)
readOpts: ->
# DEBUG
# without absolute "help", FF and Safari perform badly, Chrome & IE (Edge) are fine
@initDefaultPanes()
super()
@maximizeReadOpts()
if @_absolute
CUI.util.assert(@__maximize, "new "+@__cls, "opts.absolute needs opts.maximize to be set.", opts: @opts)
@
maximizeAddClasses: ->
if @__maximize
@addClass("cui-maximize")
if @__maximize_horizontal
@addClass("cui-maximize-horizontal")
if @__maximize_vertical
@addClass("cui-maximize-vertical")
@
maximizeReadOpts: ->
if CUI.util.isNull(@_maximize) and
CUI.util.isNull(@_maximize_horizontal) and
CUI.util.isNull(@_maximize_vertical)
@_maximize = true
if @_maximize
CUI.util.assert(not @_maximize_horizontal and not @_maximize_vertical, "new "+CUI.util.getObjectClass(@), "opts.maximize cannot be set together with opts.maximize_horizontal or opts.maximize_vertical", opts: @opts)
@__maximize_horizontal = true
@__maximize_vertical = true
else
if @_maximize_horizontal
@__maximize_horizontal = true
if @_maximize_vertical
@__maximize_vertical = true
if @__maximize_vertical and @__maximize_horizontal
@__maximize = true
@
init: ->
@__init()
getTemplateMap: ->
map = {}
for pn in @__panes
map[pn] = true
map
__init: ->
CUI.util.assert(not(@_maximize == false and @_absolute == true), "Layout.__init", "opts.maximize == false and opts.absolute == true is not allowed.", opts: @opts)
@__panes = @getPanes()
@__panes.push("center")
@__name = @getName()
@__layout = new CUI.Template
name: @__name
map_prefix: @getMapPrefix()
map: @getTemplateMap()
@registerTemplate(@__layout)
# if @__maximize_horizontal and @__maximize_vertical
# CUI.Events.listen
# type: "content-resize"
# instance: @
# node: @DOM
# call: (ev) =>
# console.debug "context-resizse stopped"
# if CUI.dom.closest(ev.getTarget(), '.cui-absolute')
# # no stopping inside absolute layouts
# return
# ev.stopPropagation()
@maximizeAddClasses()
@addClass(@getMapPrefix())
if @_absolute
@addClass("cui-absolute")
CUI.util.assert(CUI.dom.getAttribute(@DOM, "data-cui-absolute-container") in ["row","column"], "new CUI.Layout", "opts.absolute: template must include a cui-absolute-container attribute set to \"row\" or \"column\".")
CUI.dom.waitForDOMInsert(node: @DOM)
.done =>
# console.debug "Layout[absolute] inserted", @__uniqueId
CUI.Layout.all()
# _call = (event) =>
# console.error "Layout.setAbsolute[#{event.getDebug()}]:", @DOM[0]
# # console.error "Layout[viewport-resize] received", @DOM[0]
# #
# event.stopPropagation()
# Layout.setAbsolute(@DOM)
# CUI.Events.listen
# type: "viewport-resize"
# node: @DOM
# instance: @
# call: _call
# CUI.Events.listen
# type: "content-resize"
# node: @DOM
# instance: @
# call: _call
else
CUI.dom.removeAttribute(@DOM, "data-cui-absolute-container")
for child in @DOM.children
CUI.dom.removeAttribute(child, "data-cui-absolute-set")
@__buttonbars = {}
if @hasFlexHandles()
has_flex_handles = true
# console.warn(CUI.util.getObjectClass(@)+".initFlexHandles", @opts, @__layout.__uniqueId, @DOM[0])
pane_opts = {}
for pn in @__panes
pane = @["_#{pn}"]
if pane?.flexHandle
pane_opts[pn] = pane.flexHandle
@__layout.initFlexHandles(pane_opts)
else
has_flex_handles = false
# every pane gets a method "<pane>: ->" to retrieve
# the DOM element from the template
for pn in @__panes
do (pn) =>
@[pn] = =>
CUI.util.assert(@["_#{pn}"], "#{@__cls}.#{pn}", "Pane \"#{pn}\" not initialized.", opts: @opts)
CUI.util.assert(not @__layout.isDestroyed(), "Layout already destroyed, cannot get pane \"#{pn}\".")
@__layout.map[pn]
pane = @["_#{pn}"]
if pane
@__initPane(pane, pn)
if has_flex_handles and pn != "center" and not pane.flexHandle
@__layout.getFlexHandle(pn).destroy()
else
# console.debug(CUI.util.getObjectClass(@), "removing uninitialized pane", pn, @)
CUI.dom.remove(@__layout.map[pn])
if has_flex_handles
@__layout.getFlexHandle(pn).destroy()
@__isInit = true
destroy: ->
CUI.Events.ignore(instance: @)
super()
getMapPrefix: ->
undefined
#initialive pane option
__initPane: (options, pane_name) ->
CUI.util.assert(pane_name, "Layout.initPane", "pane_name must be set", options: options, pane_name: pane_name)
opts = CUI.Element.readOpts(options, "new CUI.Layout.__initPane",
class:
check: String
ui:
check: String
content: {}
flexHandle: {}
)
@append(opts.content, pane_name)
if opts.class
@__layout.addClass(opts.class, pane_name)
if opts.ui
CUI.dom.setAttribute(@__layout.get(pane_name), "ui", opts.ui)
return
# returns true if this Layout has at least one
# flexHandle
hasFlexHandles: ->
true
# init default panes, so that they are in markup
initDefaultPanes: ->
for pn in @getPanes()
if not @opts.hasOwnProperty(pn)
@opts[pn] = {}
@
getPanes: ->
CUI.util.assert(false, "#{@__cls}.getPanes", "Needs implementation")
getSupportedPanes: ->
CUI.util.assert(false, "#{@__cls}.getSupportedPanes", "Needs implementation")
getLayout: ->
@__layout
getButtonbar: (key) ->
if not @__buttonbars[key]
@__buttonbars[key] = new CUI.Buttonbar()
# console.info("#{@__cls}: automatically generated Buttonbar for #{key}.")
CUI.DOMElement::append.call(@, @__buttonbars[key], key)
@__buttonbars[key]
__callAutoButtonbar: (value, key) ->
if CUI.util.isFunction(value)
value = value(@)
get_value = (v) ->
if CUI.util.isPlainObject(v)
return new CUI.defaults.class.Button(v)
else
return v
value = get_value(value)
if CUI.util.isArray(value)
for _v in value
v = get_value(_v)
if v instanceof CUI.Button
@getButtonbar(key).addButton(v)
else
CUI.DOMElement::append.call(@, _v, key)
else if value instanceof CUI.Button
@getButtonbar(key).addButton(value)
else
return CUI.DOMElement::append.call(@, value, key)
# @param [jQuery, Function, Array, ...] value the value to append to the layer
# @param [String] key the name of the pane
# @param [Boolean] auto_buttonbar if set to true (default), automatically generate a {Buttonbar} for Buttons passed directly, in an Array or thru a Function
#
# @return [jQuery] the DOM node (created and) appended
append: (value, key, auto_buttonbar = @_auto_buttonbar) ->
if auto_buttonbar
return @__callAutoButtonbar(value, key)
else
return super(value, key)
replace: (value, key, auto_buttonbar = @_auto_buttonbar) ->
if auto_buttonbar
delete(@__buttonbars[key])
@empty(key)
return @__callAutoButtonbar(value, key)
else
return super(value, key)
setAbsolute: ->
@addClass("cui-absolute")
CUI.Layout.__all()
unsetAbsolute: ->
@DOM.removeAttribute("data-cui-absolute-check-value")
@DOM.removeAttribute("data-cui-absolute-values")
for child in CUI.dom.children(@DOM)
CUI.dom.setStyle child,
top: ""
left: ""
right: ""
bottom: ""
@removeClass("cui-absolute")
@
getName: ->
CUI.util.assert(false, "#{@__cls}.getName", "Needs to be overwritten.")
@setAbsolute: (layout) ->
# console.error "Layout.setAbsolute", layout[0]
CUI.util.assert(CUI.util.isElement(layout), "Layout.setAbsolute", "layout needs to be HTMLElement", layout: layout)
direction = CUI.dom.getAttribute(layout, "data-cui-absolute-container")
switch direction
when "row"
rect_key = "<KEY>"
rect_check_key = "<KEY>"
when "column"
rect_key = "<KEY>"
rect_check_key = "<KEY>"
else
CUI.util.assert(false, "Layout.setAbsolute", "cui-absolute-container is not set for .cui-absolute container or not set to row or column.", container: layout, direction: direction)
# measure all children
values = []
children = CUI.dom.children(layout)
for child, idx in children
values[idx] = CUI.dom.getDimensions(child)[rect_key]
abs_values = values.join(",")
check_value = CUI.dom.getDimensions(layout)[rect_check_key]+""
# console.debug layout, abs_values, CUI.dom.getAttribute(layout, "data-cui-absolute-values")
# console.debug layout, check_value, CUI.dom.getAttribute(layout, "data-cui-absolute-check-value")
if CUI.dom.getAttribute(layout, "data-cui-absolute-values") == abs_values and
CUI.dom.getAttribute(layout, "data-cui-absolute-check-value") == check_value
# nothing to do
return false
if CUI.dom.getAttribute(layout, "data-cui-absolute-check-value") != check_value
CUI.dom.setAttribute(layout, "data-cui-absolute-check-value", check_value)
if CUI.dom.getAttribute(layout, "data-cui-absolute-values") != abs_values
CUI.dom.setAttribute(layout, "data-cui-absolute-values", abs_values)
# console.debug(txt, values)
for child, idx in children
set = CUI.dom.getAttribute(child, "data-cui-absolute-set")
if not set
continue
css = {}
for key in set.split(",")
switch key
when "left", "top"
# this is left hand
if idx > 0
value = values.slice(0, idx).reduce((a,b) -> a+b)
else
value = 0
when "right", "bottom"
if idx + 1 < values.length
value = values.slice(idx+1).reduce((a,b) -> a+b)
else
value = 0
else
CUI.util.assert(false, "Layout.setAbsolute: Unknown key #{key} in data-cui-absolute-set.")
# console.debug idx, key, value
css[key] = value
CUI.dom.setStyle(child, css)
# CUI.Events.trigger
# type: "viewport-resize"
# exclude_self: true
# node: layout
return true
@__all: ->
layouts = []
changed = 0
for layout, idx in CUI.dom.matchSelector(document.documentElement, ".cui-absolute")
if CUI.Layout.setAbsolute(layout)
changed++
if changed > 0
# console.info("Layout.setAbsolute[all]: changed: ", changed)
# console.debug "triggering viewport resize"
CUI.Events.trigger(type: "viewport-resize")
@
@all: ->
CUI.scheduleCallback(call: CUI.Layout.__all)
CUI.ready ->
CUI.Events.listen
type: ["viewport-resize", "content-resize"]
call: (ev, info) ->
if info.FlexHandle
CUI.Layout.__all()
else
CUI.Layout.all()
| true | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# {Layout} is used for all layout related stuff, like {HorizontalLayout},
# {VerticalLayout}, {BorderLayout}, {Toolbar}, {Pane}, etc.
#
# It features an automatic {Buttonbar} generation for all panes (see {Layout#append})
class CUI.Layout extends CUI.DOMElement
#Construct a new Layout.
#
# @param [Object] options for layout creation
# @option options [String] maximize the center so that it pushes top pane to top and bottom pane to the bottom of the parent element
# @option options [Object] pane name of the pane on its options, check {Layout.initPane} for the options.
# TODO document other options
# TODO create a Pane Class
constructor: (opts) ->
super(opts)
@__isInit = false
@init()
initOpts: ->
super()
@addOpts
absolute:
check: Boolean
maximize:
check: Boolean
maximize_horizontal:
check: Boolean
maximize_vertical:
check: Boolean
auto_buttonbar:
default: true
mandatory: true
check: Boolean
center:
default: {}
check: "PlainObject"
for pn in @getSupportedPanes()
@addOpt(pn,
check: (v) ->
CUI.util.isPlainObject(v) or v == false
)
readOpts: ->
# DEBUG
# without absolute "help", FF and Safari perform badly, Chrome & IE (Edge) are fine
@initDefaultPanes()
super()
@maximizeReadOpts()
if @_absolute
CUI.util.assert(@__maximize, "new "+@__cls, "opts.absolute needs opts.maximize to be set.", opts: @opts)
@
maximizeAddClasses: ->
if @__maximize
@addClass("cui-maximize")
if @__maximize_horizontal
@addClass("cui-maximize-horizontal")
if @__maximize_vertical
@addClass("cui-maximize-vertical")
@
maximizeReadOpts: ->
if CUI.util.isNull(@_maximize) and
CUI.util.isNull(@_maximize_horizontal) and
CUI.util.isNull(@_maximize_vertical)
@_maximize = true
if @_maximize
CUI.util.assert(not @_maximize_horizontal and not @_maximize_vertical, "new "+CUI.util.getObjectClass(@), "opts.maximize cannot be set together with opts.maximize_horizontal or opts.maximize_vertical", opts: @opts)
@__maximize_horizontal = true
@__maximize_vertical = true
else
if @_maximize_horizontal
@__maximize_horizontal = true
if @_maximize_vertical
@__maximize_vertical = true
if @__maximize_vertical and @__maximize_horizontal
@__maximize = true
@
init: ->
@__init()
getTemplateMap: ->
map = {}
for pn in @__panes
map[pn] = true
map
__init: ->
CUI.util.assert(not(@_maximize == false and @_absolute == true), "Layout.__init", "opts.maximize == false and opts.absolute == true is not allowed.", opts: @opts)
@__panes = @getPanes()
@__panes.push("center")
@__name = @getName()
@__layout = new CUI.Template
name: @__name
map_prefix: @getMapPrefix()
map: @getTemplateMap()
@registerTemplate(@__layout)
# if @__maximize_horizontal and @__maximize_vertical
# CUI.Events.listen
# type: "content-resize"
# instance: @
# node: @DOM
# call: (ev) =>
# console.debug "context-resizse stopped"
# if CUI.dom.closest(ev.getTarget(), '.cui-absolute')
# # no stopping inside absolute layouts
# return
# ev.stopPropagation()
@maximizeAddClasses()
@addClass(@getMapPrefix())
if @_absolute
@addClass("cui-absolute")
CUI.util.assert(CUI.dom.getAttribute(@DOM, "data-cui-absolute-container") in ["row","column"], "new CUI.Layout", "opts.absolute: template must include a cui-absolute-container attribute set to \"row\" or \"column\".")
CUI.dom.waitForDOMInsert(node: @DOM)
.done =>
# console.debug "Layout[absolute] inserted", @__uniqueId
CUI.Layout.all()
# _call = (event) =>
# console.error "Layout.setAbsolute[#{event.getDebug()}]:", @DOM[0]
# # console.error "Layout[viewport-resize] received", @DOM[0]
# #
# event.stopPropagation()
# Layout.setAbsolute(@DOM)
# CUI.Events.listen
# type: "viewport-resize"
# node: @DOM
# instance: @
# call: _call
# CUI.Events.listen
# type: "content-resize"
# node: @DOM
# instance: @
# call: _call
else
CUI.dom.removeAttribute(@DOM, "data-cui-absolute-container")
for child in @DOM.children
CUI.dom.removeAttribute(child, "data-cui-absolute-set")
@__buttonbars = {}
if @hasFlexHandles()
has_flex_handles = true
# console.warn(CUI.util.getObjectClass(@)+".initFlexHandles", @opts, @__layout.__uniqueId, @DOM[0])
pane_opts = {}
for pn in @__panes
pane = @["_#{pn}"]
if pane?.flexHandle
pane_opts[pn] = pane.flexHandle
@__layout.initFlexHandles(pane_opts)
else
has_flex_handles = false
# every pane gets a method "<pane>: ->" to retrieve
# the DOM element from the template
for pn in @__panes
do (pn) =>
@[pn] = =>
CUI.util.assert(@["_#{pn}"], "#{@__cls}.#{pn}", "Pane \"#{pn}\" not initialized.", opts: @opts)
CUI.util.assert(not @__layout.isDestroyed(), "Layout already destroyed, cannot get pane \"#{pn}\".")
@__layout.map[pn]
pane = @["_#{pn}"]
if pane
@__initPane(pane, pn)
if has_flex_handles and pn != "center" and not pane.flexHandle
@__layout.getFlexHandle(pn).destroy()
else
# console.debug(CUI.util.getObjectClass(@), "removing uninitialized pane", pn, @)
CUI.dom.remove(@__layout.map[pn])
if has_flex_handles
@__layout.getFlexHandle(pn).destroy()
@__isInit = true
destroy: ->
CUI.Events.ignore(instance: @)
super()
getMapPrefix: ->
undefined
#initialive pane option
__initPane: (options, pane_name) ->
CUI.util.assert(pane_name, "Layout.initPane", "pane_name must be set", options: options, pane_name: pane_name)
opts = CUI.Element.readOpts(options, "new CUI.Layout.__initPane",
class:
check: String
ui:
check: String
content: {}
flexHandle: {}
)
@append(opts.content, pane_name)
if opts.class
@__layout.addClass(opts.class, pane_name)
if opts.ui
CUI.dom.setAttribute(@__layout.get(pane_name), "ui", opts.ui)
return
# returns true if this Layout has at least one
# flexHandle
hasFlexHandles: ->
true
# init default panes, so that they are in markup
initDefaultPanes: ->
for pn in @getPanes()
if not @opts.hasOwnProperty(pn)
@opts[pn] = {}
@
getPanes: ->
CUI.util.assert(false, "#{@__cls}.getPanes", "Needs implementation")
getSupportedPanes: ->
CUI.util.assert(false, "#{@__cls}.getSupportedPanes", "Needs implementation")
getLayout: ->
@__layout
getButtonbar: (key) ->
if not @__buttonbars[key]
@__buttonbars[key] = new CUI.Buttonbar()
# console.info("#{@__cls}: automatically generated Buttonbar for #{key}.")
CUI.DOMElement::append.call(@, @__buttonbars[key], key)
@__buttonbars[key]
__callAutoButtonbar: (value, key) ->
if CUI.util.isFunction(value)
value = value(@)
get_value = (v) ->
if CUI.util.isPlainObject(v)
return new CUI.defaults.class.Button(v)
else
return v
value = get_value(value)
if CUI.util.isArray(value)
for _v in value
v = get_value(_v)
if v instanceof CUI.Button
@getButtonbar(key).addButton(v)
else
CUI.DOMElement::append.call(@, _v, key)
else if value instanceof CUI.Button
@getButtonbar(key).addButton(value)
else
return CUI.DOMElement::append.call(@, value, key)
# @param [jQuery, Function, Array, ...] value the value to append to the layer
# @param [String] key the name of the pane
# @param [Boolean] auto_buttonbar if set to true (default), automatically generate a {Buttonbar} for Buttons passed directly, in an Array or thru a Function
#
# @return [jQuery] the DOM node (created and) appended
append: (value, key, auto_buttonbar = @_auto_buttonbar) ->
if auto_buttonbar
return @__callAutoButtonbar(value, key)
else
return super(value, key)
replace: (value, key, auto_buttonbar = @_auto_buttonbar) ->
if auto_buttonbar
delete(@__buttonbars[key])
@empty(key)
return @__callAutoButtonbar(value, key)
else
return super(value, key)
setAbsolute: ->
@addClass("cui-absolute")
CUI.Layout.__all()
unsetAbsolute: ->
@DOM.removeAttribute("data-cui-absolute-check-value")
@DOM.removeAttribute("data-cui-absolute-values")
for child in CUI.dom.children(@DOM)
CUI.dom.setStyle child,
top: ""
left: ""
right: ""
bottom: ""
@removeClass("cui-absolute")
@
getName: ->
CUI.util.assert(false, "#{@__cls}.getName", "Needs to be overwritten.")
@setAbsolute: (layout) ->
# console.error "Layout.setAbsolute", layout[0]
CUI.util.assert(CUI.util.isElement(layout), "Layout.setAbsolute", "layout needs to be HTMLElement", layout: layout)
direction = CUI.dom.getAttribute(layout, "data-cui-absolute-container")
switch direction
when "row"
rect_key = "PI:KEY:<KEY>END_PI"
rect_check_key = "PI:KEY:<KEY>END_PI"
when "column"
rect_key = "PI:KEY:<KEY>END_PI"
rect_check_key = "PI:KEY:<KEY>END_PI"
else
CUI.util.assert(false, "Layout.setAbsolute", "cui-absolute-container is not set for .cui-absolute container or not set to row or column.", container: layout, direction: direction)
# measure all children
values = []
children = CUI.dom.children(layout)
for child, idx in children
values[idx] = CUI.dom.getDimensions(child)[rect_key]
abs_values = values.join(",")
check_value = CUI.dom.getDimensions(layout)[rect_check_key]+""
# console.debug layout, abs_values, CUI.dom.getAttribute(layout, "data-cui-absolute-values")
# console.debug layout, check_value, CUI.dom.getAttribute(layout, "data-cui-absolute-check-value")
if CUI.dom.getAttribute(layout, "data-cui-absolute-values") == abs_values and
CUI.dom.getAttribute(layout, "data-cui-absolute-check-value") == check_value
# nothing to do
return false
if CUI.dom.getAttribute(layout, "data-cui-absolute-check-value") != check_value
CUI.dom.setAttribute(layout, "data-cui-absolute-check-value", check_value)
if CUI.dom.getAttribute(layout, "data-cui-absolute-values") != abs_values
CUI.dom.setAttribute(layout, "data-cui-absolute-values", abs_values)
# console.debug(txt, values)
for child, idx in children
set = CUI.dom.getAttribute(child, "data-cui-absolute-set")
if not set
continue
css = {}
for key in set.split(",")
switch key
when "left", "top"
# this is left hand
if idx > 0
value = values.slice(0, idx).reduce((a,b) -> a+b)
else
value = 0
when "right", "bottom"
if idx + 1 < values.length
value = values.slice(idx+1).reduce((a,b) -> a+b)
else
value = 0
else
CUI.util.assert(false, "Layout.setAbsolute: Unknown key #{key} in data-cui-absolute-set.")
# console.debug idx, key, value
css[key] = value
CUI.dom.setStyle(child, css)
# CUI.Events.trigger
# type: "viewport-resize"
# exclude_self: true
# node: layout
return true
@__all: ->
layouts = []
changed = 0
for layout, idx in CUI.dom.matchSelector(document.documentElement, ".cui-absolute")
if CUI.Layout.setAbsolute(layout)
changed++
if changed > 0
# console.info("Layout.setAbsolute[all]: changed: ", changed)
# console.debug "triggering viewport resize"
CUI.Events.trigger(type: "viewport-resize")
@
@all: ->
CUI.scheduleCallback(call: CUI.Layout.__all)
CUI.ready ->
CUI.Events.listen
type: ["viewport-resize", "content-resize"]
call: (ev, info) ->
if info.FlexHandle
CUI.Layout.__all()
else
CUI.Layout.all()
|
[
{
"context": "'Webslide'\n title: 'Webslide'\n copyright: '© Kelvin Miao, 2016'\n\n $scope.socket_io = io()\n $scope.show_h",
"end": 295,
"score": 0.9998795986175537,
"start": 284,
"tag": "NAME",
"value": "Kelvin Miao"
}
] | static/js/app.coffee | tjumyk/webslide | 0 | PDFJS.workerSrc = '/static/vendor/js/pdfjs/build/pdf.worker.js'
angular.module 'app', []
.controller 'rootController', ['$scope','$http', '$sce', '$timeout', 'util', ($scope, $http, $sce, $timeout, util)->
$scope.app =
name: 'Webslide'
title: 'Webslide'
copyright: '© Kelvin Miao, 2016'
$scope.socket_io = io()
$scope.show_home_menu = true
$scope.host_mode = false
$scope.mouse_positions = {}
$scope.mouse_timeout = {}
canvas_wrapper = document.querySelector('.canvas-wrapper')
canvas_pdf = document.getElementById('canvas-pdf')
canvas_pdf_context = canvas_pdf.getContext('2d')
canvas_board = document.getElementById('canvas-board')
canvas_board_context = canvas_board.getContext('2d')
canvas_board_buffer = document.getElementById('canvas-board-buffer')
canvas_board_buffer_context = canvas_board_buffer.getContext('2d')
$scope.socket_io
.on 'id', (data)->
$scope.$apply ->
$scope.id = data
.on 'status', (status)->
$scope.$apply ->
$scope.status = status
delete_ghost_users()
.on 'mousePos', (data)->
$timeout.cancel($scope.mouse_timeout[data.user_id])
$scope.$apply ->
data._active = true
$scope.mouse_positions[data.user_id] = data
$scope.mouse_timeout[data.user_id] = $timeout ->
pos = $scope.mouse_positions[data.user_id]
if pos
pos._active = false
, 3000
.on 'drawPath', (data)->
$scope.$apply ->
if not $scope.status or not $scope.pdf or not $scope.scale
return
total_seg = data.path.length
if total_seg == 0
return
scale = $scope.scale
color = $scope.get_user(data.user_id).color
canvas_board_context.lineWidth = scale
canvas_board_context.strokeStyle = color
canvas_board_context.beginPath()
canvas_board_context.moveTo(data.path[0].x * scale, data.path[0].y * scale)
i = 1
prev_seg = data.path[0]
while i < total_seg
seg = data.path[i]
canvas_board_context.bezierCurveTo((prev_seg.x + prev_seg.ox) * scale, (prev_seg.y + prev_seg.oy) * scale, (seg.x + seg.ix) * scale, (seg.y + seg.iy) * scale, seg.x * scale, seg.y * scale)
prev_seg = seg
i++
canvas_board_context.stroke()
canvas_board_context.closePath()
.on 'refresh', ->
$scope.$apply ->
$scope.render()
$scope.$watch 'status.file_id', (new_val)->
$scope.show_home_menu = !new_val
if !!new_val
$scope.load_pdf('/pdf/'+new_val, $scope.status.page)
else
$scope.reset_pdf()
$scope.$watch 'status.page', (new_val)->
return if not new_val or not $scope.pdf
$scope.load_page(new_val)
$scope.get_user = (uid)->
return undefined if !$scope.status
for user in $scope.status.users
if user.id == uid
return user
return undefined
$scope.load_pdf = (url, page, callback)->
$scope.pdf = undefined
$scope.downloadProgress = 0
PDFJS.getDocument(url, undefined , undefined , (progress)->
if progress.total > 0
$timeout ->
if progress.loaded >= progress.total
$scope.downloadProgress = undefined
else
$scope.downloadProgress = Math.round(100.0 * progress.loaded / progress.total)
).then (pdf)->
$scope.pdf = pdf
$scope.load_page(page, callback)
, (data)->
console.error(data)
$scope.reset_pdf = ->
$scope.page = undefined
$scope.pdf = undefined
canvas_wrapper.style.width = '0px'
canvas_wrapper.style.height = '0px'
$scope.load_page = (page_num, callback)->
return if not $scope.pdf
$scope.page = undefined
$scope.pdf.getPage(page_num).then (page)->
$scope.page = page
$scope.render()
, (data)->
console.error(data)
$scope.toggle_fullscreen = ->
util.toggleFullscreen()
$scope.refresh = ->
$scope.socket_io.emit 'refresh'
$scope.render = ->
if not $scope.pdf or not $scope.page
return
viewport = $scope.page.getViewport(1.0)
scale_w = document.body.clientWidth / viewport.width
scale_h = document.body.clientHeight / viewport.height
$scope.scale = Math.min(scale_w, scale_h)
viewport = $scope.page.getViewport($scope.scale)
canvas_wrapper.style.width = viewport.width + 'px'
canvas_wrapper.style.height = viewport.height + 'px'
canvas_wrapper.style.left = (document.body.clientWidth - viewport.width)/2 + 'px'
canvas_wrapper.style.top = (document.body.clientHeight - viewport.height)/2 + 'px'
$('canvas').each ->
@width = viewport.width
@height = viewport.height
$scope.page.render
canvasContext: canvas_pdf_context
viewport: viewport
paper.setup([viewport.width / $scope.scale, viewport.height / $scope.scale])
$inputPDF = $('#input-pdf')
$inputPDF.on 'change', ()->
return if @files.length != 1
sendFile(@files[0])
@.value = ''
$scope.startPresentation = ->
$scope.uploadProgress = undefined
$scope.host_mode = true
$inputPDF.click()
return
delete_ghost_users = ->
to_remove = []
for uid of $scope.mouse_positions
not_found = true
for user in $scope.status.users
if user.id == uid
not_found = false
break
if not_found
to_remove.push(uid)
for uid in to_remove
delete $scope.mouse_positions[uid]
sendFile = (file) ->
$timeout ->
formData = new FormData()
formData.append('pdf', file)
formData.append('host', $scope.id)
$.ajax
type:'POST'
url: '/upload-pdf'
data:formData
xhr: ->
myXhr = $.ajaxSettings.xhr()
if myXhr.upload
myXhr.upload.addEventListener('progress',fileProgress, false)
else
console.warn('Failed to add file upload progress listener')
return myXhr
cache:false
contentType: false
processData: false
success:(data)->
console.log(data)
error: (data)->
console.error(data)
fileProgress = (e)->
if e.lengthComputable
max = e.total
current = e.loaded
$scope.$apply ->
if current == max
$scope.uploadProgress = undefined
else
$scope.uploadProgress = 100.0 * current / max
else
console.warn('File upload progress is not computable')
resizeCanvas = ->
$timeout ->
$scope.render()
resizeCanvas()
$(window). on 'resize', resizeCanvas
$(document). on 'keydown', (e)->
if e.keyCode == 37 or e.keyCode == 38
$scope.load_prev_page()
else if e.keyCode == 39 or e.keyCode == 40
$scope.load_next_page()
$scope.load_prev_page = ->
if $scope.id != $scope.status.host
return
if not $scope.status or not $scope.pdf
return
page = $scope.status.page
if page > 1
$scope.status.page = page - 1
$scope.socket_io.emit 'statusUpdate', $scope.status
$scope.load_next_page = ->
if $scope.id != $scope.status.host
return
if not $scope.status or not $scope.pdf
return
page = $scope.status.page
if page < $scope.pdf.numPages
$scope.status.page = page + 1
$scope.socket_io.emit 'statusUpdate', $scope.status
draw_started = false
draw_path = []
draw_start = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
if e.type == 'mousedown' and e.which != 1 # clicked non-left button
return
draw_started = true
if e.touches
t = e.touches[0]
px = t.pageX
py = t.pageY
else
px = e.pageX
py = e.pageY
pos =
x: (px - @offsetLeft) / $scope.scale
y: (py - @offsetTop) / $scope.scale
draw_path = [pos]
canvas_board_buffer_context.lineWidth = $scope.scale
canvas_board_buffer_context.strokeStyle = $scope.get_user($scope.id).color
canvas_board_buffer_context.beginPath()
canvas_board_buffer_context.moveTo(pos.x * $scope.scale, pos.y * $scope.scale)
drawing = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
if e.touches
t = e.touches[0]
px = t.pageX
py = t.pageY
else
px = e.pageX
py = e.pageY
pos =
x: (px - @offsetLeft)/ $scope.scale
y: (py - @offsetTop) / $scope.scale
$scope.socket_io.emit 'mousePosUpdate', pos
if draw_started
draw_path.push(pos)
canvas_board_buffer_context.lineTo(pos.x * $scope.scale, pos.y * $scope.scale)
canvas_board_buffer_context.clearRect(0, 0, canvas_board_buffer.width, canvas_board_buffer.height)
canvas_board_buffer_context.stroke()
draw_end = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
canvas_board_buffer_context.closePath()
canvas_board_buffer_context.clearRect(0, 0, canvas_board_buffer.width, canvas_board_buffer.height)
draw_started = false
$scope.socket_io.emit 'drawPath',
path: optimize_path(draw_path)
optimize_path = (path)->
p = new paper.Path
segments: path
p.simplify(1.0)
results = []
total = p.segments.length
for seg, i in p.segments
data =
x: Math.round(seg.point.x * 100) / 100
y: Math.round(seg.point.y * 100) / 100
if i > 0
data.ix = Math.round(seg.handleIn.x * 100) / 100
data.iy = Math.round(seg.handleIn.y * 100) / 100
if i < total - 1
data.ox = Math.round(seg.handleOut.x * 100) / 100
data.oy = Math.round(seg.handleOut.y * 100) / 100
results.push(data)
return results
$(canvas_wrapper)
.on 'mousedown touchstart', draw_start
.on 'mousemove touchmove', drawing
.on 'mouseup touchend', draw_end
$(document.body).on 'touchmove', (e)->
e.preventDefault()
$(window).on 'close', ->
$scope.socket_io.close()
] | 198090 | PDFJS.workerSrc = '/static/vendor/js/pdfjs/build/pdf.worker.js'
angular.module 'app', []
.controller 'rootController', ['$scope','$http', '$sce', '$timeout', 'util', ($scope, $http, $sce, $timeout, util)->
$scope.app =
name: 'Webslide'
title: 'Webslide'
copyright: '© <NAME>, 2016'
$scope.socket_io = io()
$scope.show_home_menu = true
$scope.host_mode = false
$scope.mouse_positions = {}
$scope.mouse_timeout = {}
canvas_wrapper = document.querySelector('.canvas-wrapper')
canvas_pdf = document.getElementById('canvas-pdf')
canvas_pdf_context = canvas_pdf.getContext('2d')
canvas_board = document.getElementById('canvas-board')
canvas_board_context = canvas_board.getContext('2d')
canvas_board_buffer = document.getElementById('canvas-board-buffer')
canvas_board_buffer_context = canvas_board_buffer.getContext('2d')
$scope.socket_io
.on 'id', (data)->
$scope.$apply ->
$scope.id = data
.on 'status', (status)->
$scope.$apply ->
$scope.status = status
delete_ghost_users()
.on 'mousePos', (data)->
$timeout.cancel($scope.mouse_timeout[data.user_id])
$scope.$apply ->
data._active = true
$scope.mouse_positions[data.user_id] = data
$scope.mouse_timeout[data.user_id] = $timeout ->
pos = $scope.mouse_positions[data.user_id]
if pos
pos._active = false
, 3000
.on 'drawPath', (data)->
$scope.$apply ->
if not $scope.status or not $scope.pdf or not $scope.scale
return
total_seg = data.path.length
if total_seg == 0
return
scale = $scope.scale
color = $scope.get_user(data.user_id).color
canvas_board_context.lineWidth = scale
canvas_board_context.strokeStyle = color
canvas_board_context.beginPath()
canvas_board_context.moveTo(data.path[0].x * scale, data.path[0].y * scale)
i = 1
prev_seg = data.path[0]
while i < total_seg
seg = data.path[i]
canvas_board_context.bezierCurveTo((prev_seg.x + prev_seg.ox) * scale, (prev_seg.y + prev_seg.oy) * scale, (seg.x + seg.ix) * scale, (seg.y + seg.iy) * scale, seg.x * scale, seg.y * scale)
prev_seg = seg
i++
canvas_board_context.stroke()
canvas_board_context.closePath()
.on 'refresh', ->
$scope.$apply ->
$scope.render()
$scope.$watch 'status.file_id', (new_val)->
$scope.show_home_menu = !new_val
if !!new_val
$scope.load_pdf('/pdf/'+new_val, $scope.status.page)
else
$scope.reset_pdf()
$scope.$watch 'status.page', (new_val)->
return if not new_val or not $scope.pdf
$scope.load_page(new_val)
$scope.get_user = (uid)->
return undefined if !$scope.status
for user in $scope.status.users
if user.id == uid
return user
return undefined
$scope.load_pdf = (url, page, callback)->
$scope.pdf = undefined
$scope.downloadProgress = 0
PDFJS.getDocument(url, undefined , undefined , (progress)->
if progress.total > 0
$timeout ->
if progress.loaded >= progress.total
$scope.downloadProgress = undefined
else
$scope.downloadProgress = Math.round(100.0 * progress.loaded / progress.total)
).then (pdf)->
$scope.pdf = pdf
$scope.load_page(page, callback)
, (data)->
console.error(data)
$scope.reset_pdf = ->
$scope.page = undefined
$scope.pdf = undefined
canvas_wrapper.style.width = '0px'
canvas_wrapper.style.height = '0px'
$scope.load_page = (page_num, callback)->
return if not $scope.pdf
$scope.page = undefined
$scope.pdf.getPage(page_num).then (page)->
$scope.page = page
$scope.render()
, (data)->
console.error(data)
$scope.toggle_fullscreen = ->
util.toggleFullscreen()
$scope.refresh = ->
$scope.socket_io.emit 'refresh'
$scope.render = ->
if not $scope.pdf or not $scope.page
return
viewport = $scope.page.getViewport(1.0)
scale_w = document.body.clientWidth / viewport.width
scale_h = document.body.clientHeight / viewport.height
$scope.scale = Math.min(scale_w, scale_h)
viewport = $scope.page.getViewport($scope.scale)
canvas_wrapper.style.width = viewport.width + 'px'
canvas_wrapper.style.height = viewport.height + 'px'
canvas_wrapper.style.left = (document.body.clientWidth - viewport.width)/2 + 'px'
canvas_wrapper.style.top = (document.body.clientHeight - viewport.height)/2 + 'px'
$('canvas').each ->
@width = viewport.width
@height = viewport.height
$scope.page.render
canvasContext: canvas_pdf_context
viewport: viewport
paper.setup([viewport.width / $scope.scale, viewport.height / $scope.scale])
$inputPDF = $('#input-pdf')
$inputPDF.on 'change', ()->
return if @files.length != 1
sendFile(@files[0])
@.value = ''
$scope.startPresentation = ->
$scope.uploadProgress = undefined
$scope.host_mode = true
$inputPDF.click()
return
delete_ghost_users = ->
to_remove = []
for uid of $scope.mouse_positions
not_found = true
for user in $scope.status.users
if user.id == uid
not_found = false
break
if not_found
to_remove.push(uid)
for uid in to_remove
delete $scope.mouse_positions[uid]
sendFile = (file) ->
$timeout ->
formData = new FormData()
formData.append('pdf', file)
formData.append('host', $scope.id)
$.ajax
type:'POST'
url: '/upload-pdf'
data:formData
xhr: ->
myXhr = $.ajaxSettings.xhr()
if myXhr.upload
myXhr.upload.addEventListener('progress',fileProgress, false)
else
console.warn('Failed to add file upload progress listener')
return myXhr
cache:false
contentType: false
processData: false
success:(data)->
console.log(data)
error: (data)->
console.error(data)
fileProgress = (e)->
if e.lengthComputable
max = e.total
current = e.loaded
$scope.$apply ->
if current == max
$scope.uploadProgress = undefined
else
$scope.uploadProgress = 100.0 * current / max
else
console.warn('File upload progress is not computable')
resizeCanvas = ->
$timeout ->
$scope.render()
resizeCanvas()
$(window). on 'resize', resizeCanvas
$(document). on 'keydown', (e)->
if e.keyCode == 37 or e.keyCode == 38
$scope.load_prev_page()
else if e.keyCode == 39 or e.keyCode == 40
$scope.load_next_page()
$scope.load_prev_page = ->
if $scope.id != $scope.status.host
return
if not $scope.status or not $scope.pdf
return
page = $scope.status.page
if page > 1
$scope.status.page = page - 1
$scope.socket_io.emit 'statusUpdate', $scope.status
$scope.load_next_page = ->
if $scope.id != $scope.status.host
return
if not $scope.status or not $scope.pdf
return
page = $scope.status.page
if page < $scope.pdf.numPages
$scope.status.page = page + 1
$scope.socket_io.emit 'statusUpdate', $scope.status
draw_started = false
draw_path = []
draw_start = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
if e.type == 'mousedown' and e.which != 1 # clicked non-left button
return
draw_started = true
if e.touches
t = e.touches[0]
px = t.pageX
py = t.pageY
else
px = e.pageX
py = e.pageY
pos =
x: (px - @offsetLeft) / $scope.scale
y: (py - @offsetTop) / $scope.scale
draw_path = [pos]
canvas_board_buffer_context.lineWidth = $scope.scale
canvas_board_buffer_context.strokeStyle = $scope.get_user($scope.id).color
canvas_board_buffer_context.beginPath()
canvas_board_buffer_context.moveTo(pos.x * $scope.scale, pos.y * $scope.scale)
drawing = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
if e.touches
t = e.touches[0]
px = t.pageX
py = t.pageY
else
px = e.pageX
py = e.pageY
pos =
x: (px - @offsetLeft)/ $scope.scale
y: (py - @offsetTop) / $scope.scale
$scope.socket_io.emit 'mousePosUpdate', pos
if draw_started
draw_path.push(pos)
canvas_board_buffer_context.lineTo(pos.x * $scope.scale, pos.y * $scope.scale)
canvas_board_buffer_context.clearRect(0, 0, canvas_board_buffer.width, canvas_board_buffer.height)
canvas_board_buffer_context.stroke()
draw_end = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
canvas_board_buffer_context.closePath()
canvas_board_buffer_context.clearRect(0, 0, canvas_board_buffer.width, canvas_board_buffer.height)
draw_started = false
$scope.socket_io.emit 'drawPath',
path: optimize_path(draw_path)
optimize_path = (path)->
p = new paper.Path
segments: path
p.simplify(1.0)
results = []
total = p.segments.length
for seg, i in p.segments
data =
x: Math.round(seg.point.x * 100) / 100
y: Math.round(seg.point.y * 100) / 100
if i > 0
data.ix = Math.round(seg.handleIn.x * 100) / 100
data.iy = Math.round(seg.handleIn.y * 100) / 100
if i < total - 1
data.ox = Math.round(seg.handleOut.x * 100) / 100
data.oy = Math.round(seg.handleOut.y * 100) / 100
results.push(data)
return results
$(canvas_wrapper)
.on 'mousedown touchstart', draw_start
.on 'mousemove touchmove', drawing
.on 'mouseup touchend', draw_end
$(document.body).on 'touchmove', (e)->
e.preventDefault()
$(window).on 'close', ->
$scope.socket_io.close()
] | true | PDFJS.workerSrc = '/static/vendor/js/pdfjs/build/pdf.worker.js'
angular.module 'app', []
.controller 'rootController', ['$scope','$http', '$sce', '$timeout', 'util', ($scope, $http, $sce, $timeout, util)->
$scope.app =
name: 'Webslide'
title: 'Webslide'
copyright: '© PI:NAME:<NAME>END_PI, 2016'
$scope.socket_io = io()
$scope.show_home_menu = true
$scope.host_mode = false
$scope.mouse_positions = {}
$scope.mouse_timeout = {}
canvas_wrapper = document.querySelector('.canvas-wrapper')
canvas_pdf = document.getElementById('canvas-pdf')
canvas_pdf_context = canvas_pdf.getContext('2d')
canvas_board = document.getElementById('canvas-board')
canvas_board_context = canvas_board.getContext('2d')
canvas_board_buffer = document.getElementById('canvas-board-buffer')
canvas_board_buffer_context = canvas_board_buffer.getContext('2d')
$scope.socket_io
.on 'id', (data)->
$scope.$apply ->
$scope.id = data
.on 'status', (status)->
$scope.$apply ->
$scope.status = status
delete_ghost_users()
.on 'mousePos', (data)->
$timeout.cancel($scope.mouse_timeout[data.user_id])
$scope.$apply ->
data._active = true
$scope.mouse_positions[data.user_id] = data
$scope.mouse_timeout[data.user_id] = $timeout ->
pos = $scope.mouse_positions[data.user_id]
if pos
pos._active = false
, 3000
.on 'drawPath', (data)->
$scope.$apply ->
if not $scope.status or not $scope.pdf or not $scope.scale
return
total_seg = data.path.length
if total_seg == 0
return
scale = $scope.scale
color = $scope.get_user(data.user_id).color
canvas_board_context.lineWidth = scale
canvas_board_context.strokeStyle = color
canvas_board_context.beginPath()
canvas_board_context.moveTo(data.path[0].x * scale, data.path[0].y * scale)
i = 1
prev_seg = data.path[0]
while i < total_seg
seg = data.path[i]
canvas_board_context.bezierCurveTo((prev_seg.x + prev_seg.ox) * scale, (prev_seg.y + prev_seg.oy) * scale, (seg.x + seg.ix) * scale, (seg.y + seg.iy) * scale, seg.x * scale, seg.y * scale)
prev_seg = seg
i++
canvas_board_context.stroke()
canvas_board_context.closePath()
.on 'refresh', ->
$scope.$apply ->
$scope.render()
$scope.$watch 'status.file_id', (new_val)->
$scope.show_home_menu = !new_val
if !!new_val
$scope.load_pdf('/pdf/'+new_val, $scope.status.page)
else
$scope.reset_pdf()
$scope.$watch 'status.page', (new_val)->
return if not new_val or not $scope.pdf
$scope.load_page(new_val)
$scope.get_user = (uid)->
return undefined if !$scope.status
for user in $scope.status.users
if user.id == uid
return user
return undefined
$scope.load_pdf = (url, page, callback)->
$scope.pdf = undefined
$scope.downloadProgress = 0
PDFJS.getDocument(url, undefined , undefined , (progress)->
if progress.total > 0
$timeout ->
if progress.loaded >= progress.total
$scope.downloadProgress = undefined
else
$scope.downloadProgress = Math.round(100.0 * progress.loaded / progress.total)
).then (pdf)->
$scope.pdf = pdf
$scope.load_page(page, callback)
, (data)->
console.error(data)
$scope.reset_pdf = ->
$scope.page = undefined
$scope.pdf = undefined
canvas_wrapper.style.width = '0px'
canvas_wrapper.style.height = '0px'
$scope.load_page = (page_num, callback)->
return if not $scope.pdf
$scope.page = undefined
$scope.pdf.getPage(page_num).then (page)->
$scope.page = page
$scope.render()
, (data)->
console.error(data)
$scope.toggle_fullscreen = ->
util.toggleFullscreen()
$scope.refresh = ->
$scope.socket_io.emit 'refresh'
$scope.render = ->
if not $scope.pdf or not $scope.page
return
viewport = $scope.page.getViewport(1.0)
scale_w = document.body.clientWidth / viewport.width
scale_h = document.body.clientHeight / viewport.height
$scope.scale = Math.min(scale_w, scale_h)
viewport = $scope.page.getViewport($scope.scale)
canvas_wrapper.style.width = viewport.width + 'px'
canvas_wrapper.style.height = viewport.height + 'px'
canvas_wrapper.style.left = (document.body.clientWidth - viewport.width)/2 + 'px'
canvas_wrapper.style.top = (document.body.clientHeight - viewport.height)/2 + 'px'
$('canvas').each ->
@width = viewport.width
@height = viewport.height
$scope.page.render
canvasContext: canvas_pdf_context
viewport: viewport
paper.setup([viewport.width / $scope.scale, viewport.height / $scope.scale])
$inputPDF = $('#input-pdf')
$inputPDF.on 'change', ()->
return if @files.length != 1
sendFile(@files[0])
@.value = ''
$scope.startPresentation = ->
$scope.uploadProgress = undefined
$scope.host_mode = true
$inputPDF.click()
return
delete_ghost_users = ->
to_remove = []
for uid of $scope.mouse_positions
not_found = true
for user in $scope.status.users
if user.id == uid
not_found = false
break
if not_found
to_remove.push(uid)
for uid in to_remove
delete $scope.mouse_positions[uid]
sendFile = (file) ->
$timeout ->
formData = new FormData()
formData.append('pdf', file)
formData.append('host', $scope.id)
$.ajax
type:'POST'
url: '/upload-pdf'
data:formData
xhr: ->
myXhr = $.ajaxSettings.xhr()
if myXhr.upload
myXhr.upload.addEventListener('progress',fileProgress, false)
else
console.warn('Failed to add file upload progress listener')
return myXhr
cache:false
contentType: false
processData: false
success:(data)->
console.log(data)
error: (data)->
console.error(data)
fileProgress = (e)->
if e.lengthComputable
max = e.total
current = e.loaded
$scope.$apply ->
if current == max
$scope.uploadProgress = undefined
else
$scope.uploadProgress = 100.0 * current / max
else
console.warn('File upload progress is not computable')
resizeCanvas = ->
$timeout ->
$scope.render()
resizeCanvas()
$(window). on 'resize', resizeCanvas
$(document). on 'keydown', (e)->
if e.keyCode == 37 or e.keyCode == 38
$scope.load_prev_page()
else if e.keyCode == 39 or e.keyCode == 40
$scope.load_next_page()
$scope.load_prev_page = ->
if $scope.id != $scope.status.host
return
if not $scope.status or not $scope.pdf
return
page = $scope.status.page
if page > 1
$scope.status.page = page - 1
$scope.socket_io.emit 'statusUpdate', $scope.status
$scope.load_next_page = ->
if $scope.id != $scope.status.host
return
if not $scope.status or not $scope.pdf
return
page = $scope.status.page
if page < $scope.pdf.numPages
$scope.status.page = page + 1
$scope.socket_io.emit 'statusUpdate', $scope.status
draw_started = false
draw_path = []
draw_start = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
if e.type == 'mousedown' and e.which != 1 # clicked non-left button
return
draw_started = true
if e.touches
t = e.touches[0]
px = t.pageX
py = t.pageY
else
px = e.pageX
py = e.pageY
pos =
x: (px - @offsetLeft) / $scope.scale
y: (py - @offsetTop) / $scope.scale
draw_path = [pos]
canvas_board_buffer_context.lineWidth = $scope.scale
canvas_board_buffer_context.strokeStyle = $scope.get_user($scope.id).color
canvas_board_buffer_context.beginPath()
canvas_board_buffer_context.moveTo(pos.x * $scope.scale, pos.y * $scope.scale)
drawing = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
if e.touches
t = e.touches[0]
px = t.pageX
py = t.pageY
else
px = e.pageX
py = e.pageY
pos =
x: (px - @offsetLeft)/ $scope.scale
y: (py - @offsetTop) / $scope.scale
$scope.socket_io.emit 'mousePosUpdate', pos
if draw_started
draw_path.push(pos)
canvas_board_buffer_context.lineTo(pos.x * $scope.scale, pos.y * $scope.scale)
canvas_board_buffer_context.clearRect(0, 0, canvas_board_buffer.width, canvas_board_buffer.height)
canvas_board_buffer_context.stroke()
draw_end = (e)->
e.preventDefault()
if not $scope.status or not $scope.pdf or not $scope.scale
return
canvas_board_buffer_context.closePath()
canvas_board_buffer_context.clearRect(0, 0, canvas_board_buffer.width, canvas_board_buffer.height)
draw_started = false
$scope.socket_io.emit 'drawPath',
path: optimize_path(draw_path)
optimize_path = (path)->
p = new paper.Path
segments: path
p.simplify(1.0)
results = []
total = p.segments.length
for seg, i in p.segments
data =
x: Math.round(seg.point.x * 100) / 100
y: Math.round(seg.point.y * 100) / 100
if i > 0
data.ix = Math.round(seg.handleIn.x * 100) / 100
data.iy = Math.round(seg.handleIn.y * 100) / 100
if i < total - 1
data.ox = Math.round(seg.handleOut.x * 100) / 100
data.oy = Math.round(seg.handleOut.y * 100) / 100
results.push(data)
return results
$(canvas_wrapper)
.on 'mousedown touchstart', draw_start
.on 'mousemove touchmove', drawing
.on 'mouseup touchend', draw_end
$(document.body).on 'touchmove', (e)->
e.preventDefault()
$(window).on 'close', ->
$scope.socket_io.close()
] |
[
{
"context": "r defining Droplet parsers.\n#\n# Copyright (c) 2015 Anthony Bau (dab1998@gmail.com)\n# MIT License\n\nhelper = requi",
"end": 110,
"score": 0.9998762011528015,
"start": 99,
"tag": "NAME",
"value": "Anthony Bau"
},
{
"context": "plet parsers.\n#\n# Copyright (c) 2015 An... | src/parser.coffee | cs50/droplet | 1 | # Droplet parser wrapper.
# Utility functions for defining Droplet parsers.
#
# Copyright (c) 2015 Anthony Bau (dab1998@gmail.com)
# MIT License
helper = require './helper.coffee'
model = require './model.coffee'
exports.PreNodeContext = class PreNodeContext
constructor: (@type, @preParenLength, @postParenLength) ->
apply: (node) ->
trailingText = node.getTrailingText()
trailingText = trailingText[0...trailingText.length - @postParenLength]
leadingText = node.getLeadingText()
leadingText = leadingText[@preParenLength...leadingText.length]
return new model.NodeContext @type, leadingText, trailingText
sax = require 'sax'
_extend = (opts, defaults) ->
unless opts? then return defaults
for key, val of defaults
unless key of opts
opts[key] = val
return opts
YES = -> true
isPrefix = (a, b) -> a[...b.length] is b
exports.ParserFactory = class ParserFactory
constructor: (@opts = {}) ->
createParser: (text) -> new Parser text, @opts
# ## Parser ##
# The Parser class is a simple
# wrapper on the above functions
# and a given parser function.
exports.Parser = class Parser
constructor: (@text, @opts = {}) ->
# Text can sometimes be subject to change
# when doing error recovery, so keep a record of
# the original text.
@originalText = @text
@markup = []
# ## parse ##
_parse: (opts, cachedParse) ->
opts = _extend opts, {
wrapAtRoot: true
preserveEmpty: true
}
# Generate the list of tokens
@markRoot opts.context, cachedParse
# Sort by position and depth
do @sortMarkup
# Generate a document from the markup
document = @applyMarkup opts
# Correct parent tree
document.correctParentTree()
# Add node context annotations from PreNodeContext
# annotations
head = document.start
until head is document.end
if head.type is 'blockStart' and head.container._preNodeContext?
head.container.nodeContext = head.container._preNodeContext.apply head.container
head = head.next
# Strip away blocks flagged to be removed
# (for `` hack and error recovery)
if opts.preserveEmpty
stripFlaggedBlocks document
return document
markRoot: ->
# ## addBlock ##
# addBlock takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# precedence: Number
# color: String
# socketLevel: Number
# parenWrapped: Boolean
# }
addBlock: (opts) ->
block = new model.Block opts.color,
opts.shape,
opts.parseContext,
null,
opts.buttons,
opts.data
block._preNodeContext = opts.nodeContext
@addMarkup block, opts.bounds, opts.depth
addButtonContainer: (opts) ->
container = new model.ButtonContainer opts.parseContext,
opts.buttons,
opts.data
@addMarkup container, opts.bounds, opts.depth
addLockedSocket: (opts) ->
container = new model.LockedSocket opts.parseContext,
opts.dropdown,
opts.data
@addMarkup container, opts.bounds, opts.depth
# flagToRemove, used for removing the placeholders that
# are placed when round-tripping empty sockets, so that, e.g. in CoffeeScript mode
# a + (empty socket) -> a + `` -> a + (empty socket).
#
# These are done by placing blocks around that text and then removing that block from the tree.
flagToRemove: (bounds, depth) ->
block = new model.Block()
block.flagToRemove = true
@addMarkup block, bounds, depth
# ## addSocket ##
# addSocket takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# precedence: Number
# accepts: shallow_dict
# }
addSocket: (opts) ->
socket = new model.Socket opts.empty ? @empty,
false,
opts.dropdown,
opts.parseContext
@addMarkup socket, opts.bounds, opts.depth
# ## addIndent ##
# addIndent takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# prefix: String
# }
addIndent: (opts) ->
indent = new model.Indent @emptyIndent, opts.prefix, opts.indentContext
@addMarkup indent, opts.bounds, opts.depth
checkBounds: (bounds) ->
if not (bounds?.start?.line? and bounds?.start?.column? and
bounds?.end?.line? and bounds?.end?.column?)
throw new IllegalArgumentException 'bad bounds object'
# ## addMarkup ##
# Add a container around some bounds
addMarkup: (container, bounds, depth) ->
@checkBounds bounds
@markup.push
token: container.start
location: bounds.start
depth: depth
start: true
@markup.push
token: container.end
location: bounds.end
depth: depth
start: false
return container
# ## sortMarkup ##
# Sort the markup by the order
# in which it will appear in the text.
sortMarkup: ->
@markup.sort (a, b) ->
# First by line
if a.location.line > b.location.line
return 1
if b.location.line > a.location.line
return -1
# Then by column
if a.location.column > b.location.column
return 1
if b.location.column > a.location.column
return -1
# If two pieces of markup are in the same position, end markup
# comes before start markup
isDifferent = 1
if a.token.container is b.token.container
isDifferent = -1
if a.start and not b.start
return isDifferent
if b.start and not a.start
return -isDifferent
# If two pieces of markup are in the same position,
# and are both start or end,
# the markup placed earlier gets to go on the outside
if a.start and b.start
if a.depth > b.depth
return 1
else return -1
if (not a.start) and (not b.start)
if a.depth > b.depth
return -1
else return 1
# ## constructHandwrittenBlock
# Construct a handwritten block with the given
# text inside
constructHandwrittenBlock: (text) ->
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
if @isComment text
head = block.start
{sockets, color} = @parseComment(text)
if color?
block.color = color
lastPosition = 0
if sockets?
for socketPosition in sockets
socket = new model.Socket '', false, null, '__comment__'
socket.setParent block
padText = text[lastPosition...socketPosition[0]]
if padText.length > 0
padTextToken = new model.TextToken padText
padTextToken.setParent block
helper.connect head, padTextToken
head = padTextToken
textToken = new model.TextToken text[socketPosition[0]...socketPosition[1]]
textToken.setParent block
helper.connect head, socket.start
helper.connect socket.start, textToken
helper.connect textToken, socket.end
head = socket.end
lastPosition = socketPosition[1]
finalPadText = text[lastPosition...text.length]
if finalPadText.length > 0
finalPadTextToken = new model.TextToken finalPadText
finalPadTextToken.setParent block
helper.connect head, finalPadTextToken
head = finalPadTextToken
helper.connect head, block.end
else
socket = new model.Socket '', true
textToken = new model.TextToken text
textToken.setParent socket
block.shape = helper.BLOCK_ONLY
helper.connect block.start, socket.start
helper.connect socket.start, textToken
helper.connect textToken, socket.end
helper.connect socket.end, block.end
return block
handleButton: (text, command, oldblock) ->
return text
# applyMarkup
# -----------
#
# The parser adapter will throw out markup in arbitrary orders. `applyMarkup`'s job is to assemble
# a parse tree from this markup. `applyMarkup` also cleans up any leftover text that lies outside blocks or
# sockets by passing them through a comment-handling procedure.
#
# `applyMarkup` applies the generated markup by sorting it, then walking from the beginning to the end of the
# document, creating `TextToken`s and inserting the markup between them. It also keeps a stack
# of which containers it is currently in, for error detection and comment handling.
#
# Whenever the container is currently an `Indent` or a `Document` and we get some text, we handle it as a comment.
# If it contains block-comment tokens, like /* or */, we immediately make comment blocks around them, amalgamating multiline comments
# into single blocks. We do this by scanning forward and just toggling on or off a bit that says whether we're inside
# a block comment, refusing to put any markup while we're inside one.
#
# When outside a block-comment, we pass free text to the mode's comment parser. This comment parser
# will return a set of text ranges to put in sockets, usually the place where freeform text can be put in the comment.
# For instance, `//hello` in JavaScript should return (2, 6) to put a socket around 'hello'. In C, this is used
# to handle preprocessor directives.
applyMarkup: (opts) ->
# For convenience, will we
# separate the markup by the line on which it is placed.
markupOnLines = {}
for mark in @markup
markupOnLines[mark.location.line] ?= []
markupOnLines[mark.location.line].push mark
# Now, we will interact with the text
# by line-column coordinates. So we first want
# to split the text into lines.
lines = @text.split '\n'
indentDepth = 0
stack = []
document = new model.Document(opts.context ? @rootContext); head = document.start
currentlyCommented = false
for line, i in lines
# If there is no markup on this line,
# helper.connect simply, the text of this line to the document
# (stripping things as needed for indent)
if not (i of markupOnLines)
# If this line is not properly indented,
# flag it in the model.
if indentDepth > line.length or line[...indentDepth].trim().length > 0
head.specialIndent = (' ' for [0...line.length - line.trimLeft().length]).join ''
line = line.trimLeft()
else
line = line[indentDepth...]
# If we have some text here that
# is floating (not surrounded by a block),
# wrap it in a generic block automatically.
#
# We will also send it through a pass through a comment parser here,
# for special handling of different forms of comments (or, e.g. in C mode, directives),
# and amalgamate multiline comments.
placedSomething = false
while line.length > 0
if currentlyCommented
placedSomething = true
if line.indexOf(@endComment) > -1
head = helper.connect head,
new model.TextToken line[...line.indexOf(@endComment) + @endComment.length]
line = line[line.indexOf(@endComment) + @endComment.length...]
head = helper.connect head, stack.pop().end
currentlyCommented = false
if not currentlyCommented and
((opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent') and
line.length > 0
placedSomething = true
if isPrefix(line.trimLeft(), @startComment)
currentlyCommented = true
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
stack.push block
helper.connect head, block.start
head = block.start
else
block = @constructHandwrittenBlock line
helper.connect head, block.start
head = block.end
line = ''
else if line.length > 0
placedSomething = true
head = helper.connect head, new model.TextToken line
line = ''
if line.length is 0 and not placedSomething and stack[stack.length - 1]?.type in ['indent', 'document', undefined] and
hasSomeTextAfter(lines, i)
block = new model.Block @opts.emptyLineColor, helper.BLOCK_ONLY, '__comment__'
head = helper.connect head, block.start
head = helper.connect head, block.end
head = helper.connect head, new model.NewlineToken()
# If there is markup on this line, insert it.
else
# Flag if this line is not properly indented.
if indentDepth > line.length or line[...indentDepth].trim().length > 0
lastIndex = line.length - line.trimLeft().length
head.specialIndent = line[0...lastIndex]
else
lastIndex = indentDepth
for mark in markupOnLines[i]
# If flagToRemove is turned off, ignore markup
# that was generated by the flagToRemove mechanism. This will simply
# create text tokens instead of creating a block slated to be removed.
continue if mark.token.container? and mark.token.container.flagToRemove and not opts.preserveEmpty
# Insert a text token for all the text up until this markup
# (unless there is no such text
unless lastIndex >= mark.location.column or lastIndex >= line.length
if (not currentlyCommented) and
(opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent'
block = @constructHandwrittenBlock line[lastIndex...mark.location.column]
helper.connect head, block.start
head = block.end
else
head = helper.connect head, new model.TextToken(line[lastIndex...mark.location.column])
if currentlyCommented
head = helper.connect head, stack.pop().end
currentlyCommented = false
# Note, if we have inserted something,
# the new indent depth and the new stack.
switch mark.token.type
when 'indentStart'
# An Indent is only allowed to be
# directly inside a block; if not, then throw.
unless stack?[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: indent must be inside block, but is inside ' + stack?[stack.length - 1]?.type
indentDepth += mark.token.container.prefix.length
when 'blockStart'
# If the a block is embedded
# directly in another block, throw.
if stack[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: block cannot nest immediately inside another block.'
when 'socketStart'
# A socket is only allowed to be directly inside a block.
unless stack[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: socket must be immediately inside a block.'
when 'indentEnd'
indentDepth -= mark.token.container.prefix.length
# Update the stack
if mark.token instanceof model.StartToken
stack.push mark.token.container
else if mark.token instanceof model.EndToken
unless mark.token.container is stack[stack.length - 1]
throw new Error "Improper parser: #{head.container.type} ended too early."
stack.pop()
# Append the token
head = helper.connect head, mark.token
lastIndex = mark.location.column
# Append the rest of the string
# (after the last piece of markup)
until lastIndex >= line.length
if currentlyCommented
if line[lastIndex...].indexOf(@endComment) > -1
head = helper.connect head,
new model.TextToken line[lastIndex...lastIndex + line[lastIndex...].indexOf(@endComment) + @endComment.length]
lastIndex += line[lastIndex...].indexOf(@endComment) + @endComment.length
head = helper.connect head, stack.pop().end
currentlyCommented = false
if not currentlyCommented and
((opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent') and
line.length > 0
if isPrefix(line[lastIndex...].trimLeft(), @startComment)
currentlyCommented = true
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
stack.push block
helper.connect head, block.start
head = block.start
else
block = @constructHandwrittenBlock line[lastIndex...]
helper.connect head, block.start
head = block.end
lastIndex = line.length
else if lastIndex < line.length
head = helper.connect head, new model.TextToken line[lastIndex...]
lastIndex = line.length
head = helper.connect head, new model.NewlineToken()
# Pop off the last newline token, which is not necessary
head = head.prev
head.next.remove()
# Reinsert the end token of the document,
# which we previously threw away by using "connect"
head = helper.connect head, document.end
# Return the document
return document
exports.parseXML = (xml) ->
root = new model.Document(); head = root.start
stack = []
parser = sax.parser true
parser.ontext = (text) ->
tokens = text.split '\n'
for token, i in tokens
unless token.length is 0
head = helper.connect head, new model.TextToken token
unless i is tokens.length - 1
head = helper.connect head, new model.NewlineToken()
# TODO Improve serialization format
# for test updates. Currently no longer unity
# because @empty is not preserved.
parser.onopentag = (node) ->
attributes = node.attributes
switch node.name
when 'block'
container = new model.Block attributes.color,
attributes.shape, attributes.parseContext
when 'socket'
container = new model.Socket '', attributes.handritten, attributes.parseContext
when 'indent'
container = new model.Indent '', attributes.prefix, attributes.indentContext
when 'document'
# Root is optional
unless stack.length is 0
container = new model.Document()
when 'br'
head = helper.connect head, new model.NewlineToken()
return null
if container?
stack.push {
node: node
container: container
}
head = helper.connect head, container.start
parser.onclosetag = (nodeName) ->
if stack.length > 0 and nodeName is stack[stack.length - 1].node.name
head = helper.connect head, stack[stack.length - 1].container.end
stack.pop()
parser.onerror = (e) ->
throw e
parser.write(xml).close()
head = helper.connect head, root.end
root.correctParentTree()
return root
hasSomeTextAfter = (lines, i) ->
until i is lines.length
if lines[i].length > 0 then return true
i += 1
return false
# ## applyMarkup ##
# Given some text and (sorted) markup,
# produce an ICE editor document
# with the markup inserted into the text.
#
# Automatically insert sockets around blocks along the way.
stripFlaggedBlocks = (document) ->
head = document.start
until head is document.end
if (head instanceof model.StartToken and
head.container.flagToRemove)
container = head.container
head = container.end.next
document.remove container
else if (head instanceof model.StartToken and
head.container.flagToStrip)
head.container.parent?.color = 'error'
text = head.next
text.value =
text.value.substring(
head.container.flagToStrip.left,
text.value.length - head.container.flagToStrip.right)
head = text.next
else
head = head.next
Parser.parens = (leading, trailing, node, context) ->
Parser.drop = (block, context, pred, next) ->
if block.type is 'document' and context.type is 'socket'
return helper.FORBID
else
return helper.ENCOURAGE
Parser.empty = ''
Parser.emptyIndent = ''
getDefaultSelectionRange = (string) -> {start: 0, end: string.length}
exports.wrapParser = (CustomParser) ->
class CustomParserFactory extends ParserFactory
constructor: (@opts = {}) ->
@empty = CustomParser.empty
@emptyIndent = CustomParser.emptyIndent
@startComment = CustomParser.startComment ? '/*'
@endComment = CustomParser.endComment ? '*/'
@rootContext = CustomParser.rootContext
@startSingleLineComment = CustomParser.startSingleLineComment
@getDefaultSelectionRange = CustomParser.getDefaultSelectionRange ? getDefaultSelectionRange
@getParenCandidates = CustomParser.getParenCandidates
lockedSocketCallback: (socketText, blockText, parseContext) ->
if CustomParser.lockedSocketCallback?
return CustomParser.lockedSocketCallback @opts, socketText, blockText, parseContext
else
return blockText
# TODO kind of hacky assignation of @empty,
# maybe change the api?
createParser: (text) ->
parser = new CustomParser text, @opts
parser.startComment = @startComment
parser.endComment = @endComment
parser.empty = @empty
parser.emptyIndent = @emptyIndent
parser.rootContext = @rootContext
return parser
stringFixer: (string) ->
if CustomParser.stringFixer?
CustomParser.stringFixer.apply @, arguments
else
return string
preparse: (text, context) ->
return @createParser(text).preparse context
parse: (text, opts, cachedParse = null) ->
@opts.parseOptions = opts
opts ?= wrapAtRoot: true
return @createParser(text)._parse opts, cachedParse
parens: (leading, trailing, node, context) ->
# We do this function thing so that if leading and trailing are the same
# (i.e. there is only one text token), parser adapter functions can still treat
# it as if they are two different things.
# leadingFn is always a getter/setter for leading
leadingFn = (value) ->
if value?
leading = value
return leading
# trailingFn may either get/set leading or trailing;
# will point to leading if leading is the only token,
# but will point to trailing otherwise.
if trailing?
trailingFn = (value) ->
if value?
trailing = value
return trailing
else
trailingFn = leadingFn
context = CustomParser.parens leadingFn, trailingFn, node, context
return [leading, trailing, context]
drop: (block, context, pred, next) -> CustomParser.drop block, context, pred, next
handleButton: (text, command, oldblock) ->
parser = @createParser(text)
parser.handleButton text, command, oldblock
| 10507 | # Droplet parser wrapper.
# Utility functions for defining Droplet parsers.
#
# Copyright (c) 2015 <NAME> (<EMAIL>)
# MIT License
helper = require './helper.coffee'
model = require './model.coffee'
exports.PreNodeContext = class PreNodeContext
constructor: (@type, @preParenLength, @postParenLength) ->
apply: (node) ->
trailingText = node.getTrailingText()
trailingText = trailingText[0...trailingText.length - @postParenLength]
leadingText = node.getLeadingText()
leadingText = leadingText[@preParenLength...leadingText.length]
return new model.NodeContext @type, leadingText, trailingText
sax = require 'sax'
_extend = (opts, defaults) ->
unless opts? then return defaults
for key, val of defaults
unless key of opts
opts[key] = val
return opts
YES = -> true
isPrefix = (a, b) -> a[...b.length] is b
exports.ParserFactory = class ParserFactory
constructor: (@opts = {}) ->
createParser: (text) -> new Parser text, @opts
# ## Parser ##
# The Parser class is a simple
# wrapper on the above functions
# and a given parser function.
exports.Parser = class Parser
constructor: (@text, @opts = {}) ->
# Text can sometimes be subject to change
# when doing error recovery, so keep a record of
# the original text.
@originalText = @text
@markup = []
# ## parse ##
_parse: (opts, cachedParse) ->
opts = _extend opts, {
wrapAtRoot: true
preserveEmpty: true
}
# Generate the list of tokens
@markRoot opts.context, cachedParse
# Sort by position and depth
do @sortMarkup
# Generate a document from the markup
document = @applyMarkup opts
# Correct parent tree
document.correctParentTree()
# Add node context annotations from PreNodeContext
# annotations
head = document.start
until head is document.end
if head.type is 'blockStart' and head.container._preNodeContext?
head.container.nodeContext = head.container._preNodeContext.apply head.container
head = head.next
# Strip away blocks flagged to be removed
# (for `` hack and error recovery)
if opts.preserveEmpty
stripFlaggedBlocks document
return document
markRoot: ->
# ## addBlock ##
# addBlock takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# precedence: Number
# color: String
# socketLevel: Number
# parenWrapped: Boolean
# }
addBlock: (opts) ->
block = new model.Block opts.color,
opts.shape,
opts.parseContext,
null,
opts.buttons,
opts.data
block._preNodeContext = opts.nodeContext
@addMarkup block, opts.bounds, opts.depth
addButtonContainer: (opts) ->
container = new model.ButtonContainer opts.parseContext,
opts.buttons,
opts.data
@addMarkup container, opts.bounds, opts.depth
addLockedSocket: (opts) ->
container = new model.LockedSocket opts.parseContext,
opts.dropdown,
opts.data
@addMarkup container, opts.bounds, opts.depth
# flagToRemove, used for removing the placeholders that
# are placed when round-tripping empty sockets, so that, e.g. in CoffeeScript mode
# a + (empty socket) -> a + `` -> a + (empty socket).
#
# These are done by placing blocks around that text and then removing that block from the tree.
flagToRemove: (bounds, depth) ->
block = new model.Block()
block.flagToRemove = true
@addMarkup block, bounds, depth
# ## addSocket ##
# addSocket takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# precedence: Number
# accepts: shallow_dict
# }
addSocket: (opts) ->
socket = new model.Socket opts.empty ? @empty,
false,
opts.dropdown,
opts.parseContext
@addMarkup socket, opts.bounds, opts.depth
# ## addIndent ##
# addIndent takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# prefix: String
# }
addIndent: (opts) ->
indent = new model.Indent @emptyIndent, opts.prefix, opts.indentContext
@addMarkup indent, opts.bounds, opts.depth
checkBounds: (bounds) ->
if not (bounds?.start?.line? and bounds?.start?.column? and
bounds?.end?.line? and bounds?.end?.column?)
throw new IllegalArgumentException 'bad bounds object'
# ## addMarkup ##
# Add a container around some bounds
addMarkup: (container, bounds, depth) ->
@checkBounds bounds
@markup.push
token: container.start
location: bounds.start
depth: depth
start: true
@markup.push
token: container.end
location: bounds.end
depth: depth
start: false
return container
# ## sortMarkup ##
# Sort the markup by the order
# in which it will appear in the text.
sortMarkup: ->
@markup.sort (a, b) ->
# First by line
if a.location.line > b.location.line
return 1
if b.location.line > a.location.line
return -1
# Then by column
if a.location.column > b.location.column
return 1
if b.location.column > a.location.column
return -1
# If two pieces of markup are in the same position, end markup
# comes before start markup
isDifferent = 1
if a.token.container is b.token.container
isDifferent = -1
if a.start and not b.start
return isDifferent
if b.start and not a.start
return -isDifferent
# If two pieces of markup are in the same position,
# and are both start or end,
# the markup placed earlier gets to go on the outside
if a.start and b.start
if a.depth > b.depth
return 1
else return -1
if (not a.start) and (not b.start)
if a.depth > b.depth
return -1
else return 1
# ## constructHandwrittenBlock
# Construct a handwritten block with the given
# text inside
constructHandwrittenBlock: (text) ->
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
if @isComment text
head = block.start
{sockets, color} = @parseComment(text)
if color?
block.color = color
lastPosition = 0
if sockets?
for socketPosition in sockets
socket = new model.Socket '', false, null, '__comment__'
socket.setParent block
padText = text[lastPosition...socketPosition[0]]
if padText.length > 0
padTextToken = new model.TextToken padText
padTextToken.setParent block
helper.connect head, padTextToken
head = padTextToken
textToken = new model.TextToken text[socketPosition[0]...socketPosition[1]]
textToken.setParent block
helper.connect head, socket.start
helper.connect socket.start, textToken
helper.connect textToken, socket.end
head = socket.end
lastPosition = socketPosition[1]
finalPadText = text[lastPosition...text.length]
if finalPadText.length > 0
finalPadTextToken = new model.TextToken finalPadText
finalPadTextToken.setParent block
helper.connect head, finalPadTextToken
head = finalPadTextToken
helper.connect head, block.end
else
socket = new model.Socket '', true
textToken = new model.TextToken text
textToken.setParent socket
block.shape = helper.BLOCK_ONLY
helper.connect block.start, socket.start
helper.connect socket.start, textToken
helper.connect textToken, socket.end
helper.connect socket.end, block.end
return block
handleButton: (text, command, oldblock) ->
return text
# applyMarkup
# -----------
#
# The parser adapter will throw out markup in arbitrary orders. `applyMarkup`'s job is to assemble
# a parse tree from this markup. `applyMarkup` also cleans up any leftover text that lies outside blocks or
# sockets by passing them through a comment-handling procedure.
#
# `applyMarkup` applies the generated markup by sorting it, then walking from the beginning to the end of the
# document, creating `TextToken`s and inserting the markup between them. It also keeps a stack
# of which containers it is currently in, for error detection and comment handling.
#
# Whenever the container is currently an `Indent` or a `Document` and we get some text, we handle it as a comment.
# If it contains block-comment tokens, like /* or */, we immediately make comment blocks around them, amalgamating multiline comments
# into single blocks. We do this by scanning forward and just toggling on or off a bit that says whether we're inside
# a block comment, refusing to put any markup while we're inside one.
#
# When outside a block-comment, we pass free text to the mode's comment parser. This comment parser
# will return a set of text ranges to put in sockets, usually the place where freeform text can be put in the comment.
# For instance, `//hello` in JavaScript should return (2, 6) to put a socket around 'hello'. In C, this is used
# to handle preprocessor directives.
applyMarkup: (opts) ->
# For convenience, will we
# separate the markup by the line on which it is placed.
markupOnLines = {}
for mark in @markup
markupOnLines[mark.location.line] ?= []
markupOnLines[mark.location.line].push mark
# Now, we will interact with the text
# by line-column coordinates. So we first want
# to split the text into lines.
lines = @text.split '\n'
indentDepth = 0
stack = []
document = new model.Document(opts.context ? @rootContext); head = document.start
currentlyCommented = false
for line, i in lines
# If there is no markup on this line,
# helper.connect simply, the text of this line to the document
# (stripping things as needed for indent)
if not (i of markupOnLines)
# If this line is not properly indented,
# flag it in the model.
if indentDepth > line.length or line[...indentDepth].trim().length > 0
head.specialIndent = (' ' for [0...line.length - line.trimLeft().length]).join ''
line = line.trimLeft()
else
line = line[indentDepth...]
# If we have some text here that
# is floating (not surrounded by a block),
# wrap it in a generic block automatically.
#
# We will also send it through a pass through a comment parser here,
# for special handling of different forms of comments (or, e.g. in C mode, directives),
# and amalgamate multiline comments.
placedSomething = false
while line.length > 0
if currentlyCommented
placedSomething = true
if line.indexOf(@endComment) > -1
head = helper.connect head,
new model.TextToken line[...line.indexOf(@endComment) + @endComment.length]
line = line[line.indexOf(@endComment) + @endComment.length...]
head = helper.connect head, stack.pop().end
currentlyCommented = false
if not currentlyCommented and
((opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent') and
line.length > 0
placedSomething = true
if isPrefix(line.trimLeft(), @startComment)
currentlyCommented = true
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
stack.push block
helper.connect head, block.start
head = block.start
else
block = @constructHandwrittenBlock line
helper.connect head, block.start
head = block.end
line = ''
else if line.length > 0
placedSomething = true
head = helper.connect head, new model.TextToken line
line = ''
if line.length is 0 and not placedSomething and stack[stack.length - 1]?.type in ['indent', 'document', undefined] and
hasSomeTextAfter(lines, i)
block = new model.Block @opts.emptyLineColor, helper.BLOCK_ONLY, '__comment__'
head = helper.connect head, block.start
head = helper.connect head, block.end
head = helper.connect head, new model.NewlineToken()
# If there is markup on this line, insert it.
else
# Flag if this line is not properly indented.
if indentDepth > line.length or line[...indentDepth].trim().length > 0
lastIndex = line.length - line.trimLeft().length
head.specialIndent = line[0...lastIndex]
else
lastIndex = indentDepth
for mark in markupOnLines[i]
# If flagToRemove is turned off, ignore markup
# that was generated by the flagToRemove mechanism. This will simply
# create text tokens instead of creating a block slated to be removed.
continue if mark.token.container? and mark.token.container.flagToRemove and not opts.preserveEmpty
# Insert a text token for all the text up until this markup
# (unless there is no such text
unless lastIndex >= mark.location.column or lastIndex >= line.length
if (not currentlyCommented) and
(opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent'
block = @constructHandwrittenBlock line[lastIndex...mark.location.column]
helper.connect head, block.start
head = block.end
else
head = helper.connect head, new model.TextToken(line[lastIndex...mark.location.column])
if currentlyCommented
head = helper.connect head, stack.pop().end
currentlyCommented = false
# Note, if we have inserted something,
# the new indent depth and the new stack.
switch mark.token.type
when 'indentStart'
# An Indent is only allowed to be
# directly inside a block; if not, then throw.
unless stack?[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: indent must be inside block, but is inside ' + stack?[stack.length - 1]?.type
indentDepth += mark.token.container.prefix.length
when 'blockStart'
# If the a block is embedded
# directly in another block, throw.
if stack[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: block cannot nest immediately inside another block.'
when 'socketStart'
# A socket is only allowed to be directly inside a block.
unless stack[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: socket must be immediately inside a block.'
when 'indentEnd'
indentDepth -= mark.token.container.prefix.length
# Update the stack
if mark.token instanceof model.StartToken
stack.push mark.token.container
else if mark.token instanceof model.EndToken
unless mark.token.container is stack[stack.length - 1]
throw new Error "Improper parser: #{head.container.type} ended too early."
stack.pop()
# Append the token
head = helper.connect head, mark.token
lastIndex = mark.location.column
# Append the rest of the string
# (after the last piece of markup)
until lastIndex >= line.length
if currentlyCommented
if line[lastIndex...].indexOf(@endComment) > -1
head = helper.connect head,
new model.TextToken line[lastIndex...lastIndex + line[lastIndex...].indexOf(@endComment) + @endComment.length]
lastIndex += line[lastIndex...].indexOf(@endComment) + @endComment.length
head = helper.connect head, stack.pop().end
currentlyCommented = false
if not currentlyCommented and
((opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent') and
line.length > 0
if isPrefix(line[lastIndex...].trimLeft(), @startComment)
currentlyCommented = true
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
stack.push block
helper.connect head, block.start
head = block.start
else
block = @constructHandwrittenBlock line[lastIndex...]
helper.connect head, block.start
head = block.end
lastIndex = line.length
else if lastIndex < line.length
head = helper.connect head, new model.TextToken line[lastIndex...]
lastIndex = line.length
head = helper.connect head, new model.NewlineToken()
# Pop off the last newline token, which is not necessary
head = head.prev
head.next.remove()
# Reinsert the end token of the document,
# which we previously threw away by using "connect"
head = helper.connect head, document.end
# Return the document
return document
exports.parseXML = (xml) ->
root = new model.Document(); head = root.start
stack = []
parser = sax.parser true
parser.ontext = (text) ->
tokens = text.split '\n'
for token, i in tokens
unless token.length is 0
head = helper.connect head, new model.TextToken token
unless i is tokens.length - 1
head = helper.connect head, new model.NewlineToken()
# TODO Improve serialization format
# for test updates. Currently no longer unity
# because @empty is not preserved.
parser.onopentag = (node) ->
attributes = node.attributes
switch node.name
when 'block'
container = new model.Block attributes.color,
attributes.shape, attributes.parseContext
when 'socket'
container = new model.Socket '', attributes.handritten, attributes.parseContext
when 'indent'
container = new model.Indent '', attributes.prefix, attributes.indentContext
when 'document'
# Root is optional
unless stack.length is 0
container = new model.Document()
when 'br'
head = helper.connect head, new model.NewlineToken()
return null
if container?
stack.push {
node: node
container: container
}
head = helper.connect head, container.start
parser.onclosetag = (nodeName) ->
if stack.length > 0 and nodeName is stack[stack.length - 1].node.name
head = helper.connect head, stack[stack.length - 1].container.end
stack.pop()
parser.onerror = (e) ->
throw e
parser.write(xml).close()
head = helper.connect head, root.end
root.correctParentTree()
return root
hasSomeTextAfter = (lines, i) ->
until i is lines.length
if lines[i].length > 0 then return true
i += 1
return false
# ## applyMarkup ##
# Given some text and (sorted) markup,
# produce an ICE editor document
# with the markup inserted into the text.
#
# Automatically insert sockets around blocks along the way.
stripFlaggedBlocks = (document) ->
head = document.start
until head is document.end
if (head instanceof model.StartToken and
head.container.flagToRemove)
container = head.container
head = container.end.next
document.remove container
else if (head instanceof model.StartToken and
head.container.flagToStrip)
head.container.parent?.color = 'error'
text = head.next
text.value =
text.value.substring(
head.container.flagToStrip.left,
text.value.length - head.container.flagToStrip.right)
head = text.next
else
head = head.next
Parser.parens = (leading, trailing, node, context) ->
Parser.drop = (block, context, pred, next) ->
if block.type is 'document' and context.type is 'socket'
return helper.FORBID
else
return helper.ENCOURAGE
Parser.empty = ''
Parser.emptyIndent = ''
getDefaultSelectionRange = (string) -> {start: 0, end: string.length}
exports.wrapParser = (CustomParser) ->
class CustomParserFactory extends ParserFactory
constructor: (@opts = {}) ->
@empty = CustomParser.empty
@emptyIndent = CustomParser.emptyIndent
@startComment = CustomParser.startComment ? '/*'
@endComment = CustomParser.endComment ? '*/'
@rootContext = CustomParser.rootContext
@startSingleLineComment = CustomParser.startSingleLineComment
@getDefaultSelectionRange = CustomParser.getDefaultSelectionRange ? getDefaultSelectionRange
@getParenCandidates = CustomParser.getParenCandidates
lockedSocketCallback: (socketText, blockText, parseContext) ->
if CustomParser.lockedSocketCallback?
return CustomParser.lockedSocketCallback @opts, socketText, blockText, parseContext
else
return blockText
# TODO kind of hacky assignation of @empty,
# maybe change the api?
createParser: (text) ->
parser = new CustomParser text, @opts
parser.startComment = @startComment
parser.endComment = @endComment
parser.empty = @empty
parser.emptyIndent = @emptyIndent
parser.rootContext = @rootContext
return parser
stringFixer: (string) ->
if CustomParser.stringFixer?
CustomParser.stringFixer.apply @, arguments
else
return string
preparse: (text, context) ->
return @createParser(text).preparse context
parse: (text, opts, cachedParse = null) ->
@opts.parseOptions = opts
opts ?= wrapAtRoot: true
return @createParser(text)._parse opts, cachedParse
parens: (leading, trailing, node, context) ->
# We do this function thing so that if leading and trailing are the same
# (i.e. there is only one text token), parser adapter functions can still treat
# it as if they are two different things.
# leadingFn is always a getter/setter for leading
leadingFn = (value) ->
if value?
leading = value
return leading
# trailingFn may either get/set leading or trailing;
# will point to leading if leading is the only token,
# but will point to trailing otherwise.
if trailing?
trailingFn = (value) ->
if value?
trailing = value
return trailing
else
trailingFn = leadingFn
context = CustomParser.parens leadingFn, trailingFn, node, context
return [leading, trailing, context]
drop: (block, context, pred, next) -> CustomParser.drop block, context, pred, next
handleButton: (text, command, oldblock) ->
parser = @createParser(text)
parser.handleButton text, command, oldblock
| true | # Droplet parser wrapper.
# Utility functions for defining Droplet parsers.
#
# Copyright (c) 2015 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# MIT License
helper = require './helper.coffee'
model = require './model.coffee'
exports.PreNodeContext = class PreNodeContext
constructor: (@type, @preParenLength, @postParenLength) ->
apply: (node) ->
trailingText = node.getTrailingText()
trailingText = trailingText[0...trailingText.length - @postParenLength]
leadingText = node.getLeadingText()
leadingText = leadingText[@preParenLength...leadingText.length]
return new model.NodeContext @type, leadingText, trailingText
sax = require 'sax'
_extend = (opts, defaults) ->
unless opts? then return defaults
for key, val of defaults
unless key of opts
opts[key] = val
return opts
YES = -> true
isPrefix = (a, b) -> a[...b.length] is b
exports.ParserFactory = class ParserFactory
constructor: (@opts = {}) ->
createParser: (text) -> new Parser text, @opts
# ## Parser ##
# The Parser class is a simple
# wrapper on the above functions
# and a given parser function.
exports.Parser = class Parser
constructor: (@text, @opts = {}) ->
# Text can sometimes be subject to change
# when doing error recovery, so keep a record of
# the original text.
@originalText = @text
@markup = []
# ## parse ##
_parse: (opts, cachedParse) ->
opts = _extend opts, {
wrapAtRoot: true
preserveEmpty: true
}
# Generate the list of tokens
@markRoot opts.context, cachedParse
# Sort by position and depth
do @sortMarkup
# Generate a document from the markup
document = @applyMarkup opts
# Correct parent tree
document.correctParentTree()
# Add node context annotations from PreNodeContext
# annotations
head = document.start
until head is document.end
if head.type is 'blockStart' and head.container._preNodeContext?
head.container.nodeContext = head.container._preNodeContext.apply head.container
head = head.next
# Strip away blocks flagged to be removed
# (for `` hack and error recovery)
if opts.preserveEmpty
stripFlaggedBlocks document
return document
markRoot: ->
# ## addBlock ##
# addBlock takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# precedence: Number
# color: String
# socketLevel: Number
# parenWrapped: Boolean
# }
addBlock: (opts) ->
block = new model.Block opts.color,
opts.shape,
opts.parseContext,
null,
opts.buttons,
opts.data
block._preNodeContext = opts.nodeContext
@addMarkup block, opts.bounds, opts.depth
addButtonContainer: (opts) ->
container = new model.ButtonContainer opts.parseContext,
opts.buttons,
opts.data
@addMarkup container, opts.bounds, opts.depth
addLockedSocket: (opts) ->
container = new model.LockedSocket opts.parseContext,
opts.dropdown,
opts.data
@addMarkup container, opts.bounds, opts.depth
# flagToRemove, used for removing the placeholders that
# are placed when round-tripping empty sockets, so that, e.g. in CoffeeScript mode
# a + (empty socket) -> a + `` -> a + (empty socket).
#
# These are done by placing blocks around that text and then removing that block from the tree.
flagToRemove: (bounds, depth) ->
block = new model.Block()
block.flagToRemove = true
@addMarkup block, bounds, depth
# ## addSocket ##
# addSocket takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# precedence: Number
# accepts: shallow_dict
# }
addSocket: (opts) ->
socket = new model.Socket opts.empty ? @empty,
false,
opts.dropdown,
opts.parseContext
@addMarkup socket, opts.bounds, opts.depth
# ## addIndent ##
# addIndent takes {
# bounds: {
# start: {line, column}
# end: {line, column}
# }
# depth: Number
# prefix: String
# }
addIndent: (opts) ->
indent = new model.Indent @emptyIndent, opts.prefix, opts.indentContext
@addMarkup indent, opts.bounds, opts.depth
checkBounds: (bounds) ->
if not (bounds?.start?.line? and bounds?.start?.column? and
bounds?.end?.line? and bounds?.end?.column?)
throw new IllegalArgumentException 'bad bounds object'
# ## addMarkup ##
# Add a container around some bounds
addMarkup: (container, bounds, depth) ->
@checkBounds bounds
@markup.push
token: container.start
location: bounds.start
depth: depth
start: true
@markup.push
token: container.end
location: bounds.end
depth: depth
start: false
return container
# ## sortMarkup ##
# Sort the markup by the order
# in which it will appear in the text.
sortMarkup: ->
@markup.sort (a, b) ->
# First by line
if a.location.line > b.location.line
return 1
if b.location.line > a.location.line
return -1
# Then by column
if a.location.column > b.location.column
return 1
if b.location.column > a.location.column
return -1
# If two pieces of markup are in the same position, end markup
# comes before start markup
isDifferent = 1
if a.token.container is b.token.container
isDifferent = -1
if a.start and not b.start
return isDifferent
if b.start and not a.start
return -isDifferent
# If two pieces of markup are in the same position,
# and are both start or end,
# the markup placed earlier gets to go on the outside
if a.start and b.start
if a.depth > b.depth
return 1
else return -1
if (not a.start) and (not b.start)
if a.depth > b.depth
return -1
else return 1
# ## constructHandwrittenBlock
# Construct a handwritten block with the given
# text inside
constructHandwrittenBlock: (text) ->
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
if @isComment text
head = block.start
{sockets, color} = @parseComment(text)
if color?
block.color = color
lastPosition = 0
if sockets?
for socketPosition in sockets
socket = new model.Socket '', false, null, '__comment__'
socket.setParent block
padText = text[lastPosition...socketPosition[0]]
if padText.length > 0
padTextToken = new model.TextToken padText
padTextToken.setParent block
helper.connect head, padTextToken
head = padTextToken
textToken = new model.TextToken text[socketPosition[0]...socketPosition[1]]
textToken.setParent block
helper.connect head, socket.start
helper.connect socket.start, textToken
helper.connect textToken, socket.end
head = socket.end
lastPosition = socketPosition[1]
finalPadText = text[lastPosition...text.length]
if finalPadText.length > 0
finalPadTextToken = new model.TextToken finalPadText
finalPadTextToken.setParent block
helper.connect head, finalPadTextToken
head = finalPadTextToken
helper.connect head, block.end
else
socket = new model.Socket '', true
textToken = new model.TextToken text
textToken.setParent socket
block.shape = helper.BLOCK_ONLY
helper.connect block.start, socket.start
helper.connect socket.start, textToken
helper.connect textToken, socket.end
helper.connect socket.end, block.end
return block
handleButton: (text, command, oldblock) ->
return text
# applyMarkup
# -----------
#
# The parser adapter will throw out markup in arbitrary orders. `applyMarkup`'s job is to assemble
# a parse tree from this markup. `applyMarkup` also cleans up any leftover text that lies outside blocks or
# sockets by passing them through a comment-handling procedure.
#
# `applyMarkup` applies the generated markup by sorting it, then walking from the beginning to the end of the
# document, creating `TextToken`s and inserting the markup between them. It also keeps a stack
# of which containers it is currently in, for error detection and comment handling.
#
# Whenever the container is currently an `Indent` or a `Document` and we get some text, we handle it as a comment.
# If it contains block-comment tokens, like /* or */, we immediately make comment blocks around them, amalgamating multiline comments
# into single blocks. We do this by scanning forward and just toggling on or off a bit that says whether we're inside
# a block comment, refusing to put any markup while we're inside one.
#
# When outside a block-comment, we pass free text to the mode's comment parser. This comment parser
# will return a set of text ranges to put in sockets, usually the place where freeform text can be put in the comment.
# For instance, `//hello` in JavaScript should return (2, 6) to put a socket around 'hello'. In C, this is used
# to handle preprocessor directives.
applyMarkup: (opts) ->
# For convenience, will we
# separate the markup by the line on which it is placed.
markupOnLines = {}
for mark in @markup
markupOnLines[mark.location.line] ?= []
markupOnLines[mark.location.line].push mark
# Now, we will interact with the text
# by line-column coordinates. So we first want
# to split the text into lines.
lines = @text.split '\n'
indentDepth = 0
stack = []
document = new model.Document(opts.context ? @rootContext); head = document.start
currentlyCommented = false
for line, i in lines
# If there is no markup on this line,
# helper.connect simply, the text of this line to the document
# (stripping things as needed for indent)
if not (i of markupOnLines)
# If this line is not properly indented,
# flag it in the model.
if indentDepth > line.length or line[...indentDepth].trim().length > 0
head.specialIndent = (' ' for [0...line.length - line.trimLeft().length]).join ''
line = line.trimLeft()
else
line = line[indentDepth...]
# If we have some text here that
# is floating (not surrounded by a block),
# wrap it in a generic block automatically.
#
# We will also send it through a pass through a comment parser here,
# for special handling of different forms of comments (or, e.g. in C mode, directives),
# and amalgamate multiline comments.
placedSomething = false
while line.length > 0
if currentlyCommented
placedSomething = true
if line.indexOf(@endComment) > -1
head = helper.connect head,
new model.TextToken line[...line.indexOf(@endComment) + @endComment.length]
line = line[line.indexOf(@endComment) + @endComment.length...]
head = helper.connect head, stack.pop().end
currentlyCommented = false
if not currentlyCommented and
((opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent') and
line.length > 0
placedSomething = true
if isPrefix(line.trimLeft(), @startComment)
currentlyCommented = true
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
stack.push block
helper.connect head, block.start
head = block.start
else
block = @constructHandwrittenBlock line
helper.connect head, block.start
head = block.end
line = ''
else if line.length > 0
placedSomething = true
head = helper.connect head, new model.TextToken line
line = ''
if line.length is 0 and not placedSomething and stack[stack.length - 1]?.type in ['indent', 'document', undefined] and
hasSomeTextAfter(lines, i)
block = new model.Block @opts.emptyLineColor, helper.BLOCK_ONLY, '__comment__'
head = helper.connect head, block.start
head = helper.connect head, block.end
head = helper.connect head, new model.NewlineToken()
# If there is markup on this line, insert it.
else
# Flag if this line is not properly indented.
if indentDepth > line.length or line[...indentDepth].trim().length > 0
lastIndex = line.length - line.trimLeft().length
head.specialIndent = line[0...lastIndex]
else
lastIndex = indentDepth
for mark in markupOnLines[i]
# If flagToRemove is turned off, ignore markup
# that was generated by the flagToRemove mechanism. This will simply
# create text tokens instead of creating a block slated to be removed.
continue if mark.token.container? and mark.token.container.flagToRemove and not opts.preserveEmpty
# Insert a text token for all the text up until this markup
# (unless there is no such text
unless lastIndex >= mark.location.column or lastIndex >= line.length
if (not currentlyCommented) and
(opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent'
block = @constructHandwrittenBlock line[lastIndex...mark.location.column]
helper.connect head, block.start
head = block.end
else
head = helper.connect head, new model.TextToken(line[lastIndex...mark.location.column])
if currentlyCommented
head = helper.connect head, stack.pop().end
currentlyCommented = false
# Note, if we have inserted something,
# the new indent depth and the new stack.
switch mark.token.type
when 'indentStart'
# An Indent is only allowed to be
# directly inside a block; if not, then throw.
unless stack?[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: indent must be inside block, but is inside ' + stack?[stack.length - 1]?.type
indentDepth += mark.token.container.prefix.length
when 'blockStart'
# If the a block is embedded
# directly in another block, throw.
if stack[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: block cannot nest immediately inside another block.'
when 'socketStart'
# A socket is only allowed to be directly inside a block.
unless stack[stack.length - 1]?.type in ['block', 'buttonContainer']
throw new Error 'Improper parser: socket must be immediately inside a block.'
when 'indentEnd'
indentDepth -= mark.token.container.prefix.length
# Update the stack
if mark.token instanceof model.StartToken
stack.push mark.token.container
else if mark.token instanceof model.EndToken
unless mark.token.container is stack[stack.length - 1]
throw new Error "Improper parser: #{head.container.type} ended too early."
stack.pop()
# Append the token
head = helper.connect head, mark.token
lastIndex = mark.location.column
# Append the rest of the string
# (after the last piece of markup)
until lastIndex >= line.length
if currentlyCommented
if line[lastIndex...].indexOf(@endComment) > -1
head = helper.connect head,
new model.TextToken line[lastIndex...lastIndex + line[lastIndex...].indexOf(@endComment) + @endComment.length]
lastIndex += line[lastIndex...].indexOf(@endComment) + @endComment.length
head = helper.connect head, stack.pop().end
currentlyCommented = false
if not currentlyCommented and
((opts.wrapAtRoot and stack.length is 0) or stack[stack.length - 1]?.type is 'indent') and
line.length > 0
if isPrefix(line[lastIndex...].trimLeft(), @startComment)
currentlyCommented = true
block = new model.Block 'comment', helper.ANY_DROP, '__comment__'
stack.push block
helper.connect head, block.start
head = block.start
else
block = @constructHandwrittenBlock line[lastIndex...]
helper.connect head, block.start
head = block.end
lastIndex = line.length
else if lastIndex < line.length
head = helper.connect head, new model.TextToken line[lastIndex...]
lastIndex = line.length
head = helper.connect head, new model.NewlineToken()
# Pop off the last newline token, which is not necessary
head = head.prev
head.next.remove()
# Reinsert the end token of the document,
# which we previously threw away by using "connect"
head = helper.connect head, document.end
# Return the document
return document
exports.parseXML = (xml) ->
root = new model.Document(); head = root.start
stack = []
parser = sax.parser true
parser.ontext = (text) ->
tokens = text.split '\n'
for token, i in tokens
unless token.length is 0
head = helper.connect head, new model.TextToken token
unless i is tokens.length - 1
head = helper.connect head, new model.NewlineToken()
# TODO Improve serialization format
# for test updates. Currently no longer unity
# because @empty is not preserved.
parser.onopentag = (node) ->
attributes = node.attributes
switch node.name
when 'block'
container = new model.Block attributes.color,
attributes.shape, attributes.parseContext
when 'socket'
container = new model.Socket '', attributes.handritten, attributes.parseContext
when 'indent'
container = new model.Indent '', attributes.prefix, attributes.indentContext
when 'document'
# Root is optional
unless stack.length is 0
container = new model.Document()
when 'br'
head = helper.connect head, new model.NewlineToken()
return null
if container?
stack.push {
node: node
container: container
}
head = helper.connect head, container.start
parser.onclosetag = (nodeName) ->
if stack.length > 0 and nodeName is stack[stack.length - 1].node.name
head = helper.connect head, stack[stack.length - 1].container.end
stack.pop()
parser.onerror = (e) ->
throw e
parser.write(xml).close()
head = helper.connect head, root.end
root.correctParentTree()
return root
hasSomeTextAfter = (lines, i) ->
until i is lines.length
if lines[i].length > 0 then return true
i += 1
return false
# ## applyMarkup ##
# Given some text and (sorted) markup,
# produce an ICE editor document
# with the markup inserted into the text.
#
# Automatically insert sockets around blocks along the way.
stripFlaggedBlocks = (document) ->
head = document.start
until head is document.end
if (head instanceof model.StartToken and
head.container.flagToRemove)
container = head.container
head = container.end.next
document.remove container
else if (head instanceof model.StartToken and
head.container.flagToStrip)
head.container.parent?.color = 'error'
text = head.next
text.value =
text.value.substring(
head.container.flagToStrip.left,
text.value.length - head.container.flagToStrip.right)
head = text.next
else
head = head.next
Parser.parens = (leading, trailing, node, context) ->
Parser.drop = (block, context, pred, next) ->
if block.type is 'document' and context.type is 'socket'
return helper.FORBID
else
return helper.ENCOURAGE
Parser.empty = ''
Parser.emptyIndent = ''
getDefaultSelectionRange = (string) -> {start: 0, end: string.length}
exports.wrapParser = (CustomParser) ->
class CustomParserFactory extends ParserFactory
constructor: (@opts = {}) ->
@empty = CustomParser.empty
@emptyIndent = CustomParser.emptyIndent
@startComment = CustomParser.startComment ? '/*'
@endComment = CustomParser.endComment ? '*/'
@rootContext = CustomParser.rootContext
@startSingleLineComment = CustomParser.startSingleLineComment
@getDefaultSelectionRange = CustomParser.getDefaultSelectionRange ? getDefaultSelectionRange
@getParenCandidates = CustomParser.getParenCandidates
lockedSocketCallback: (socketText, blockText, parseContext) ->
if CustomParser.lockedSocketCallback?
return CustomParser.lockedSocketCallback @opts, socketText, blockText, parseContext
else
return blockText
# TODO kind of hacky assignation of @empty,
# maybe change the api?
createParser: (text) ->
parser = new CustomParser text, @opts
parser.startComment = @startComment
parser.endComment = @endComment
parser.empty = @empty
parser.emptyIndent = @emptyIndent
parser.rootContext = @rootContext
return parser
stringFixer: (string) ->
if CustomParser.stringFixer?
CustomParser.stringFixer.apply @, arguments
else
return string
preparse: (text, context) ->
return @createParser(text).preparse context
parse: (text, opts, cachedParse = null) ->
@opts.parseOptions = opts
opts ?= wrapAtRoot: true
return @createParser(text)._parse opts, cachedParse
parens: (leading, trailing, node, context) ->
# We do this function thing so that if leading and trailing are the same
# (i.e. there is only one text token), parser adapter functions can still treat
# it as if they are two different things.
# leadingFn is always a getter/setter for leading
leadingFn = (value) ->
if value?
leading = value
return leading
# trailingFn may either get/set leading or trailing;
# will point to leading if leading is the only token,
# but will point to trailing otherwise.
if trailing?
trailingFn = (value) ->
if value?
trailing = value
return trailing
else
trailingFn = leadingFn
context = CustomParser.parens leadingFn, trailingFn, node, context
return [leading, trailing, context]
drop: (block, context, pred, next) -> CustomParser.drop block, context, pred, next
handleButton: (text, command, oldblock) ->
parser = @createParser(text)
parser.handleButton text, command, oldblock
|
[
{
"context": " item.property\n title: title\n author: author\n journal: journal\n \n try\n await",
"end": 2631,
"score": 0.8763895034790039,
"start": 2625,
"tag": "NAME",
"value": "author"
}
] | coffees/route-readingjournals.coffee | android1and1/easti | 0 | fs = require 'fs'
pug = require 'pug'
path = require 'path'
express = require 'express'
router = express.Router()
#formidable = require 'formidable'
Redis = require 'redis'
RT = require '../modules/md-readingjournals'
# for debug target
Nohm = require 'nohm'
# client not to connect this time.
[nohm1,nohm2] = [Nohm.Nohm,Nohm.Nohm]
[nohm1,nohm2].forEach (itisnohm)->
# now we have 2 redis clients.
redis= Redis.createClient()
redis.on 'error',(err)->
console.log 'debug info::route-readingjournals::',err.message
redis.on 'connect',->
itisnohm.setClient redis
# another route - /neighborCar use redis-server,so,they should in same name space:'gaikai'
itisnohm.setPrefix 'gaikai'
router.get '/',(req,res,next)->
schema = nohm1.register RT
# top10
allids = await schema.sort {'field':'visits','direction':'DESC','limit':[0,10]}
allitems = await schema.loadMany allids
alljournals = []
for item in allitems
alljournals.push item.allProperties()
res.render 'readingjournals/index',{title:'App Title','alljournals':alljournals}
router.get '/search-via-id/:id',(req,res,next)->
schema = ins.register RT
try
items = await schema.findAndLoad
timestamp:1412121600000
visits:
min:1
max:'+inf'
resultArray = []
for item in items
resultArray.push item.id + '#' + item.property 'title'
res.json {results: resultArray}
catch error
res.json {results:''}
router.post '/delete/:id',(req,res,next)->
schema = nohm1.register RT
# at a list page,each item has button named 'Delete It'
thisid = req.params.id
try
thisins = await schema.load thisid
thisins.remove().then ->
res.json {status:'delete-ok'}
catch error
res.json {status:'delete-error',error:error.message}
router.get '/sample-mod2form',(req,res,next)->
opts = RT.definitions
url = 'http://www.fellow5.cn'
snippet = pug.render RT.mod2form(),{opts:opts,url:url}
res.render 'readingjournals/tianna',{snippet:snippet}
# add
router.all '/add',(req,res,next)->
if req.method is 'POST'
schema = nohm2.register RT
item = await nohm2.factory RT.modelName
{title,author,visits,reading_history,tag,timestamp,journal} = req.body
# TODO check if value == '',let is abey default value defined in schema.
if visits isnt ''
item.property 'visits',visits
if tag isnt ''
item.property 'tag',tag
if timestamp isnt ''
item.property 'timestamp',timestamp
if reading_history isnt ''
item.property 'reading_history',reading_history
item.property
title: title
author: author
journal: journal
try
await item.save silence:true
res.json {status:'ok'}
catch error
if error instanceof Nohm.ValidationError
console.log 'validation error during save().,reason is',error.errors
else
console.log error.message
res.json {status:'error',reason:'no save,check abouts.'}
else # this case is method : 'GET'
opts = RT.definitions
url = '/reading-journals/add'
snippet = pug.render RT.mod2form(),{opts:opts,url:url}
res.render 'readingjournals/add.pug',{snippet:snippet}
rjFactory = (app)->
(pathname)->
app.use pathname,router
module.exports = rjFactory
| 47614 | fs = require 'fs'
pug = require 'pug'
path = require 'path'
express = require 'express'
router = express.Router()
#formidable = require 'formidable'
Redis = require 'redis'
RT = require '../modules/md-readingjournals'
# for debug target
Nohm = require 'nohm'
# client not to connect this time.
[nohm1,nohm2] = [Nohm.Nohm,Nohm.Nohm]
[nohm1,nohm2].forEach (itisnohm)->
# now we have 2 redis clients.
redis= Redis.createClient()
redis.on 'error',(err)->
console.log 'debug info::route-readingjournals::',err.message
redis.on 'connect',->
itisnohm.setClient redis
# another route - /neighborCar use redis-server,so,they should in same name space:'gaikai'
itisnohm.setPrefix 'gaikai'
router.get '/',(req,res,next)->
schema = nohm1.register RT
# top10
allids = await schema.sort {'field':'visits','direction':'DESC','limit':[0,10]}
allitems = await schema.loadMany allids
alljournals = []
for item in allitems
alljournals.push item.allProperties()
res.render 'readingjournals/index',{title:'App Title','alljournals':alljournals}
router.get '/search-via-id/:id',(req,res,next)->
schema = ins.register RT
try
items = await schema.findAndLoad
timestamp:1412121600000
visits:
min:1
max:'+inf'
resultArray = []
for item in items
resultArray.push item.id + '#' + item.property 'title'
res.json {results: resultArray}
catch error
res.json {results:''}
router.post '/delete/:id',(req,res,next)->
schema = nohm1.register RT
# at a list page,each item has button named 'Delete It'
thisid = req.params.id
try
thisins = await schema.load thisid
thisins.remove().then ->
res.json {status:'delete-ok'}
catch error
res.json {status:'delete-error',error:error.message}
router.get '/sample-mod2form',(req,res,next)->
opts = RT.definitions
url = 'http://www.fellow5.cn'
snippet = pug.render RT.mod2form(),{opts:opts,url:url}
res.render 'readingjournals/tianna',{snippet:snippet}
# add
router.all '/add',(req,res,next)->
if req.method is 'POST'
schema = nohm2.register RT
item = await nohm2.factory RT.modelName
{title,author,visits,reading_history,tag,timestamp,journal} = req.body
# TODO check if value == '',let is abey default value defined in schema.
if visits isnt ''
item.property 'visits',visits
if tag isnt ''
item.property 'tag',tag
if timestamp isnt ''
item.property 'timestamp',timestamp
if reading_history isnt ''
item.property 'reading_history',reading_history
item.property
title: title
author: <NAME>
journal: journal
try
await item.save silence:true
res.json {status:'ok'}
catch error
if error instanceof Nohm.ValidationError
console.log 'validation error during save().,reason is',error.errors
else
console.log error.message
res.json {status:'error',reason:'no save,check abouts.'}
else # this case is method : 'GET'
opts = RT.definitions
url = '/reading-journals/add'
snippet = pug.render RT.mod2form(),{opts:opts,url:url}
res.render 'readingjournals/add.pug',{snippet:snippet}
rjFactory = (app)->
(pathname)->
app.use pathname,router
module.exports = rjFactory
| true | fs = require 'fs'
pug = require 'pug'
path = require 'path'
express = require 'express'
router = express.Router()
#formidable = require 'formidable'
Redis = require 'redis'
RT = require '../modules/md-readingjournals'
# for debug target
Nohm = require 'nohm'
# client not to connect this time.
[nohm1,nohm2] = [Nohm.Nohm,Nohm.Nohm]
[nohm1,nohm2].forEach (itisnohm)->
# now we have 2 redis clients.
redis= Redis.createClient()
redis.on 'error',(err)->
console.log 'debug info::route-readingjournals::',err.message
redis.on 'connect',->
itisnohm.setClient redis
# another route - /neighborCar use redis-server,so,they should in same name space:'gaikai'
itisnohm.setPrefix 'gaikai'
router.get '/',(req,res,next)->
schema = nohm1.register RT
# top10
allids = await schema.sort {'field':'visits','direction':'DESC','limit':[0,10]}
allitems = await schema.loadMany allids
alljournals = []
for item in allitems
alljournals.push item.allProperties()
res.render 'readingjournals/index',{title:'App Title','alljournals':alljournals}
router.get '/search-via-id/:id',(req,res,next)->
schema = ins.register RT
try
items = await schema.findAndLoad
timestamp:1412121600000
visits:
min:1
max:'+inf'
resultArray = []
for item in items
resultArray.push item.id + '#' + item.property 'title'
res.json {results: resultArray}
catch error
res.json {results:''}
router.post '/delete/:id',(req,res,next)->
schema = nohm1.register RT
# at a list page,each item has button named 'Delete It'
thisid = req.params.id
try
thisins = await schema.load thisid
thisins.remove().then ->
res.json {status:'delete-ok'}
catch error
res.json {status:'delete-error',error:error.message}
router.get '/sample-mod2form',(req,res,next)->
opts = RT.definitions
url = 'http://www.fellow5.cn'
snippet = pug.render RT.mod2form(),{opts:opts,url:url}
res.render 'readingjournals/tianna',{snippet:snippet}
# add
router.all '/add',(req,res,next)->
if req.method is 'POST'
schema = nohm2.register RT
item = await nohm2.factory RT.modelName
{title,author,visits,reading_history,tag,timestamp,journal} = req.body
# TODO check if value == '',let is abey default value defined in schema.
if visits isnt ''
item.property 'visits',visits
if tag isnt ''
item.property 'tag',tag
if timestamp isnt ''
item.property 'timestamp',timestamp
if reading_history isnt ''
item.property 'reading_history',reading_history
item.property
title: title
author: PI:NAME:<NAME>END_PI
journal: journal
try
await item.save silence:true
res.json {status:'ok'}
catch error
if error instanceof Nohm.ValidationError
console.log 'validation error during save().,reason is',error.errors
else
console.log error.message
res.json {status:'error',reason:'no save,check abouts.'}
else # this case is method : 'GET'
opts = RT.definitions
url = '/reading-journals/add'
snippet = pug.render RT.mod2form(),{opts:opts,url:url}
res.render 'readingjournals/add.pug',{snippet:snippet}
rjFactory = (app)->
(pathname)->
app.use pathname,router
module.exports = rjFactory
|
[
{
"context": "object', ->\n items = [\n {name: 'bob'},\n {name: 'jane'},\n ]\n ",
"end": 2983,
"score": 0.9997705817222595,
"start": 2980,
"tag": "NAME",
"value": "bob"
},
{
"context": " [\n {name: 'bob'},\n {name: 'jan... | yacs/static/global/specs/utilities_spec.coffee | louy2/YACS | 10 | describe 'getCookie', ->
it 'should extract value from cookie string', ->
cookie = 'foo=bar;name=joe;rofl=coptor'
expect(getCookie('foo', cookie)).toEqual('bar')
expect(getCookie('name', cookie)).toEqual('joe')
expect(getCookie('rofl', cookie)).toEqual('coptor')
it 'should return null if no key exists in cookie string', ->
expect(getCookie('foo', '')).toBeNull()
describe 'product', ->
it 'should return an array with one empty array with no args', ->
expect(product()).toEqual([[]])
it 'should return an array with original array of possibilities', ->
expect(product([1, 2, 3])).toEqual([[1], [2], [3]])
it 'should create product with multiple arrays', ->
expect(product([1, 2, 3], [4, 5])).toEqual([
[1, 4],
[1, 5],
[2, 4],
[2, 5],
[3, 4],
[3, 5],
])
describe 'iterate', ->
it 'should loop over items asynchronously', ->
runs ->
@eachfn = jasmine.createSpy().andCallFake (item, index) ->
@i ?= 5
expect([index, item]).toEqual([@i - 5, @i])
@i++
@endfn = jasmine.createSpy().andCallFake ->
expect(@i).toEqual(10)
iterate([5..9], {
delay: 1
each: @eachfn
end: @endfn
})
waits(10)
runs ->
expect(@eachfn.callCount).toEqual(5)
expect(@endfn).toHaveBeenCalled()
it 'should be cancellable', ->
runs ->
@end = jasmine.createSpy()
job = iterate([0...5], {
delay: 1
each: jasmine.createSpy()
end: @end
})
job.abort()
waits(10)
runs ->
expect(@end.callCount).toEqual(0)
describe 'pushUnique', ->
it 'inserts item if it does not exist in the array and return true', ->
a = [1, 2, 3]
expect(pushUnique(a, 4)).toBeTruthy()
expect(a).toEqual([1, 2, 3, 4])
it 'does nothing if the item already exists in the array and return false', ->
a = [1, 2, 3]
expect(pushUnique(a, 2)).toBeFalsy()
expect(a).toEqual([1, 2, 3])
describe 'format', ->
it 'does nothing to format string only', ->
expect(format('foo {{ 0 }}')).toEqual('foo {{ 0 }}')
it 'formats based on positional arguments', ->
expect(format('foo {{ 0 }} {{ 1 }}', 'bar', 'cake')).toEqual('foo bar cake')
it 'formats even with undefined values', ->
expect(format('foo {{ 0 }} {{ 1 }}', undefined, null)).toEqual('foo <undefined> <null>')
it 'formats based on object hash', ->
expect(format('{{ hello }} {{ world }}', hello: 'goodbye', world: 'everyone')).toEqual('goodbye everyone')
describe 'hash_by_attr', ->
it 'can flatten array of objects to an object', ->
items = [
{name: 'bob'},
{name: 'jane'},
]
result = hash_by_attr(items, 'name', flat: true)
expect(result).toEqual(
bob: {name: 'bob'},
jane: {name: 'jane'}
)
it 'can categorize array of objects in to a hash', ->
items = [
{name: 'bob', id: 1},
{name: 'jane', id: 2},
{name: 'bob', id: 3},
]
result = hash_by_attr(items, 'name')
expect(result).toEqual(
bob: [
{name: 'bob', id: 1},
{name: 'bob', id: 3},
]
jane: [{name: 'jane', id: 2}]
)
it 'can use functions instead of keys', ->
items = [
{name: 'bob', id: 1},
{name: 'jane', id: 2},
{name: 'bob', id: 3},
]
result = hash_by_attr(items, ((o) -> o.name), value: (o) -> o.id)
expect(result).toEqual(
bob: [1, 3]
jane: [2]
)
describe 'barrier', ->
it 'invokes callback after number of invocations', ->
spy = jasmine.createSpy()
b = barrier(3, spy)
b()
b()
expect(spy.callCount).toEqual(0)
b()
expect(spy.callCount).toEqual(1)
it 'ignores further invocations', ->
spy = jasmine.createSpy()
b = barrier(1, spy)
for i in [0...50]
b()
expect(spy.callCount).toEqual(1)
describe 'array_of_ints', ->
it 'converts a sequence set of numbers into an array', ->
items = array_of_ints('1, 2,3, 04')
expect(items).toEqual([1, 2, 3, 4])
it 'returns empty array for empty string', ->
expect(array_of_ints('')).toEqual([])
| 19391 | describe 'getCookie', ->
it 'should extract value from cookie string', ->
cookie = 'foo=bar;name=joe;rofl=coptor'
expect(getCookie('foo', cookie)).toEqual('bar')
expect(getCookie('name', cookie)).toEqual('joe')
expect(getCookie('rofl', cookie)).toEqual('coptor')
it 'should return null if no key exists in cookie string', ->
expect(getCookie('foo', '')).toBeNull()
describe 'product', ->
it 'should return an array with one empty array with no args', ->
expect(product()).toEqual([[]])
it 'should return an array with original array of possibilities', ->
expect(product([1, 2, 3])).toEqual([[1], [2], [3]])
it 'should create product with multiple arrays', ->
expect(product([1, 2, 3], [4, 5])).toEqual([
[1, 4],
[1, 5],
[2, 4],
[2, 5],
[3, 4],
[3, 5],
])
describe 'iterate', ->
it 'should loop over items asynchronously', ->
runs ->
@eachfn = jasmine.createSpy().andCallFake (item, index) ->
@i ?= 5
expect([index, item]).toEqual([@i - 5, @i])
@i++
@endfn = jasmine.createSpy().andCallFake ->
expect(@i).toEqual(10)
iterate([5..9], {
delay: 1
each: @eachfn
end: @endfn
})
waits(10)
runs ->
expect(@eachfn.callCount).toEqual(5)
expect(@endfn).toHaveBeenCalled()
it 'should be cancellable', ->
runs ->
@end = jasmine.createSpy()
job = iterate([0...5], {
delay: 1
each: jasmine.createSpy()
end: @end
})
job.abort()
waits(10)
runs ->
expect(@end.callCount).toEqual(0)
describe 'pushUnique', ->
it 'inserts item if it does not exist in the array and return true', ->
a = [1, 2, 3]
expect(pushUnique(a, 4)).toBeTruthy()
expect(a).toEqual([1, 2, 3, 4])
it 'does nothing if the item already exists in the array and return false', ->
a = [1, 2, 3]
expect(pushUnique(a, 2)).toBeFalsy()
expect(a).toEqual([1, 2, 3])
describe 'format', ->
it 'does nothing to format string only', ->
expect(format('foo {{ 0 }}')).toEqual('foo {{ 0 }}')
it 'formats based on positional arguments', ->
expect(format('foo {{ 0 }} {{ 1 }}', 'bar', 'cake')).toEqual('foo bar cake')
it 'formats even with undefined values', ->
expect(format('foo {{ 0 }} {{ 1 }}', undefined, null)).toEqual('foo <undefined> <null>')
it 'formats based on object hash', ->
expect(format('{{ hello }} {{ world }}', hello: 'goodbye', world: 'everyone')).toEqual('goodbye everyone')
describe 'hash_by_attr', ->
it 'can flatten array of objects to an object', ->
items = [
{name: '<NAME>'},
{name: '<NAME>'},
]
result = hash_by_attr(items, 'name', flat: true)
expect(result).toEqual(
bob: {name: '<NAME>'},
<NAME>: {name: '<NAME>'}
)
it 'can categorize array of objects in to a hash', ->
items = [
{name: '<NAME>', id: 1},
{name: '<NAME>', id: 2},
{name: '<NAME>', id: 3},
]
result = hash_by_attr(items, 'name')
expect(result).toEqual(
bob: [
{name: '<NAME>', id: 1},
{name: '<NAME>', id: 3},
]
jane: [{name: '<NAME>', id: 2}]
)
it 'can use functions instead of keys', ->
items = [
{name: '<NAME>', id: 1},
{name: '<NAME>', id: 2},
{name: '<NAME>', id: 3},
]
result = hash_by_attr(items, ((o) -> o.name), value: (o) -> o.id)
expect(result).toEqual(
bob: [1, 3]
<NAME>: [2]
)
describe 'barrier', ->
it 'invokes callback after number of invocations', ->
spy = jasmine.createSpy()
b = barrier(3, spy)
b()
b()
expect(spy.callCount).toEqual(0)
b()
expect(spy.callCount).toEqual(1)
it 'ignores further invocations', ->
spy = jasmine.createSpy()
b = barrier(1, spy)
for i in [0...50]
b()
expect(spy.callCount).toEqual(1)
describe 'array_of_ints', ->
it 'converts a sequence set of numbers into an array', ->
items = array_of_ints('1, 2,3, 04')
expect(items).toEqual([1, 2, 3, 4])
it 'returns empty array for empty string', ->
expect(array_of_ints('')).toEqual([])
| true | describe 'getCookie', ->
it 'should extract value from cookie string', ->
cookie = 'foo=bar;name=joe;rofl=coptor'
expect(getCookie('foo', cookie)).toEqual('bar')
expect(getCookie('name', cookie)).toEqual('joe')
expect(getCookie('rofl', cookie)).toEqual('coptor')
it 'should return null if no key exists in cookie string', ->
expect(getCookie('foo', '')).toBeNull()
describe 'product', ->
it 'should return an array with one empty array with no args', ->
expect(product()).toEqual([[]])
it 'should return an array with original array of possibilities', ->
expect(product([1, 2, 3])).toEqual([[1], [2], [3]])
it 'should create product with multiple arrays', ->
expect(product([1, 2, 3], [4, 5])).toEqual([
[1, 4],
[1, 5],
[2, 4],
[2, 5],
[3, 4],
[3, 5],
])
describe 'iterate', ->
it 'should loop over items asynchronously', ->
runs ->
@eachfn = jasmine.createSpy().andCallFake (item, index) ->
@i ?= 5
expect([index, item]).toEqual([@i - 5, @i])
@i++
@endfn = jasmine.createSpy().andCallFake ->
expect(@i).toEqual(10)
iterate([5..9], {
delay: 1
each: @eachfn
end: @endfn
})
waits(10)
runs ->
expect(@eachfn.callCount).toEqual(5)
expect(@endfn).toHaveBeenCalled()
it 'should be cancellable', ->
runs ->
@end = jasmine.createSpy()
job = iterate([0...5], {
delay: 1
each: jasmine.createSpy()
end: @end
})
job.abort()
waits(10)
runs ->
expect(@end.callCount).toEqual(0)
describe 'pushUnique', ->
it 'inserts item if it does not exist in the array and return true', ->
a = [1, 2, 3]
expect(pushUnique(a, 4)).toBeTruthy()
expect(a).toEqual([1, 2, 3, 4])
it 'does nothing if the item already exists in the array and return false', ->
a = [1, 2, 3]
expect(pushUnique(a, 2)).toBeFalsy()
expect(a).toEqual([1, 2, 3])
describe 'format', ->
it 'does nothing to format string only', ->
expect(format('foo {{ 0 }}')).toEqual('foo {{ 0 }}')
it 'formats based on positional arguments', ->
expect(format('foo {{ 0 }} {{ 1 }}', 'bar', 'cake')).toEqual('foo bar cake')
it 'formats even with undefined values', ->
expect(format('foo {{ 0 }} {{ 1 }}', undefined, null)).toEqual('foo <undefined> <null>')
it 'formats based on object hash', ->
expect(format('{{ hello }} {{ world }}', hello: 'goodbye', world: 'everyone')).toEqual('goodbye everyone')
describe 'hash_by_attr', ->
it 'can flatten array of objects to an object', ->
items = [
{name: 'PI:NAME:<NAME>END_PI'},
{name: 'PI:NAME:<NAME>END_PI'},
]
result = hash_by_attr(items, 'name', flat: true)
expect(result).toEqual(
bob: {name: 'PI:NAME:<NAME>END_PI'},
PI:NAME:<NAME>END_PI: {name: 'PI:NAME:<NAME>END_PI'}
)
it 'can categorize array of objects in to a hash', ->
items = [
{name: 'PI:NAME:<NAME>END_PI', id: 1},
{name: 'PI:NAME:<NAME>END_PI', id: 2},
{name: 'PI:NAME:<NAME>END_PI', id: 3},
]
result = hash_by_attr(items, 'name')
expect(result).toEqual(
bob: [
{name: 'PI:NAME:<NAME>END_PI', id: 1},
{name: 'PI:NAME:<NAME>END_PI', id: 3},
]
jane: [{name: 'PI:NAME:<NAME>END_PI', id: 2}]
)
it 'can use functions instead of keys', ->
items = [
{name: 'PI:NAME:<NAME>END_PI', id: 1},
{name: 'PI:NAME:<NAME>END_PI', id: 2},
{name: 'PI:NAME:<NAME>END_PI', id: 3},
]
result = hash_by_attr(items, ((o) -> o.name), value: (o) -> o.id)
expect(result).toEqual(
bob: [1, 3]
PI:NAME:<NAME>END_PI: [2]
)
describe 'barrier', ->
it 'invokes callback after number of invocations', ->
spy = jasmine.createSpy()
b = barrier(3, spy)
b()
b()
expect(spy.callCount).toEqual(0)
b()
expect(spy.callCount).toEqual(1)
it 'ignores further invocations', ->
spy = jasmine.createSpy()
b = barrier(1, spy)
for i in [0...50]
b()
expect(spy.callCount).toEqual(1)
describe 'array_of_ints', ->
it 'converts a sequence set of numbers into an array', ->
items = array_of_ints('1, 2,3, 04')
expect(items).toEqual([1, 2, 3, 4])
it 'returns empty array for empty string', ->
expect(array_of_ints('')).toEqual([])
|
[
{
"context": "# Description\n# Ugh\n#\n# Author\n# ivey\n\nimages = [\n \"http://i.imgur.com/5qOPW.gif\",",
"end": 36,
"score": 0.4804104268550873,
"start": 36,
"tag": "NAME",
"value": ""
},
{
"context": "# Description\n# Ugh\n#\n# Author\n# ivey\n\nimages = [\n \"http://i.... | scripts/ugh.coffee | RiotGamesMinions/lefay | 7 | # Description
# Ugh
#
# Author
# ivey
images = [
"http://i.imgur.com/5qOPW.gif",
"http://i.imgur.com/90Lyen2.gif"
]
module.exports = (robot) ->
robot.hear /\bugh/i, (msg) ->
msg.send msg.random images
| 208030 | # Description
# Ugh
#
# Author
# <NAME> ivey
images = [
"http://i.imgur.com/5qOPW.gif",
"http://i.imgur.com/90Lyen2.gif"
]
module.exports = (robot) ->
robot.hear /\bugh/i, (msg) ->
msg.send msg.random images
| true | # Description
# Ugh
#
# Author
# PI:NAME:<NAME>END_PI ivey
images = [
"http://i.imgur.com/5qOPW.gif",
"http://i.imgur.com/90Lyen2.gif"
]
module.exports = (robot) ->
robot.hear /\bugh/i, (msg) ->
msg.send msg.random images
|
[
{
"context": "s: [\n# {name: \"title\"},\n# {name: \"author_name\"},\n# {name: \"modified\"},\n# ]\n# se",
"end": 640,
"score": 0.596843421459198,
"start": 629,
"tag": "NAME",
"value": "author_name"
}
] | creator/packages/steedos-cms/lib/admin.coffee | yicone/steedos-platform | 42 | # db.cms_sites.adminConfig =
# icon: "globe"
# color: "blue"
# tableColumns: [
# {name: "name"},
# {name: "order"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# db.cms_categories.adminConfig =
# icon: "ion ion-ios-albums-outline"
# color: "blue"
# tableColumns: [
# {name: "name"},
# {name: "order"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# db.cms_posts.adminConfig =
# icon: "globe"
# color: "blue"
# tableColumns: [
# {name: "title"},
# {name: "author_name"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# Meteor.startup ->
# @cms_categories = db.cms_categories
# @cms_sites = db.cms_sites
# @cms_posts = db.cms_posts
# @cms_pages = db.cms_pages
# @cms_tags = db.cms_tags
# AdminConfig?.collections_add
# cms_categories: db.cms_categories.adminConfig
# cms_sites: db.cms_sites.adminConfig
# cms_posts: db.cms_posts.adminConfig
# cms_pages: db.cms_pages.adminConfig
# cms_tags: db.cms_tags.adminConfig
| 35036 | # db.cms_sites.adminConfig =
# icon: "globe"
# color: "blue"
# tableColumns: [
# {name: "name"},
# {name: "order"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# db.cms_categories.adminConfig =
# icon: "ion ion-ios-albums-outline"
# color: "blue"
# tableColumns: [
# {name: "name"},
# {name: "order"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# db.cms_posts.adminConfig =
# icon: "globe"
# color: "blue"
# tableColumns: [
# {name: "title"},
# {name: "<NAME>"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# Meteor.startup ->
# @cms_categories = db.cms_categories
# @cms_sites = db.cms_sites
# @cms_posts = db.cms_posts
# @cms_pages = db.cms_pages
# @cms_tags = db.cms_tags
# AdminConfig?.collections_add
# cms_categories: db.cms_categories.adminConfig
# cms_sites: db.cms_sites.adminConfig
# cms_posts: db.cms_posts.adminConfig
# cms_pages: db.cms_pages.adminConfig
# cms_tags: db.cms_tags.adminConfig
| true | # db.cms_sites.adminConfig =
# icon: "globe"
# color: "blue"
# tableColumns: [
# {name: "name"},
# {name: "order"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# db.cms_categories.adminConfig =
# icon: "ion ion-ios-albums-outline"
# color: "blue"
# tableColumns: [
# {name: "name"},
# {name: "order"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# db.cms_posts.adminConfig =
# icon: "globe"
# color: "blue"
# tableColumns: [
# {name: "title"},
# {name: "PI:NAME:<NAME>END_PI"},
# {name: "modified"},
# ]
# selector: Selector.selectorCheckSpaceAdmin
# Meteor.startup ->
# @cms_categories = db.cms_categories
# @cms_sites = db.cms_sites
# @cms_posts = db.cms_posts
# @cms_pages = db.cms_pages
# @cms_tags = db.cms_tags
# AdminConfig?.collections_add
# cms_categories: db.cms_categories.adminConfig
# cms_sites: db.cms_sites.adminConfig
# cms_posts: db.cms_posts.adminConfig
# cms_pages: db.cms_pages.adminConfig
# cms_tags: db.cms_tags.adminConfig
|
[
{
"context": "'; date_value = new Date()\nattrs = {\n id : 'test_model',\n name : 'testy',\n a_class: {\n _type ",
"end": 1867,
"score": 0.937850296497345,
"start": 1857,
"tag": "USERNAME",
"value": "test_model"
},
{
"context": "\nattrs = {\n id : 'test_model',... | test/core/test-model.coffee | kmalakoff/backbone-articulation | 2 | Date::isEqual = (that) -> return (@valueOf() == that.valueOf())
window.SomeNamespace or= {}
class SomeNamespace.SomeClass
constructor: (int_value, string_value, date_value) ->
@int_value = int_value
@string_value = string_value
@date_value = date_value
toJSON: ->
return {
_type: 'SomeNamespace.SomeClass'
int_value: @int_value
string_value: @string_value
date_value: JSONS.serialize(@date_value)
}
@fromJSON: (obj) ->
return null if (obj._type!='SomeNamespace.SomeClass')
return new SomeClass(obj.int_value, obj.string_value, JSONS.deserialize(obj.date_value))
isEqual: (that) ->
if (!that)
return false
else if (that instanceof SomeClass)
return ((@int_value is that.int_value) and (@string_value is that.string_value) and _.isEqual(@date_value, that.date_value))
else
this_JSON = @toJSON()
return _.isEqual(this_JSON, that)
return false
module("Backbone.Articulation.Model")
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
_ = if not window._ and (typeof(require) isnt 'undefined') then require('underscore') else window._
_ = _._ if _ and _.hasOwnProperty('_') # LEGACY
Backbone = if not window.Backbone and (typeof(require) isnt 'undefined') then require('backbone') else window.Backbone
Backbone.Articulation = if not Backbone.Articulation and (typeof(require) isnt 'undefined') then require('backbone-articulation') else Backbone.Articulation
JSONS = if not window.JSONS and (typeof(require) isnt 'undefined') then require('json-serialize') else window.JSONS
test("TEST DEPENDENCY MISSING", ->
ok(!!_, '_'); ok(!!Backbone, 'Backbone'); ok(!!Backbone.Articulation, 'Backbone.Articulation'); ok(!!JSONS, 'JSONS')
)
int_value = 123456; string_value = 'Hello'; date_value = new Date()
attrs = {
id : 'test_model',
name : 'testy',
a_class: {
_type : 'SomeNamespace.SomeClass',
int_value : int_value,
string_value : string_value,
date_value : JSONS.serialize(date_value)
}
}
test("Model: deserialize from JSON", ->
model = new Backbone.Articulation.Model()
result = model.parse(attrs); model.set(result)
equal(_.size(model.attributes), 3, 'all attributes were deserialized')
result = model.get('a_class')
ok(result instanceof SomeNamespace.SomeClass, 'SomeNamespace.SomeClass deserialized as a class')
ok(_.isEqual(result.toJSON(), attrs.a_class), 'SomeNamespace.SomeClass deserialized correctly')
ok(result.date_value instanceof Date, 'SomeNamespace.SomeClass date_value deserialized as a Date')
ok(_.isEqual(JSONS.serialize(result.date_value), attrs.a_class.date_value), 'SomeNamespace.SomeClass date_value deserialized correctly')
)
test("Model: serialize to JSON", ->
model = new Backbone.Articulation.Model()
model.set({_type:'SomeNamespace.SomeClass', id: 'test_model', name: 'testy'})
instance = new SomeNamespace.SomeClass(int_value, string_value, date_value)
model.set({a_class: instance})
result = model.toJSON()
equal(_.size(result), 4, 'all attributes were serialized')
result = result.a_class
ok(_.isEqual(result, attrs.a_class), 'SomeNamespace.SomeClass serialized correctly')
ok(_.isEqual(result.date_value, attrs.a_class.date_value), 'SomeNamespace.SomeClass date_value serialized correctly')
)
test("Model: memory management clone() and destroy()", ->
class window.CloneDestroy
@instance_count = 0
constructor: -> CloneDestroy.instance_count++
toJSON: -> return { _type:'CloneDestroy' }
@fromJSON: (obj) ->
return null if (obj._type!='CloneDestroy')
return new CloneDestroy()
clone: -> return new CloneDestroy()
destroy: -> CloneDestroy.instance_count--
attributes = {id: 'superstar', attr1: {_type:'CloneDestroy'}, attr2: {_type:'CloneDestroy'}, attr3: {_type:'CloneDestroy'}}
model = new Backbone.Articulation.Model()
instance = new CloneDestroy()
equal(CloneDestroy.instance_count, 1, '1 referenced instance')
deserialized_attributes = model.parse(attributes)
equal(CloneDestroy.instance_count, 4, '1 referenced instance + 3 in attributes')
model.set(deserialized_attributes)
equal(CloneDestroy.instance_count, 10, '1 referenced instance + 3 in deserialized_attributes + 3 in attributes + 3 in previous attributes')
LC.disown(deserialized_attributes, {properties:true}); deserialized_attributes = null
equal(CloneDestroy.instance_count, 7, '1 referenced instance + 3 in attributes + 3 in previous attributes')
model.set({attr1: 1})
equal(CloneDestroy.instance_count, 5, '1 referenced instance + 2 in attributes + 2 in previous attributes')
model.clear()
equal(CloneDestroy.instance_count, 1, '1 referenced instance')
)
test("Model: memory management retain() and release()", ->
class window.RetainRelease
@retain_count = 0
constructor: -> RetainRelease.retain_count++
@fromJSON: (obj) ->
return null if (obj._type!='RetainRelease')
return new RetainRelease()
retain: ->
RetainRelease.retain_count++
return @
release: ->
RetainRelease.retain_count--
return @
attributes = {id: 'superstar', attr1: {_type:'RetainRelease'}, attr2: {_type:'RetainRelease'}, attr3: {_type:'RetainRelease'}}
model = new Backbone.Articulation.Model()
instance = new RetainRelease()
equal(RetainRelease.retain_count, 1, '1 referenced instance')
deserialized_attributes = model.parse(attributes)
model.set(deserialized_attributes)
LC.disown(deserialized_attributes, {properties:true}); deserialized_attributes = null
equal(RetainRelease.retain_count, 7, '1 referenced instance + 3 in attributes + 3 in previous attributes')
model.set({attr1: 1})
equal(RetainRelease.retain_count, 5, '1 referenced instance + 2 in attributes + 2 in previous attributes')
model.clear()
equal(RetainRelease.retain_count, 1, '1 referenced instance')
) | 40297 | Date::isEqual = (that) -> return (@valueOf() == that.valueOf())
window.SomeNamespace or= {}
class SomeNamespace.SomeClass
constructor: (int_value, string_value, date_value) ->
@int_value = int_value
@string_value = string_value
@date_value = date_value
toJSON: ->
return {
_type: 'SomeNamespace.SomeClass'
int_value: @int_value
string_value: @string_value
date_value: JSONS.serialize(@date_value)
}
@fromJSON: (obj) ->
return null if (obj._type!='SomeNamespace.SomeClass')
return new SomeClass(obj.int_value, obj.string_value, JSONS.deserialize(obj.date_value))
isEqual: (that) ->
if (!that)
return false
else if (that instanceof SomeClass)
return ((@int_value is that.int_value) and (@string_value is that.string_value) and _.isEqual(@date_value, that.date_value))
else
this_JSON = @toJSON()
return _.isEqual(this_JSON, that)
return false
module("Backbone.Articulation.Model")
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
_ = if not window._ and (typeof(require) isnt 'undefined') then require('underscore') else window._
_ = _._ if _ and _.hasOwnProperty('_') # LEGACY
Backbone = if not window.Backbone and (typeof(require) isnt 'undefined') then require('backbone') else window.Backbone
Backbone.Articulation = if not Backbone.Articulation and (typeof(require) isnt 'undefined') then require('backbone-articulation') else Backbone.Articulation
JSONS = if not window.JSONS and (typeof(require) isnt 'undefined') then require('json-serialize') else window.JSONS
test("TEST DEPENDENCY MISSING", ->
ok(!!_, '_'); ok(!!Backbone, 'Backbone'); ok(!!Backbone.Articulation, 'Backbone.Articulation'); ok(!!JSONS, 'JSONS')
)
int_value = 123456; string_value = 'Hello'; date_value = new Date()
attrs = {
id : 'test_model',
name : '<NAME>',
a_class: {
_type : 'SomeNamespace.SomeClass',
int_value : int_value,
string_value : string_value,
date_value : JSONS.serialize(date_value)
}
}
test("Model: deserialize from JSON", ->
model = new Backbone.Articulation.Model()
result = model.parse(attrs); model.set(result)
equal(_.size(model.attributes), 3, 'all attributes were deserialized')
result = model.get('a_class')
ok(result instanceof SomeNamespace.SomeClass, 'SomeNamespace.SomeClass deserialized as a class')
ok(_.isEqual(result.toJSON(), attrs.a_class), 'SomeNamespace.SomeClass deserialized correctly')
ok(result.date_value instanceof Date, 'SomeNamespace.SomeClass date_value deserialized as a Date')
ok(_.isEqual(JSONS.serialize(result.date_value), attrs.a_class.date_value), 'SomeNamespace.SomeClass date_value deserialized correctly')
)
test("Model: serialize to JSON", ->
model = new Backbone.Articulation.Model()
model.set({_type:'SomeNamespace.SomeClass', id: 'test_model', name: '<NAME>'})
instance = new SomeNamespace.SomeClass(int_value, string_value, date_value)
model.set({a_class: instance})
result = model.toJSON()
equal(_.size(result), 4, 'all attributes were serialized')
result = result.a_class
ok(_.isEqual(result, attrs.a_class), 'SomeNamespace.SomeClass serialized correctly')
ok(_.isEqual(result.date_value, attrs.a_class.date_value), 'SomeNamespace.SomeClass date_value serialized correctly')
)
test("Model: memory management clone() and destroy()", ->
class window.CloneDestroy
@instance_count = 0
constructor: -> CloneDestroy.instance_count++
toJSON: -> return { _type:'CloneDestroy' }
@fromJSON: (obj) ->
return null if (obj._type!='CloneDestroy')
return new CloneDestroy()
clone: -> return new CloneDestroy()
destroy: -> CloneDestroy.instance_count--
attributes = {id: 'superstar', attr1: {_type:'CloneDestroy'}, attr2: {_type:'CloneDestroy'}, attr3: {_type:'CloneDestroy'}}
model = new Backbone.Articulation.Model()
instance = new CloneDestroy()
equal(CloneDestroy.instance_count, 1, '1 referenced instance')
deserialized_attributes = model.parse(attributes)
equal(CloneDestroy.instance_count, 4, '1 referenced instance + 3 in attributes')
model.set(deserialized_attributes)
equal(CloneDestroy.instance_count, 10, '1 referenced instance + 3 in deserialized_attributes + 3 in attributes + 3 in previous attributes')
LC.disown(deserialized_attributes, {properties:true}); deserialized_attributes = null
equal(CloneDestroy.instance_count, 7, '1 referenced instance + 3 in attributes + 3 in previous attributes')
model.set({attr1: 1})
equal(CloneDestroy.instance_count, 5, '1 referenced instance + 2 in attributes + 2 in previous attributes')
model.clear()
equal(CloneDestroy.instance_count, 1, '1 referenced instance')
)
test("Model: memory management retain() and release()", ->
class window.RetainRelease
@retain_count = 0
constructor: -> RetainRelease.retain_count++
@fromJSON: (obj) ->
return null if (obj._type!='RetainRelease')
return new RetainRelease()
retain: ->
RetainRelease.retain_count++
return @
release: ->
RetainRelease.retain_count--
return @
attributes = {id: 'superstar', attr1: {_type:'RetainRelease'}, attr2: {_type:'RetainRelease'}, attr3: {_type:'RetainRelease'}}
model = new Backbone.Articulation.Model()
instance = new RetainRelease()
equal(RetainRelease.retain_count, 1, '1 referenced instance')
deserialized_attributes = model.parse(attributes)
model.set(deserialized_attributes)
LC.disown(deserialized_attributes, {properties:true}); deserialized_attributes = null
equal(RetainRelease.retain_count, 7, '1 referenced instance + 3 in attributes + 3 in previous attributes')
model.set({attr1: 1})
equal(RetainRelease.retain_count, 5, '1 referenced instance + 2 in attributes + 2 in previous attributes')
model.clear()
equal(RetainRelease.retain_count, 1, '1 referenced instance')
) | true | Date::isEqual = (that) -> return (@valueOf() == that.valueOf())
window.SomeNamespace or= {}
class SomeNamespace.SomeClass
constructor: (int_value, string_value, date_value) ->
@int_value = int_value
@string_value = string_value
@date_value = date_value
toJSON: ->
return {
_type: 'SomeNamespace.SomeClass'
int_value: @int_value
string_value: @string_value
date_value: JSONS.serialize(@date_value)
}
@fromJSON: (obj) ->
return null if (obj._type!='SomeNamespace.SomeClass')
return new SomeClass(obj.int_value, obj.string_value, JSONS.deserialize(obj.date_value))
isEqual: (that) ->
if (!that)
return false
else if (that instanceof SomeClass)
return ((@int_value is that.int_value) and (@string_value is that.string_value) and _.isEqual(@date_value, that.date_value))
else
this_JSON = @toJSON()
return _.isEqual(this_JSON, that)
return false
module("Backbone.Articulation.Model")
# import Underscore (or Lo-Dash with precedence), Backbone, Knockout, and Knockback
_ = if not window._ and (typeof(require) isnt 'undefined') then require('underscore') else window._
_ = _._ if _ and _.hasOwnProperty('_') # LEGACY
Backbone = if not window.Backbone and (typeof(require) isnt 'undefined') then require('backbone') else window.Backbone
Backbone.Articulation = if not Backbone.Articulation and (typeof(require) isnt 'undefined') then require('backbone-articulation') else Backbone.Articulation
JSONS = if not window.JSONS and (typeof(require) isnt 'undefined') then require('json-serialize') else window.JSONS
test("TEST DEPENDENCY MISSING", ->
ok(!!_, '_'); ok(!!Backbone, 'Backbone'); ok(!!Backbone.Articulation, 'Backbone.Articulation'); ok(!!JSONS, 'JSONS')
)
int_value = 123456; string_value = 'Hello'; date_value = new Date()
attrs = {
id : 'test_model',
name : 'PI:NAME:<NAME>END_PI',
a_class: {
_type : 'SomeNamespace.SomeClass',
int_value : int_value,
string_value : string_value,
date_value : JSONS.serialize(date_value)
}
}
test("Model: deserialize from JSON", ->
model = new Backbone.Articulation.Model()
result = model.parse(attrs); model.set(result)
equal(_.size(model.attributes), 3, 'all attributes were deserialized')
result = model.get('a_class')
ok(result instanceof SomeNamespace.SomeClass, 'SomeNamespace.SomeClass deserialized as a class')
ok(_.isEqual(result.toJSON(), attrs.a_class), 'SomeNamespace.SomeClass deserialized correctly')
ok(result.date_value instanceof Date, 'SomeNamespace.SomeClass date_value deserialized as a Date')
ok(_.isEqual(JSONS.serialize(result.date_value), attrs.a_class.date_value), 'SomeNamespace.SomeClass date_value deserialized correctly')
)
test("Model: serialize to JSON", ->
model = new Backbone.Articulation.Model()
model.set({_type:'SomeNamespace.SomeClass', id: 'test_model', name: 'PI:NAME:<NAME>END_PI'})
instance = new SomeNamespace.SomeClass(int_value, string_value, date_value)
model.set({a_class: instance})
result = model.toJSON()
equal(_.size(result), 4, 'all attributes were serialized')
result = result.a_class
ok(_.isEqual(result, attrs.a_class), 'SomeNamespace.SomeClass serialized correctly')
ok(_.isEqual(result.date_value, attrs.a_class.date_value), 'SomeNamespace.SomeClass date_value serialized correctly')
)
test("Model: memory management clone() and destroy()", ->
class window.CloneDestroy
@instance_count = 0
constructor: -> CloneDestroy.instance_count++
toJSON: -> return { _type:'CloneDestroy' }
@fromJSON: (obj) ->
return null if (obj._type!='CloneDestroy')
return new CloneDestroy()
clone: -> return new CloneDestroy()
destroy: -> CloneDestroy.instance_count--
attributes = {id: 'superstar', attr1: {_type:'CloneDestroy'}, attr2: {_type:'CloneDestroy'}, attr3: {_type:'CloneDestroy'}}
model = new Backbone.Articulation.Model()
instance = new CloneDestroy()
equal(CloneDestroy.instance_count, 1, '1 referenced instance')
deserialized_attributes = model.parse(attributes)
equal(CloneDestroy.instance_count, 4, '1 referenced instance + 3 in attributes')
model.set(deserialized_attributes)
equal(CloneDestroy.instance_count, 10, '1 referenced instance + 3 in deserialized_attributes + 3 in attributes + 3 in previous attributes')
LC.disown(deserialized_attributes, {properties:true}); deserialized_attributes = null
equal(CloneDestroy.instance_count, 7, '1 referenced instance + 3 in attributes + 3 in previous attributes')
model.set({attr1: 1})
equal(CloneDestroy.instance_count, 5, '1 referenced instance + 2 in attributes + 2 in previous attributes')
model.clear()
equal(CloneDestroy.instance_count, 1, '1 referenced instance')
)
test("Model: memory management retain() and release()", ->
class window.RetainRelease
@retain_count = 0
constructor: -> RetainRelease.retain_count++
@fromJSON: (obj) ->
return null if (obj._type!='RetainRelease')
return new RetainRelease()
retain: ->
RetainRelease.retain_count++
return @
release: ->
RetainRelease.retain_count--
return @
attributes = {id: 'superstar', attr1: {_type:'RetainRelease'}, attr2: {_type:'RetainRelease'}, attr3: {_type:'RetainRelease'}}
model = new Backbone.Articulation.Model()
instance = new RetainRelease()
equal(RetainRelease.retain_count, 1, '1 referenced instance')
deserialized_attributes = model.parse(attributes)
model.set(deserialized_attributes)
LC.disown(deserialized_attributes, {properties:true}); deserialized_attributes = null
equal(RetainRelease.retain_count, 7, '1 referenced instance + 3 in attributes + 3 in previous attributes')
model.set({attr1: 1})
equal(RetainRelease.retain_count, 5, '1 referenced instance + 2 in attributes + 2 in previous attributes')
model.clear()
equal(RetainRelease.retain_count, 1, '1 referenced instance')
) |
[
{
"context": "status.reject()\n\n input ?= {}\n\n apiCallKey = @pendingApiCallKey++\n @pendingApiCalls[apiCallKey] = statu",
"end": 3087,
"score": 0.7218930721282959,
"start": 3076,
"tag": "KEY",
"value": "@pendingApi"
},
{
"context": " input ?= {}\n\n apiCallKey = @pend... | src/api.coffee | dnanexus/dx-javascript-toolkit | 11 | # TODO: Set cookies to expire when the token expires
ajaxRequest = require('./ajax_request.coffee')
class Api
#
# Globals
#
API_ERRORS:
MalformedJSON: "The input could not be parsed as JSON"
InvalidAuthentication: "The provided OAuth2 token is invalid"
PermissionDenied: "Insufficient permissions to perform this action"
ResourceNotFound: "A specified entity or resource could not be found"
InvalidInput: "The input is syntactically correct (JSON), but semantically incorrect"
InvalidState: "The operation is not allowed at this object state"
InvalidType: "An object specified in the request is of invalid type"
InternalError: "The server encountered an internal error"
InvalidErrorResponse: "We've received an error, but cannot process the message"
InvalidAPICall: "An invalid api call has occurred"
InvalidResponse: "We've received an invalid response from an API call"
AjaxError: "There was an error in the way the server request was formed"
AjaxTimeout: "The server could not be contacted in a timely fashion"
ALL_ERRORS: "AllErrors"
#
# Construct a new API binding
#
# authToken: The authentication token with which we can access the DNAnexus API.
#
# options:
# apiServer: Override the API server information. Default: "api.dnanexus.com"
# maxAJAXTrials: The number of times to retry an AJAX request. Default: 5
#
constructor: (@authToken, options = {}) ->
throw new Error("authToken must be specified") if !@authToken? || @authToken.length == 0
@maxAJAXTrials = options.maxAJAXTrials ? 5
@apiServer = "https://#{options.apiServer ? "api.dnanexus.com"}"
# A list of pending API calls, do be tracked/aborted when needed
@pendingApiCallKey = 0
@pendingApiCalls = {}
#
# Performs an API call against Nucleus.
#
# subject: The target of the API call, in the form object-xxxx
# method: The method to call on the target, "describe" for example
# input: An object representing the arguments for the API call
#
# options: Some custom options that are needed from time to time
# withCredentials: if true will set the withCredentials property on the xhr request
#
# Returns a deferred object which will be called with the results upon success, or the error if an
# error occurs. The deferred object also has an "abort" method which will abort the AJAX call.
#
call: (subject, method, input, options = {}) ->
status = $.Deferred()
# Add abort for early returns (will be replaced by a more comlpex method later)
status.abort = () ->
@aborted = true
# If this API connection is disabled, return a deferred object which will never be resolved
return status if @disabled
# If no subject or method is given, reject outright
if !(subject? && method? && typeof subject == "string" && typeof method == "string")
console.error("Subject and method must both be defined and must be strings, when calling Nucleus.call", subject, method)
return status.reject()
input ?= {}
apiCallKey = @pendingApiCallKey++
@pendingApiCalls[apiCallKey] = status
url = [@apiServer, subject, method].join('/')
headers = {}
headers.Authorization = "Bearer #{@authToken}"
input =
headers: headers
data: input
maxRetries: @maxAJAXTrials
if options.withCredentials == true
input.withCredentials = true
request = ajaxRequest(url, input)
# Decorate the deferred object with an abort method which cancels the ajax request and sets the internal
# state of the deferred object to aborted, which prevents the deferred object from being resolved
status.abort = () ->
@aborted = true
request.abort()
request.done((data) =>
return if status.aborted
# Firefox insists that the returned data is a string, not a JSON object. Here we parse the
# JSON if we can, or leave it as a string if not.
try
data = $.parseJSON(data) if typeof data == "string"
catch error
status.reject({type: "InvalidResponse"})
return
status.resolve(data)
).fail((error) =>
status.reject(error)
).always(() =>
delete @pendingApiCalls[apiCallKey]
)
return status
# Aborts all unresolved callbacks
destroy: () ->
@disabled = true
for own key, status of @pendingApiCalls
status.abort()
getNumPendingApiCalls: () ->
count = 0
for own key, status of @pendingApiCalls
count++
return count
#
# Note that the last two parameters are only used when dealing with errors. In
# normal use, status will be undefined
#
uploadFilePart: (fileID, part, slice, md5Hash, errors, attempt = 0, status) ->
deferred = status ? $.Deferred()
headers =
"Content-MD5": md5Hash
# Headers that we refuse to set, regardless of what comes back from the API server.
blacklistedHeaders =
"content-length": true
"origin": true
"host": true
input =
index: part
md5: md5Hash
size: slice.size
onError = (error) =>
# Don't retry aborted uploads
return if deferred.__aborted
if attempt >= 8
deferred.reject(error)
else
# Try again shortly. There is no problem attempting an upload of the same part multiple times
delay = Math.pow(2, attempt) * 1000
console.warn("[Trial #{attempt + 1}] Error uploading #{fileID} part #{part} trying again in #{delay}ms")
console.warn(error)
retryHandler = () =>
@uploadFilePart(fileID, part, slice, md5Hash, errors, attempt + 1, deferred)
setTimeout(retryHandler, delay)
originalCall = @call(fileID, "upload", input, errors).done((results) ->
# Merge the upload headers into our headers
for k, v of results.headers
headers[k] = v unless blacklistedHeaders[k.toLowerCase()]
ajaxCall = $.ajax({
url: results.url
contentType: "application/octet-stream"
processData: false
data: slice
headers: headers
success: () ->
deferred.resolve(null)
error: (jqXHR, status, error) ->
try
errorType = JSON.parse(jqXHR.responseText).error.type
onError(errorType)
catch jsError
onError(error)
type: "PUT"
xhr: () ->
# Grab upload progress from XMLHttpRequest2 if available
xhr = $.ajaxSettings.xhr()
if xhr.upload?
progressHandler = (e) ->
if e.lengthComputable
# TODO: Change names?
deferred.notify({loaded: e.loaded, total: e.total})
doneHandler = () ->
# Clean up event listeners
xhr.upload.removeEventListener("progress", progressHandler)
xhr.upload.removeEventListener("loadend", doneHandler)
xhr.upload.addEventListener("progress", progressHandler)
xhr.upload.addEventListener("loadend", doneHandler)
return xhr
})
origAbort = originalCall.abort
originalCall.abort = () ->
ajaxCall.abort()
origAbort.call(originalCall)
).fail(onError)
# Delegate abort calls
deferred.abort = () ->
deferred.__aborted = true
originalCall.abort()
return deferred
module.exports = Api
| 1725 | # TODO: Set cookies to expire when the token expires
ajaxRequest = require('./ajax_request.coffee')
class Api
#
# Globals
#
API_ERRORS:
MalformedJSON: "The input could not be parsed as JSON"
InvalidAuthentication: "The provided OAuth2 token is invalid"
PermissionDenied: "Insufficient permissions to perform this action"
ResourceNotFound: "A specified entity or resource could not be found"
InvalidInput: "The input is syntactically correct (JSON), but semantically incorrect"
InvalidState: "The operation is not allowed at this object state"
InvalidType: "An object specified in the request is of invalid type"
InternalError: "The server encountered an internal error"
InvalidErrorResponse: "We've received an error, but cannot process the message"
InvalidAPICall: "An invalid api call has occurred"
InvalidResponse: "We've received an invalid response from an API call"
AjaxError: "There was an error in the way the server request was formed"
AjaxTimeout: "The server could not be contacted in a timely fashion"
ALL_ERRORS: "AllErrors"
#
# Construct a new API binding
#
# authToken: The authentication token with which we can access the DNAnexus API.
#
# options:
# apiServer: Override the API server information. Default: "api.dnanexus.com"
# maxAJAXTrials: The number of times to retry an AJAX request. Default: 5
#
constructor: (@authToken, options = {}) ->
throw new Error("authToken must be specified") if !@authToken? || @authToken.length == 0
@maxAJAXTrials = options.maxAJAXTrials ? 5
@apiServer = "https://#{options.apiServer ? "api.dnanexus.com"}"
# A list of pending API calls, do be tracked/aborted when needed
@pendingApiCallKey = 0
@pendingApiCalls = {}
#
# Performs an API call against Nucleus.
#
# subject: The target of the API call, in the form object-xxxx
# method: The method to call on the target, "describe" for example
# input: An object representing the arguments for the API call
#
# options: Some custom options that are needed from time to time
# withCredentials: if true will set the withCredentials property on the xhr request
#
# Returns a deferred object which will be called with the results upon success, or the error if an
# error occurs. The deferred object also has an "abort" method which will abort the AJAX call.
#
call: (subject, method, input, options = {}) ->
status = $.Deferred()
# Add abort for early returns (will be replaced by a more comlpex method later)
status.abort = () ->
@aborted = true
# If this API connection is disabled, return a deferred object which will never be resolved
return status if @disabled
# If no subject or method is given, reject outright
if !(subject? && method? && typeof subject == "string" && typeof method == "string")
console.error("Subject and method must both be defined and must be strings, when calling Nucleus.call", subject, method)
return status.reject()
input ?= {}
apiCallKey = <KEY>CallKey<KEY>++
@pendingApiCalls[apiCallKey] = status
url = [@apiServer, subject, method].join('/')
headers = {}
headers.Authorization = "Bearer #{@authToken}"
input =
headers: headers
data: input
maxRetries: @maxAJAXTrials
if options.withCredentials == true
input.withCredentials = true
request = ajaxRequest(url, input)
# Decorate the deferred object with an abort method which cancels the ajax request and sets the internal
# state of the deferred object to aborted, which prevents the deferred object from being resolved
status.abort = () ->
@aborted = true
request.abort()
request.done((data) =>
return if status.aborted
# Firefox insists that the returned data is a string, not a JSON object. Here we parse the
# JSON if we can, or leave it as a string if not.
try
data = $.parseJSON(data) if typeof data == "string"
catch error
status.reject({type: "InvalidResponse"})
return
status.resolve(data)
).fail((error) =>
status.reject(error)
).always(() =>
delete @pendingApiCalls[apiCallKey]
)
return status
# Aborts all unresolved callbacks
destroy: () ->
@disabled = true
for own key, status of @pendingApiCalls
status.abort()
getNumPendingApiCalls: () ->
count = 0
for own key, status of @pendingApiCalls
count++
return count
#
# Note that the last two parameters are only used when dealing with errors. In
# normal use, status will be undefined
#
uploadFilePart: (fileID, part, slice, md5Hash, errors, attempt = 0, status) ->
deferred = status ? $.Deferred()
headers =
"Content-MD5": md5Hash
# Headers that we refuse to set, regardless of what comes back from the API server.
blacklistedHeaders =
"content-length": true
"origin": true
"host": true
input =
index: part
md5: md5Hash
size: slice.size
onError = (error) =>
# Don't retry aborted uploads
return if deferred.__aborted
if attempt >= 8
deferred.reject(error)
else
# Try again shortly. There is no problem attempting an upload of the same part multiple times
delay = Math.pow(2, attempt) * 1000
console.warn("[Trial #{attempt + 1}] Error uploading #{fileID} part #{part} trying again in #{delay}ms")
console.warn(error)
retryHandler = () =>
@uploadFilePart(fileID, part, slice, md5Hash, errors, attempt + 1, deferred)
setTimeout(retryHandler, delay)
originalCall = @call(fileID, "upload", input, errors).done((results) ->
# Merge the upload headers into our headers
for k, v of results.headers
headers[k] = v unless blacklistedHeaders[k.toLowerCase()]
ajaxCall = $.ajax({
url: results.url
contentType: "application/octet-stream"
processData: false
data: slice
headers: headers
success: () ->
deferred.resolve(null)
error: (jqXHR, status, error) ->
try
errorType = JSON.parse(jqXHR.responseText).error.type
onError(errorType)
catch jsError
onError(error)
type: "PUT"
xhr: () ->
# Grab upload progress from XMLHttpRequest2 if available
xhr = $.ajaxSettings.xhr()
if xhr.upload?
progressHandler = (e) ->
if e.lengthComputable
# TODO: Change names?
deferred.notify({loaded: e.loaded, total: e.total})
doneHandler = () ->
# Clean up event listeners
xhr.upload.removeEventListener("progress", progressHandler)
xhr.upload.removeEventListener("loadend", doneHandler)
xhr.upload.addEventListener("progress", progressHandler)
xhr.upload.addEventListener("loadend", doneHandler)
return xhr
})
origAbort = originalCall.abort
originalCall.abort = () ->
ajaxCall.abort()
origAbort.call(originalCall)
).fail(onError)
# Delegate abort calls
deferred.abort = () ->
deferred.__aborted = true
originalCall.abort()
return deferred
module.exports = Api
| true | # TODO: Set cookies to expire when the token expires
ajaxRequest = require('./ajax_request.coffee')
class Api
#
# Globals
#
API_ERRORS:
MalformedJSON: "The input could not be parsed as JSON"
InvalidAuthentication: "The provided OAuth2 token is invalid"
PermissionDenied: "Insufficient permissions to perform this action"
ResourceNotFound: "A specified entity or resource could not be found"
InvalidInput: "The input is syntactically correct (JSON), but semantically incorrect"
InvalidState: "The operation is not allowed at this object state"
InvalidType: "An object specified in the request is of invalid type"
InternalError: "The server encountered an internal error"
InvalidErrorResponse: "We've received an error, but cannot process the message"
InvalidAPICall: "An invalid api call has occurred"
InvalidResponse: "We've received an invalid response from an API call"
AjaxError: "There was an error in the way the server request was formed"
AjaxTimeout: "The server could not be contacted in a timely fashion"
ALL_ERRORS: "AllErrors"
#
# Construct a new API binding
#
# authToken: The authentication token with which we can access the DNAnexus API.
#
# options:
# apiServer: Override the API server information. Default: "api.dnanexus.com"
# maxAJAXTrials: The number of times to retry an AJAX request. Default: 5
#
constructor: (@authToken, options = {}) ->
throw new Error("authToken must be specified") if !@authToken? || @authToken.length == 0
@maxAJAXTrials = options.maxAJAXTrials ? 5
@apiServer = "https://#{options.apiServer ? "api.dnanexus.com"}"
# A list of pending API calls, do be tracked/aborted when needed
@pendingApiCallKey = 0
@pendingApiCalls = {}
#
# Performs an API call against Nucleus.
#
# subject: The target of the API call, in the form object-xxxx
# method: The method to call on the target, "describe" for example
# input: An object representing the arguments for the API call
#
# options: Some custom options that are needed from time to time
# withCredentials: if true will set the withCredentials property on the xhr request
#
# Returns a deferred object which will be called with the results upon success, or the error if an
# error occurs. The deferred object also has an "abort" method which will abort the AJAX call.
#
call: (subject, method, input, options = {}) ->
status = $.Deferred()
# Add abort for early returns (will be replaced by a more comlpex method later)
status.abort = () ->
@aborted = true
# If this API connection is disabled, return a deferred object which will never be resolved
return status if @disabled
# If no subject or method is given, reject outright
if !(subject? && method? && typeof subject == "string" && typeof method == "string")
console.error("Subject and method must both be defined and must be strings, when calling Nucleus.call", subject, method)
return status.reject()
input ?= {}
apiCallKey = PI:KEY:<KEY>END_PICallKeyPI:KEY:<KEY>END_PI++
@pendingApiCalls[apiCallKey] = status
url = [@apiServer, subject, method].join('/')
headers = {}
headers.Authorization = "Bearer #{@authToken}"
input =
headers: headers
data: input
maxRetries: @maxAJAXTrials
if options.withCredentials == true
input.withCredentials = true
request = ajaxRequest(url, input)
# Decorate the deferred object with an abort method which cancels the ajax request and sets the internal
# state of the deferred object to aborted, which prevents the deferred object from being resolved
status.abort = () ->
@aborted = true
request.abort()
request.done((data) =>
return if status.aborted
# Firefox insists that the returned data is a string, not a JSON object. Here we parse the
# JSON if we can, or leave it as a string if not.
try
data = $.parseJSON(data) if typeof data == "string"
catch error
status.reject({type: "InvalidResponse"})
return
status.resolve(data)
).fail((error) =>
status.reject(error)
).always(() =>
delete @pendingApiCalls[apiCallKey]
)
return status
# Aborts all unresolved callbacks
destroy: () ->
@disabled = true
for own key, status of @pendingApiCalls
status.abort()
getNumPendingApiCalls: () ->
count = 0
for own key, status of @pendingApiCalls
count++
return count
#
# Note that the last two parameters are only used when dealing with errors. In
# normal use, status will be undefined
#
uploadFilePart: (fileID, part, slice, md5Hash, errors, attempt = 0, status) ->
deferred = status ? $.Deferred()
headers =
"Content-MD5": md5Hash
# Headers that we refuse to set, regardless of what comes back from the API server.
blacklistedHeaders =
"content-length": true
"origin": true
"host": true
input =
index: part
md5: md5Hash
size: slice.size
onError = (error) =>
# Don't retry aborted uploads
return if deferred.__aborted
if attempt >= 8
deferred.reject(error)
else
# Try again shortly. There is no problem attempting an upload of the same part multiple times
delay = Math.pow(2, attempt) * 1000
console.warn("[Trial #{attempt + 1}] Error uploading #{fileID} part #{part} trying again in #{delay}ms")
console.warn(error)
retryHandler = () =>
@uploadFilePart(fileID, part, slice, md5Hash, errors, attempt + 1, deferred)
setTimeout(retryHandler, delay)
originalCall = @call(fileID, "upload", input, errors).done((results) ->
# Merge the upload headers into our headers
for k, v of results.headers
headers[k] = v unless blacklistedHeaders[k.toLowerCase()]
ajaxCall = $.ajax({
url: results.url
contentType: "application/octet-stream"
processData: false
data: slice
headers: headers
success: () ->
deferred.resolve(null)
error: (jqXHR, status, error) ->
try
errorType = JSON.parse(jqXHR.responseText).error.type
onError(errorType)
catch jsError
onError(error)
type: "PUT"
xhr: () ->
# Grab upload progress from XMLHttpRequest2 if available
xhr = $.ajaxSettings.xhr()
if xhr.upload?
progressHandler = (e) ->
if e.lengthComputable
# TODO: Change names?
deferred.notify({loaded: e.loaded, total: e.total})
doneHandler = () ->
# Clean up event listeners
xhr.upload.removeEventListener("progress", progressHandler)
xhr.upload.removeEventListener("loadend", doneHandler)
xhr.upload.addEventListener("progress", progressHandler)
xhr.upload.addEventListener("loadend", doneHandler)
return xhr
})
origAbort = originalCall.abort
originalCall.abort = () ->
ajaxCall.abort()
origAbort.call(originalCall)
).fail(onError)
# Delegate abort calls
deferred.abort = () ->
deferred.__aborted = true
originalCall.abort()
return deferred
module.exports = Api
|
[
{
"context": ".val()\n )\n video1[0].src = abspath+'Alex Gaudino feat. Crystal Waters - Destination Calabria [Expl",
"end": 865,
"score": 0.9997513890266418,
"start": 853,
"tag": "NAME",
"value": "Alex Gaudino"
}
] | OutputController.coffee | JimmothySanchez/MusicVideoMonster | 0 | $(document).ready(()->
###Global Vars###
video1 = $('#video1')
video2 = $('#video2')
canvas = $('#canvas')
seriously = new Seriously()
reformat = seriously.transform('reformat')
vignette = seriously.effect("vignette")
tvGlitch = null
blend = seriously.effect('blend')
{ipcRenderer} = require('electron')
effectList = []
###Runtime flags ###
clock = 0
activeVideoIndex = 0
inTransition = false
transitionStartTime = 0
glitchOn = false
durationCheck = false
##Static Defaults
fadeOutTime = 5000
tickInterval = 100
effectPlugins = {}
currentEffect=null
debug = ()->
abspath = 'G:\\Projects\\YoutubeDownload\\'
$("#opacity").on('input',()->
## blend.opacity = $("#opacity").val()
)
video1[0].src = abspath+'Alex Gaudino feat. Crystal Waters - Destination Calabria [Explicit Version] [Official Video].mp4'
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
)
video2[0].src = abspath+'Major Lazer – Light it Up (feat. Nyla & Fuse ODG) [Music Video Remix] by Method Studios.mp4'
video2[0].load()
video2[0].addEventListener("canplaythrough",()->
@play()
)
video1[0].volume=0
video2[0].volume=0
transitionStartTime = clock
activeVideoIndex =2
inTransition = true
setUpEffectPlugins = (inNode,outNode)->
initEffect("ascii")
initEffect("hex")
initEffect("invert")
initEffect("sketch")
initEffect("kaleidoscope")
initEffect("nightvision")
pluginParams =[]
for plugin in effectPlugins
pluginParams.push(
Name: plugin.effect
Params: plugin.inputs()
)
ipcRenderer.send('effect-params', pluginParams)
initEffect = (effectName)->
temp = seriously.effect(effectName)
effectPlugins[temp.effect] = temp
##effectPlugins.push(temp)
##temp.on(temp.effect+'-on')
##temp.off((temp.effect+'-off'))
temp.source = blend
return temp
init = ()->
video1[0].playbackRate = 1
video2[0].playbackRate = 1
target = seriously.target('#canvas')
reformat.width = target.width
reformat.height = target.height
reformat.mode = 'cover'
#reformat.source = seriously.source('#video1')
blend.bottom = seriously.source('#video1')
blend.top = seriously.source('#video2')
setUpEffectPlugins(vignette,reformat)
vignette.source = blend
target.source = reformat;
reformat.source = vignette
seriously.go()
window.setInterval(onTick,tickInterval)
setTimeout(startGlitch, 10000+Math.random()*60000)
$('#btnFullscreen').click(()->
canvas[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)
)
$('#video').on("timeupdate",()->
dostuff =1
)
ipcRenderer.on('video-load', (event, arg) =>
abspath = 'G:\\Projects\\YoutubeDownload\\' + arg.Path
video1[0].src = abspath
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
)
)
ipcRenderer.on('stage-video', (event, arg) =>
console.log('staging')
transitionWindow()
abspath = 'G:\\Projects\\YoutubeDownload\\' + arg.Path
if(activeVideoIndex ==1)
video1[0].src = abspath
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
durationCheck = true
)
else
video2[0].src = abspath
video2[0].load()
video2[0].addEventListener("canplaythrough",()->
@play()
durationCheck = true
)
)
ipcRenderer.on('change-effect', (event, arg) =>
console.log(arg)
if(arg.Name == 'None')
currentEffect = null
vignette.source=blend
else
if(currentEffect ==null || currentEffect.effect != arg.Name)
currentEffect = effectPlugins[arg.Name]
vignette.source = currentEffect
if(arg.field)
currentEffect[arg.field] = arg.value
)
checkDurationContitions=()->
if(durationCheck)
if(activeVideoIndex ==1)
if(video1[0].duration-video1[0].currentTime<=fadeOutTime/1000)
ipcRenderer.send('request-video', true)
durationCheck = false
else
if(video2[0].duration-video2[0].currentTime<=fadeOutTime/1000)
ipcRenderer.send('request-video', true)
durationCheck = false
startGlitch=()->
tvGlitch = seriously.effect('tvglitch')
tvGlitch.source =vignette
setTimeout(endGlitch, Math.random()*1000)
endGlitch=()->
reformat.source = vignette
tvGlitch.destroy()
tvGlitch = null
setTimeout(startGlitch, 10000+Math.random()*60000)
transitionWindow = ()->
inTransition = true
transitionStartTime = clock
if(activeVideoIndex == 1)
activeVideoIndex = 2
else
activeVideoIndex = 1
onTick = ()->
clock = clock+tickInterval
if(inTransition)
updateTransitions()
updateVignette()
checkDurationContitions()
updateVignette=()->
vignette.amount = 1+2*Math.sin(clock/12000)+Math.random()/2
updateTransitions=()->
currentDuration = clock-transitionStartTime
if(currentDuration>=fadeOutTime)
if(activeVideoIndex ==1)
blend.opacity = 0
video1[0].volume=1
video2[0].volume=0
else
blend.opacity =1
video1[0].volume=0
video2[0].volume=1
blend.inTransition = false
else
alpha =(clock-transitionStartTime)/fadeOutTime
if(activeVideoIndex ==1)
blend.opacity = 1-alpha
video1[0].volume=alpha
video2[0].volume=1-alpha
else
blend.opacity =alpha
video1[0].volume=1-alpha
video2[0].volume=alpha
init()
##debug()
)
| 135084 | $(document).ready(()->
###Global Vars###
video1 = $('#video1')
video2 = $('#video2')
canvas = $('#canvas')
seriously = new Seriously()
reformat = seriously.transform('reformat')
vignette = seriously.effect("vignette")
tvGlitch = null
blend = seriously.effect('blend')
{ipcRenderer} = require('electron')
effectList = []
###Runtime flags ###
clock = 0
activeVideoIndex = 0
inTransition = false
transitionStartTime = 0
glitchOn = false
durationCheck = false
##Static Defaults
fadeOutTime = 5000
tickInterval = 100
effectPlugins = {}
currentEffect=null
debug = ()->
abspath = 'G:\\Projects\\YoutubeDownload\\'
$("#opacity").on('input',()->
## blend.opacity = $("#opacity").val()
)
video1[0].src = abspath+'<NAME> feat. Crystal Waters - Destination Calabria [Explicit Version] [Official Video].mp4'
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
)
video2[0].src = abspath+'Major Lazer – Light it Up (feat. Nyla & Fuse ODG) [Music Video Remix] by Method Studios.mp4'
video2[0].load()
video2[0].addEventListener("canplaythrough",()->
@play()
)
video1[0].volume=0
video2[0].volume=0
transitionStartTime = clock
activeVideoIndex =2
inTransition = true
setUpEffectPlugins = (inNode,outNode)->
initEffect("ascii")
initEffect("hex")
initEffect("invert")
initEffect("sketch")
initEffect("kaleidoscope")
initEffect("nightvision")
pluginParams =[]
for plugin in effectPlugins
pluginParams.push(
Name: plugin.effect
Params: plugin.inputs()
)
ipcRenderer.send('effect-params', pluginParams)
initEffect = (effectName)->
temp = seriously.effect(effectName)
effectPlugins[temp.effect] = temp
##effectPlugins.push(temp)
##temp.on(temp.effect+'-on')
##temp.off((temp.effect+'-off'))
temp.source = blend
return temp
init = ()->
video1[0].playbackRate = 1
video2[0].playbackRate = 1
target = seriously.target('#canvas')
reformat.width = target.width
reformat.height = target.height
reformat.mode = 'cover'
#reformat.source = seriously.source('#video1')
blend.bottom = seriously.source('#video1')
blend.top = seriously.source('#video2')
setUpEffectPlugins(vignette,reformat)
vignette.source = blend
target.source = reformat;
reformat.source = vignette
seriously.go()
window.setInterval(onTick,tickInterval)
setTimeout(startGlitch, 10000+Math.random()*60000)
$('#btnFullscreen').click(()->
canvas[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)
)
$('#video').on("timeupdate",()->
dostuff =1
)
ipcRenderer.on('video-load', (event, arg) =>
abspath = 'G:\\Projects\\YoutubeDownload\\' + arg.Path
video1[0].src = abspath
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
)
)
ipcRenderer.on('stage-video', (event, arg) =>
console.log('staging')
transitionWindow()
abspath = 'G:\\Projects\\YoutubeDownload\\' + arg.Path
if(activeVideoIndex ==1)
video1[0].src = abspath
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
durationCheck = true
)
else
video2[0].src = abspath
video2[0].load()
video2[0].addEventListener("canplaythrough",()->
@play()
durationCheck = true
)
)
ipcRenderer.on('change-effect', (event, arg) =>
console.log(arg)
if(arg.Name == 'None')
currentEffect = null
vignette.source=blend
else
if(currentEffect ==null || currentEffect.effect != arg.Name)
currentEffect = effectPlugins[arg.Name]
vignette.source = currentEffect
if(arg.field)
currentEffect[arg.field] = arg.value
)
checkDurationContitions=()->
if(durationCheck)
if(activeVideoIndex ==1)
if(video1[0].duration-video1[0].currentTime<=fadeOutTime/1000)
ipcRenderer.send('request-video', true)
durationCheck = false
else
if(video2[0].duration-video2[0].currentTime<=fadeOutTime/1000)
ipcRenderer.send('request-video', true)
durationCheck = false
startGlitch=()->
tvGlitch = seriously.effect('tvglitch')
tvGlitch.source =vignette
setTimeout(endGlitch, Math.random()*1000)
endGlitch=()->
reformat.source = vignette
tvGlitch.destroy()
tvGlitch = null
setTimeout(startGlitch, 10000+Math.random()*60000)
transitionWindow = ()->
inTransition = true
transitionStartTime = clock
if(activeVideoIndex == 1)
activeVideoIndex = 2
else
activeVideoIndex = 1
onTick = ()->
clock = clock+tickInterval
if(inTransition)
updateTransitions()
updateVignette()
checkDurationContitions()
updateVignette=()->
vignette.amount = 1+2*Math.sin(clock/12000)+Math.random()/2
updateTransitions=()->
currentDuration = clock-transitionStartTime
if(currentDuration>=fadeOutTime)
if(activeVideoIndex ==1)
blend.opacity = 0
video1[0].volume=1
video2[0].volume=0
else
blend.opacity =1
video1[0].volume=0
video2[0].volume=1
blend.inTransition = false
else
alpha =(clock-transitionStartTime)/fadeOutTime
if(activeVideoIndex ==1)
blend.opacity = 1-alpha
video1[0].volume=alpha
video2[0].volume=1-alpha
else
blend.opacity =alpha
video1[0].volume=1-alpha
video2[0].volume=alpha
init()
##debug()
)
| true | $(document).ready(()->
###Global Vars###
video1 = $('#video1')
video2 = $('#video2')
canvas = $('#canvas')
seriously = new Seriously()
reformat = seriously.transform('reformat')
vignette = seriously.effect("vignette")
tvGlitch = null
blend = seriously.effect('blend')
{ipcRenderer} = require('electron')
effectList = []
###Runtime flags ###
clock = 0
activeVideoIndex = 0
inTransition = false
transitionStartTime = 0
glitchOn = false
durationCheck = false
##Static Defaults
fadeOutTime = 5000
tickInterval = 100
effectPlugins = {}
currentEffect=null
debug = ()->
abspath = 'G:\\Projects\\YoutubeDownload\\'
$("#opacity").on('input',()->
## blend.opacity = $("#opacity").val()
)
video1[0].src = abspath+'PI:NAME:<NAME>END_PI feat. Crystal Waters - Destination Calabria [Explicit Version] [Official Video].mp4'
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
)
video2[0].src = abspath+'Major Lazer – Light it Up (feat. Nyla & Fuse ODG) [Music Video Remix] by Method Studios.mp4'
video2[0].load()
video2[0].addEventListener("canplaythrough",()->
@play()
)
video1[0].volume=0
video2[0].volume=0
transitionStartTime = clock
activeVideoIndex =2
inTransition = true
setUpEffectPlugins = (inNode,outNode)->
initEffect("ascii")
initEffect("hex")
initEffect("invert")
initEffect("sketch")
initEffect("kaleidoscope")
initEffect("nightvision")
pluginParams =[]
for plugin in effectPlugins
pluginParams.push(
Name: plugin.effect
Params: plugin.inputs()
)
ipcRenderer.send('effect-params', pluginParams)
initEffect = (effectName)->
temp = seriously.effect(effectName)
effectPlugins[temp.effect] = temp
##effectPlugins.push(temp)
##temp.on(temp.effect+'-on')
##temp.off((temp.effect+'-off'))
temp.source = blend
return temp
init = ()->
video1[0].playbackRate = 1
video2[0].playbackRate = 1
target = seriously.target('#canvas')
reformat.width = target.width
reformat.height = target.height
reformat.mode = 'cover'
#reformat.source = seriously.source('#video1')
blend.bottom = seriously.source('#video1')
blend.top = seriously.source('#video2')
setUpEffectPlugins(vignette,reformat)
vignette.source = blend
target.source = reformat;
reformat.source = vignette
seriously.go()
window.setInterval(onTick,tickInterval)
setTimeout(startGlitch, 10000+Math.random()*60000)
$('#btnFullscreen').click(()->
canvas[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)
)
$('#video').on("timeupdate",()->
dostuff =1
)
ipcRenderer.on('video-load', (event, arg) =>
abspath = 'G:\\Projects\\YoutubeDownload\\' + arg.Path
video1[0].src = abspath
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
)
)
ipcRenderer.on('stage-video', (event, arg) =>
console.log('staging')
transitionWindow()
abspath = 'G:\\Projects\\YoutubeDownload\\' + arg.Path
if(activeVideoIndex ==1)
video1[0].src = abspath
video1[0].load()
video1[0].addEventListener("canplaythrough",()->
@play()
durationCheck = true
)
else
video2[0].src = abspath
video2[0].load()
video2[0].addEventListener("canplaythrough",()->
@play()
durationCheck = true
)
)
ipcRenderer.on('change-effect', (event, arg) =>
console.log(arg)
if(arg.Name == 'None')
currentEffect = null
vignette.source=blend
else
if(currentEffect ==null || currentEffect.effect != arg.Name)
currentEffect = effectPlugins[arg.Name]
vignette.source = currentEffect
if(arg.field)
currentEffect[arg.field] = arg.value
)
checkDurationContitions=()->
if(durationCheck)
if(activeVideoIndex ==1)
if(video1[0].duration-video1[0].currentTime<=fadeOutTime/1000)
ipcRenderer.send('request-video', true)
durationCheck = false
else
if(video2[0].duration-video2[0].currentTime<=fadeOutTime/1000)
ipcRenderer.send('request-video', true)
durationCheck = false
startGlitch=()->
tvGlitch = seriously.effect('tvglitch')
tvGlitch.source =vignette
setTimeout(endGlitch, Math.random()*1000)
endGlitch=()->
reformat.source = vignette
tvGlitch.destroy()
tvGlitch = null
setTimeout(startGlitch, 10000+Math.random()*60000)
transitionWindow = ()->
inTransition = true
transitionStartTime = clock
if(activeVideoIndex == 1)
activeVideoIndex = 2
else
activeVideoIndex = 1
onTick = ()->
clock = clock+tickInterval
if(inTransition)
updateTransitions()
updateVignette()
checkDurationContitions()
updateVignette=()->
vignette.amount = 1+2*Math.sin(clock/12000)+Math.random()/2
updateTransitions=()->
currentDuration = clock-transitionStartTime
if(currentDuration>=fadeOutTime)
if(activeVideoIndex ==1)
blend.opacity = 0
video1[0].volume=1
video2[0].volume=0
else
blend.opacity =1
video1[0].volume=0
video2[0].volume=1
blend.inTransition = false
else
alpha =(clock-transitionStartTime)/fadeOutTime
if(activeVideoIndex ==1)
blend.opacity = 1-alpha
video1[0].volume=alpha
video2[0].volume=1-alpha
else
blend.opacity =alpha
video1[0].volume=1-alpha
video2[0].volume=alpha
init()
##debug()
)
|
[
{
"context": "ataQuery.from({\n flow: 'EXR'\n key: 'A..EUR.SP00.A'\n provider: 'ECB'\n obsDimension: 'C",
"end": 16236,
"score": 0.9990198612213135,
"start": 16223,
"tag": "KEY",
"value": "A..EUR.SP00.A"
},
{
"context": "\n query = DataQuery.from({flo... | test/utils/url-generator.test.coffee | sosna/sdmx-rest.js | 16 | should = require('chai').should()
{Service} = require '../../src/service/service'
{ApiVersion} = require '../../src/utils/api-version'
{DataQuery} = require '../../src/data/data-query'
{MetadataQuery} = require '../../src/metadata/metadata-query'
{AvailabilityQuery} = require '../../src/avail/availability-query'
{SchemaQuery} = require '../../src/schema/schema-query'
{UrlGenerator} = require '../../src/utils/url-generator'
describe 'URL Generator', ->
describe 'for metadata queries', ->
it 'generates a URL for a metadata query', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/codelist/ECB/CL_FREQ/\
latest?detail=full&references=none"
query =
MetadataQuery.from({resource: 'codelist', id: 'CL_FREQ', agency: 'ECB'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a metadata ItemScheme query', ->
expected = "http://test.com/service/codelist/all/all/\
latest/all?detail=full&references=none"
query = MetadataQuery.from({resource: 'codelist'})
service = Service.from({url: "http://test.com/service/"})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a metadata non-ItemScheme query', ->
expected = "http://test.com/service/dataflow/all/all/\
latest?detail=full&references=none"
query = MetadataQuery.from({resource: 'dataflow'})
service = Service.from({url: "http://test.com/service/"})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports item queries for API version 1.1.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/latest/A\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support item queries before API version 1.1.0', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/latest\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'treats hierarchical codelists as item schemes for API version 1.2.0', ->
expected = "http://test.com/hierarchicalcodelist/BIS/HCL/latest/HIERARCHY\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'BIS'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support hiearchy queries before API version 1.2.0', ->
expected = "http://test.com/hierarchicalcodelist/BIS/HCL/latest\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'BIS'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports multiple agencies for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB+BIS/CL_FREQ/latest/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB+BIS'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple agencies before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB+BIS'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple agencies not allowed in v1.2.0')
it 'supports multiple IDs for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ+CL_DECIMALS/latest/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ+CL_DECIMALS'
agency: 'ECB'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple agencies before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ+CL_DECIMALS'
agency: 'ECB'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple IDs not allowed in v1.2.0')
it 'supports multiple versions for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/1.0+1.1/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0+1.1'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple versions before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0+1.1'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple versions not allowed in v1.1.0')
it 'supports multiple items for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/1.0/A+M\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0'
item: 'A+M'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple items before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0'
item: 'A+M'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple items not allowed in v1.2.0')
it 'defaults to latest API version', ->
expected = "http://test.com/hierarchicalcodelist/ECB/HCL/latest/HIERARCHY\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'ECB'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for metadata', ->
expected = "http://test.com/codelist"
query = MetadataQuery.from({resource: 'codelist'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (id)', ->
expected = "http://test.com/codelist/all/CL_FREQ"
query = MetadataQuery.from({resource: 'codelist', id: 'CL_FREQ'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (version)', ->
expected = "http://test.com/codelist/all/all/42"
query = MetadataQuery.from({resource: 'codelist', version: '42'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (item)', ->
expected = "http://test.com/codelist/all/all/latest/1"
query = MetadataQuery.from({resource: 'codelist', item: '1'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (item, old API)', ->
expected = "http://test.com/codelist"
query = MetadataQuery.from({resource: 'codelist', item: '1'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail)', ->
expected = "http://test.com/codelist?detail=allstubs"
query = MetadataQuery.from({resource: 'codelist', detail: 'allstubs'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (references)', ->
expected = "http://test.com/codelist?references=datastructure"
query = MetadataQuery.from({
resource: 'codelist'
references: 'datastructure'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail & refs)', ->
expected = "http://test.com/codelist?detail=allstubs&references=datastructure"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allstubs'
references: 'datastructure'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports referencepartial since v1.3.0', ->
expected = "http://test.com/codelist?detail=referencepartial"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencepartial'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports allcompletestubs since v1.3.0', ->
expected = "http://test.com/codelist?detail=allcompletestubs"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allcompletestubs'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports referencecompletestubs since v1.3.0', ->
expected = "http://test.com/codelist?detail=referencecompletestubs"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencecompletestubs'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support referencepartial before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencepartial'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'referencepartial not allowed in v1.1.0')
it 'does not support allcompletestubs before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allcompletestubs'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'allcompletestubs not allowed in v1.2.0')
it 'does not support referencecompletestubs before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencecompletestubs'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'referencecompletestubs not allowed in v1.0.2')
it 'supports actualconstraint since v1.3.0', ->
expected = 'http://test.com/actualconstraint'
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports allowedconstraint since v1.3.0', ->
expected = 'http://test.com/allowedconstraint'
query = MetadataQuery.from({resource: 'allowedconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support actualconstraint before v1.3.0', ->
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'actualconstraint not allowed in v1.2.0')
it 'does not support allowedconstraint before v1.3.0', ->
query = MetadataQuery.from({resource: 'allowedconstraint'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'allowedconstraint not allowed in v1.0.2')
it 'supports actualconstraint since v1.3.0', ->
expected = 'http://test.com/actualconstraint'
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports VTL artefacts since v1.5.0 (type)', ->
expected = 'http://test.com/transformationscheme'
query = MetadataQuery.from({resource: 'transformationscheme'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support VTL artefacts before v1.5.0 (type)', ->
query = MetadataQuery.from({resource: 'transformationscheme'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'transformationscheme not allowed in v1.2.0')
it 'supports VTL artefacts since v1.5.0 (references)', ->
expected = 'http://test.com/codelist?references=transformationscheme'
query = MetadataQuery.from({resource: 'codelist', references: 'transformationscheme'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support VTL artefacts before v1.5.0 (references)', ->
query = MetadataQuery.from({resource: 'codelist', references: 'transformationscheme'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'transformationscheme not allowed as reference in v1.2.0')
describe 'for data queries', ->
it 'generates a URL for a full data query', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata&includeHistory=true\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: 'A..EUR.SP00.A'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({
url: 'http://test.com'
api: ApiVersion.v1_1_0
})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a partial data query', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/all?\
detail=full&includeHistory=false"
query = DataQuery.from({flow: 'EXR', key: 'A..EUR.SP00.A'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports history but only for API version 1.1.0 and above', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: 'A..EUR.SP00.A'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'defaults to latest API', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata&includeHistory=true\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: 'A..EUR.SP00.A'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for data', ->
expected = "http://test.com/data/EXR"
query = DataQuery.from({flow: 'EXR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (provider)', ->
expected = "http://test.com/data/EXR/all/ECB"
query = DataQuery.from({flow: 'EXR', provider: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (start)', ->
expected = "http://test.com/data/EXR?startPeriod=2010"
query = DataQuery.from({flow: 'EXR', start: '2010'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (end)', ->
expected = "http://test.com/data/EXR?endPeriod=2010"
query = DataQuery.from({flow: 'EXR', end: '2010'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (updatedAfter)', ->
expected = "http://test.com/data/EXR?updatedAfter=2016-03-01T00:00:00Z"
query = DataQuery.from({
flow: 'EXR'
updatedAfter: '2016-03-01T00:00:00Z'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (firstNObs)', ->
expected = "http://test.com/data/EXR?firstNObservations=1"
query = DataQuery.from({flow: 'EXR', firstNObs: 1})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (lastNObs)', ->
expected = "http://test.com/data/EXR?lastNObservations=2"
query = DataQuery.from({flow: 'EXR', lastNObs: 2})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail)', ->
expected = "http://test.com/data/EXR?detail=dataonly"
query = DataQuery.from({flow: 'EXR', detail: 'dataonly'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (history)', ->
expected = "http://test.com/data/EXR?includeHistory=true"
query = DataQuery.from({flow: 'EXR', history: true})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (obsDim)', ->
expected = "http://test.com/data/EXR?dimensionAtObservation=CURR"
query = DataQuery.from({flow: 'EXR', obsDimension: 'CURR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (various)', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A?\
updatedAfter=2016-03-01T00:00:00Z\
&startPeriod=2010&dimensionAtObservation=CURRENCY"
query = DataQuery.from({
flow: 'EXR'
key: 'A..EUR.SP00.A'
obsDimension: 'CURRENCY'
start: '2010'
updatedAfter: '2016-03-01T00:00:00Z'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports multiple providers for API version 1.3.0 and above', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/SDMX,ECB+BIS?\
updatedAfter=2016-03-01T00:00:00Z\
&startPeriod=2010&dimensionAtObservation=CURRENCY"
query = DataQuery.from({
flow: 'EXR'
key: 'A..EUR.SP00.A'
obsDimension: 'CURRENCY'
start: '2010'
updatedAfter: '2016-03-01T00:00:00Z'
provider: ['SDMX,ECB', 'BIS']
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support providers before API version 1.3.0', ->
query = DataQuery.from({flow: 'EXR', provider: 'SDMX,ECB+BIS'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple providers not allowed in v1.2.0')
it 'throws an exception if no query is supplied', ->
test = -> new UrlGenerator().getUrl()
should.Throw(test, Error,
'not a valid SDMX data, metadata or availability query')
it 'throws an exception if the input is not a data or a metadata query', ->
test = -> new UrlGenerator().getUrl({test: 'Test'})
should.Throw(test, TypeError,
'not a valid SDMX data, metadata or availability query')
it 'throws an exception if no service is supplied', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
test = -> new UrlGenerator().getUrl query
should.Throw(test, Error, 'not a valid service')
it 'throws an exception if a service without a URL is supplied', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
test = -> new UrlGenerator().getUrl query, {id: 'test'}
should.Throw(test, ReferenceError, 'not a valid service')
describe 'for availability queries', ->
it 'generates a URL for a full availability query', ->
expected = 'http://test.com/availableconstraint/EXR/A..EUR.SP00.A/ECB/FREQ?\
mode=available&references=none\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z'
query = AvailabilityQuery.from({
flow: 'EXR'
key: 'A..EUR.SP00.A'
provider: 'ECB'
component: 'FREQ'
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
mode: 'available'
references: 'none'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a partial availability query', ->
expected = 'http://test.com/availableconstraint/EXR/A..EUR.SP00.A/all/all?\
mode=exact&references=none'
query = AvailabilityQuery.from({flow: 'EXR', key: 'A..EUR.SP00.A'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports minimal query if proper query class is used', ->
expected = 'http://test.com/availableconstraint/EXR/all/all/all?\
mode=exact&references=none'
query = AvailabilityQuery.from({flow: 'EXR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support availability queries before v1.3.0', ->
query = AvailabilityQuery.from({flow: 'EXR', key: 'A..EUR.SP00.A'})
service = Service.from({url: 'http://test.com', api: 'v1.2.0'})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Availability query not supported in v1.2.0')
it 'offers to skip default values for availability', ->
expected = 'http://test.com/availableconstraint/EXR'
query = AvailabilityQuery.from({
flow: 'EXR'
mode: 'exact'
references: 'none'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (provider)', ->
expected = 'http://test.com/availableconstraint/EXR/all/ECB'
query = AvailabilityQuery.from({flow: 'EXR', provider: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (component)', ->
expected = 'http://test.com/availableconstraint/EXR/all/all/FREQ'
query = AvailabilityQuery.from({flow: 'EXR', component: 'FREQ'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (mode)', ->
expected = 'http://test.com/availableconstraint/EXR?mode=available'
query = AvailabilityQuery.from({flow: 'EXR', mode: 'available'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (references)', ->
expected = 'http://test.com/availableconstraint/EXR?references=codelist'
query = AvailabilityQuery.from({flow: 'EXR', references: 'codelist'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (start)', ->
expected = 'http://test.com/availableconstraint/EXR?startPeriod=2007'
query = AvailabilityQuery.from({flow: 'EXR', start: '2007'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (end)', ->
expected = 'http://test.com/availableconstraint/EXR?endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (start & ed)', ->
expected = 'http://test.com/availableconstraint/EXR?startPeriod=2007&\
endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', start: '2007', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (end)', ->
expected = 'http://test.com/availableconstraint/EXR?endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (updatedAfter)', ->
expected = 'http://test.com/availableconstraint/EXR?\
updatedAfter=2016-03-01T00:00:00Z'
query = AvailabilityQuery.from({
flow: 'EXR'
updatedAfter: '2016-03-01T00:00:00Z'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
describe 'for schema queries', ->
it 'generates a URL for a schema query', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/schema/dataflow\
/ECB/EXR/latest?explicitMeasure=false"
query = SchemaQuery.from({context: 'dataflow', id: 'EXR', agency: 'ECB'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a schema query (with dimensionAtObservation)', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/schema/dataflow\
/ECB/EXR/latest?explicitMeasure=false&dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', obsDimension: 'TEST'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for schema', ->
expected = "http://test.com/schema/dataflow/ECB/EXR"
query = SchemaQuery.from({context: 'dataflow', id: 'EXR', agency: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (version)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR/1.1"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', version: '1.1'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (explicit)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR?explicitMeasure=true"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', explicit: true})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (obsDimension)', ->
expected =
"http://test.com/schema/dataflow/ECB/EXR?dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', obsDimension: 'TEST'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (query params)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR?explicitMeasure=true\
&dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', explicit: true,
obsDimension: 'TEST'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
| 69933 | should = require('chai').should()
{Service} = require '../../src/service/service'
{ApiVersion} = require '../../src/utils/api-version'
{DataQuery} = require '../../src/data/data-query'
{MetadataQuery} = require '../../src/metadata/metadata-query'
{AvailabilityQuery} = require '../../src/avail/availability-query'
{SchemaQuery} = require '../../src/schema/schema-query'
{UrlGenerator} = require '../../src/utils/url-generator'
describe 'URL Generator', ->
describe 'for metadata queries', ->
it 'generates a URL for a metadata query', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/codelist/ECB/CL_FREQ/\
latest?detail=full&references=none"
query =
MetadataQuery.from({resource: 'codelist', id: 'CL_FREQ', agency: 'ECB'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a metadata ItemScheme query', ->
expected = "http://test.com/service/codelist/all/all/\
latest/all?detail=full&references=none"
query = MetadataQuery.from({resource: 'codelist'})
service = Service.from({url: "http://test.com/service/"})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a metadata non-ItemScheme query', ->
expected = "http://test.com/service/dataflow/all/all/\
latest?detail=full&references=none"
query = MetadataQuery.from({resource: 'dataflow'})
service = Service.from({url: "http://test.com/service/"})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports item queries for API version 1.1.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/latest/A\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support item queries before API version 1.1.0', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/latest\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'treats hierarchical codelists as item schemes for API version 1.2.0', ->
expected = "http://test.com/hierarchicalcodelist/BIS/HCL/latest/HIERARCHY\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'BIS'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support hiearchy queries before API version 1.2.0', ->
expected = "http://test.com/hierarchicalcodelist/BIS/HCL/latest\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'BIS'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports multiple agencies for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB+BIS/CL_FREQ/latest/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB+BIS'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple agencies before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB+BIS'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple agencies not allowed in v1.2.0')
it 'supports multiple IDs for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ+CL_DECIMALS/latest/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ+CL_DECIMALS'
agency: 'ECB'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple agencies before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ+CL_DECIMALS'
agency: 'ECB'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple IDs not allowed in v1.2.0')
it 'supports multiple versions for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/1.0+1.1/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0+1.1'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple versions before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0+1.1'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple versions not allowed in v1.1.0')
it 'supports multiple items for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/1.0/A+M\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0'
item: 'A+M'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple items before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0'
item: 'A+M'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple items not allowed in v1.2.0')
it 'defaults to latest API version', ->
expected = "http://test.com/hierarchicalcodelist/ECB/HCL/latest/HIERARCHY\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'ECB'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for metadata', ->
expected = "http://test.com/codelist"
query = MetadataQuery.from({resource: 'codelist'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (id)', ->
expected = "http://test.com/codelist/all/CL_FREQ"
query = MetadataQuery.from({resource: 'codelist', id: 'CL_FREQ'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (version)', ->
expected = "http://test.com/codelist/all/all/42"
query = MetadataQuery.from({resource: 'codelist', version: '42'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (item)', ->
expected = "http://test.com/codelist/all/all/latest/1"
query = MetadataQuery.from({resource: 'codelist', item: '1'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (item, old API)', ->
expected = "http://test.com/codelist"
query = MetadataQuery.from({resource: 'codelist', item: '1'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail)', ->
expected = "http://test.com/codelist?detail=allstubs"
query = MetadataQuery.from({resource: 'codelist', detail: 'allstubs'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (references)', ->
expected = "http://test.com/codelist?references=datastructure"
query = MetadataQuery.from({
resource: 'codelist'
references: 'datastructure'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail & refs)', ->
expected = "http://test.com/codelist?detail=allstubs&references=datastructure"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allstubs'
references: 'datastructure'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports referencepartial since v1.3.0', ->
expected = "http://test.com/codelist?detail=referencepartial"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencepartial'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports allcompletestubs since v1.3.0', ->
expected = "http://test.com/codelist?detail=allcompletestubs"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allcompletestubs'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports referencecompletestubs since v1.3.0', ->
expected = "http://test.com/codelist?detail=referencecompletestubs"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencecompletestubs'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support referencepartial before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencepartial'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'referencepartial not allowed in v1.1.0')
it 'does not support allcompletestubs before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allcompletestubs'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'allcompletestubs not allowed in v1.2.0')
it 'does not support referencecompletestubs before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencecompletestubs'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'referencecompletestubs not allowed in v1.0.2')
it 'supports actualconstraint since v1.3.0', ->
expected = 'http://test.com/actualconstraint'
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports allowedconstraint since v1.3.0', ->
expected = 'http://test.com/allowedconstraint'
query = MetadataQuery.from({resource: 'allowedconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support actualconstraint before v1.3.0', ->
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'actualconstraint not allowed in v1.2.0')
it 'does not support allowedconstraint before v1.3.0', ->
query = MetadataQuery.from({resource: 'allowedconstraint'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'allowedconstraint not allowed in v1.0.2')
it 'supports actualconstraint since v1.3.0', ->
expected = 'http://test.com/actualconstraint'
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports VTL artefacts since v1.5.0 (type)', ->
expected = 'http://test.com/transformationscheme'
query = MetadataQuery.from({resource: 'transformationscheme'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support VTL artefacts before v1.5.0 (type)', ->
query = MetadataQuery.from({resource: 'transformationscheme'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'transformationscheme not allowed in v1.2.0')
it 'supports VTL artefacts since v1.5.0 (references)', ->
expected = 'http://test.com/codelist?references=transformationscheme'
query = MetadataQuery.from({resource: 'codelist', references: 'transformationscheme'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support VTL artefacts before v1.5.0 (references)', ->
query = MetadataQuery.from({resource: 'codelist', references: 'transformationscheme'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'transformationscheme not allowed as reference in v1.2.0')
describe 'for data queries', ->
it 'generates a URL for a full data query', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata&includeHistory=true\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: '<KEY>'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({
url: 'http://test.com'
api: ApiVersion.v1_1_0
})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a partial data query', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/all?\
detail=full&includeHistory=false"
query = DataQuery.from({flow: 'EXR', key: '<KEY>'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports history but only for API version 1.1.0 and above', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: '<KEY>'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'defaults to latest API', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata&includeHistory=true\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: '<KEY>'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for data', ->
expected = "http://test.com/data/EXR"
query = DataQuery.from({flow: 'EXR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (provider)', ->
expected = "http://test.com/data/EXR/all/ECB"
query = DataQuery.from({flow: 'EXR', provider: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (start)', ->
expected = "http://test.com/data/EXR?startPeriod=2010"
query = DataQuery.from({flow: 'EXR', start: '2010'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (end)', ->
expected = "http://test.com/data/EXR?endPeriod=2010"
query = DataQuery.from({flow: 'EXR', end: '2010'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (updatedAfter)', ->
expected = "http://test.com/data/EXR?updatedAfter=2016-03-01T00:00:00Z"
query = DataQuery.from({
flow: 'EXR'
updatedAfter: '2016-03-01T00:00:00Z'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (firstNObs)', ->
expected = "http://test.com/data/EXR?firstNObservations=1"
query = DataQuery.from({flow: 'EXR', firstNObs: 1})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (lastNObs)', ->
expected = "http://test.com/data/EXR?lastNObservations=2"
query = DataQuery.from({flow: 'EXR', lastNObs: 2})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail)', ->
expected = "http://test.com/data/EXR?detail=dataonly"
query = DataQuery.from({flow: 'EXR', detail: 'dataonly'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (history)', ->
expected = "http://test.com/data/EXR?includeHistory=true"
query = DataQuery.from({flow: 'EXR', history: true})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (obsDim)', ->
expected = "http://test.com/data/EXR?dimensionAtObservation=CURR"
query = DataQuery.from({flow: 'EXR', obsDimension: 'CURR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (various)', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A?\
updatedAfter=2016-03-01T00:00:00Z\
&startPeriod=2010&dimensionAtObservation=CURRENCY"
query = DataQuery.from({
flow: 'EXR'
key: '<KEY>'
obsDimension: 'CURRENCY'
start: '2010'
updatedAfter: '2016-03-01T00:00:00Z'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports multiple providers for API version 1.3.0 and above', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/SDMX,ECB+BIS?\
updatedAfter=2016-03-01T00:00:00Z\
&startPeriod=2010&dimensionAtObservation=CURRENCY"
query = DataQuery.from({
flow: 'EXR'
key: '<KEY>A'
obsDimension: 'CURRENCY'
start: '2010'
updatedAfter: '2016-03-01T00:00:00Z'
provider: ['SDMX,ECB', 'BIS']
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support providers before API version 1.3.0', ->
query = DataQuery.from({flow: 'EXR', provider: 'SDMX,ECB+BIS'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple providers not allowed in v1.2.0')
it 'throws an exception if no query is supplied', ->
test = -> new UrlGenerator().getUrl()
should.Throw(test, Error,
'not a valid SDMX data, metadata or availability query')
it 'throws an exception if the input is not a data or a metadata query', ->
test = -> new UrlGenerator().getUrl({test: 'Test'})
should.Throw(test, TypeError,
'not a valid SDMX data, metadata or availability query')
it 'throws an exception if no service is supplied', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
test = -> new UrlGenerator().getUrl query
should.Throw(test, Error, 'not a valid service')
it 'throws an exception if a service without a URL is supplied', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
test = -> new UrlGenerator().getUrl query, {id: 'test'}
should.Throw(test, ReferenceError, 'not a valid service')
describe 'for availability queries', ->
it 'generates a URL for a full availability query', ->
expected = 'http://test.com/availableconstraint/EXR/A..EUR.SP00.A/ECB/FREQ?\
mode=available&references=none\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z'
query = AvailabilityQuery.from({
flow: 'EXR'
key: '<KEY>'
provider: 'ECB'
component: 'FREQ'
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
mode: 'available'
references: 'none'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a partial availability query', ->
expected = 'http://test.com/availableconstraint/EXR/A..EUR.SP00.A/all/all?\
mode=exact&references=none'
query = AvailabilityQuery.from({flow: 'EXR', key: '<KEY>'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports minimal query if proper query class is used', ->
expected = 'http://test.com/availableconstraint/EXR/all/all/all?\
mode=exact&references=none'
query = AvailabilityQuery.from({flow: 'EXR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support availability queries before v1.3.0', ->
query = AvailabilityQuery.from({flow: 'EXR', key: '<KEY>'})
service = Service.from({url: 'http://test.com', api: 'v1.2.0'})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Availability query not supported in v1.2.0')
it 'offers to skip default values for availability', ->
expected = 'http://test.com/availableconstraint/EXR'
query = AvailabilityQuery.from({
flow: 'EXR'
mode: 'exact'
references: 'none'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (provider)', ->
expected = 'http://test.com/availableconstraint/EXR/all/ECB'
query = AvailabilityQuery.from({flow: 'EXR', provider: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (component)', ->
expected = 'http://test.com/availableconstraint/EXR/all/all/FREQ'
query = AvailabilityQuery.from({flow: 'EXR', component: 'FREQ'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (mode)', ->
expected = 'http://test.com/availableconstraint/EXR?mode=available'
query = AvailabilityQuery.from({flow: 'EXR', mode: 'available'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (references)', ->
expected = 'http://test.com/availableconstraint/EXR?references=codelist'
query = AvailabilityQuery.from({flow: 'EXR', references: 'codelist'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (start)', ->
expected = 'http://test.com/availableconstraint/EXR?startPeriod=2007'
query = AvailabilityQuery.from({flow: 'EXR', start: '2007'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (end)', ->
expected = 'http://test.com/availableconstraint/EXR?endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (start & ed)', ->
expected = 'http://test.com/availableconstraint/EXR?startPeriod=2007&\
endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', start: '2007', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (end)', ->
expected = 'http://test.com/availableconstraint/EXR?endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (updatedAfter)', ->
expected = 'http://test.com/availableconstraint/EXR?\
updatedAfter=2016-03-01T00:00:00Z'
query = AvailabilityQuery.from({
flow: 'EXR'
updatedAfter: '2016-03-01T00:00:00Z'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
describe 'for schema queries', ->
it 'generates a URL for a schema query', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/schema/dataflow\
/ECB/EXR/latest?explicitMeasure=false"
query = SchemaQuery.from({context: 'dataflow', id: 'EXR', agency: 'ECB'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a schema query (with dimensionAtObservation)', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/schema/dataflow\
/ECB/EXR/latest?explicitMeasure=false&dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', obsDimension: 'TEST'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for schema', ->
expected = "http://test.com/schema/dataflow/ECB/EXR"
query = SchemaQuery.from({context: 'dataflow', id: 'EXR', agency: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (version)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR/1.1"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', version: '1.1'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (explicit)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR?explicitMeasure=true"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', explicit: true})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (obsDimension)', ->
expected =
"http://test.com/schema/dataflow/ECB/EXR?dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', obsDimension: 'TEST'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (query params)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR?explicitMeasure=true\
&dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', explicit: true,
obsDimension: 'TEST'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
| true | should = require('chai').should()
{Service} = require '../../src/service/service'
{ApiVersion} = require '../../src/utils/api-version'
{DataQuery} = require '../../src/data/data-query'
{MetadataQuery} = require '../../src/metadata/metadata-query'
{AvailabilityQuery} = require '../../src/avail/availability-query'
{SchemaQuery} = require '../../src/schema/schema-query'
{UrlGenerator} = require '../../src/utils/url-generator'
describe 'URL Generator', ->
describe 'for metadata queries', ->
it 'generates a URL for a metadata query', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/codelist/ECB/CL_FREQ/\
latest?detail=full&references=none"
query =
MetadataQuery.from({resource: 'codelist', id: 'CL_FREQ', agency: 'ECB'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a metadata ItemScheme query', ->
expected = "http://test.com/service/codelist/all/all/\
latest/all?detail=full&references=none"
query = MetadataQuery.from({resource: 'codelist'})
service = Service.from({url: "http://test.com/service/"})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a metadata non-ItemScheme query', ->
expected = "http://test.com/service/dataflow/all/all/\
latest?detail=full&references=none"
query = MetadataQuery.from({resource: 'dataflow'})
service = Service.from({url: "http://test.com/service/"})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports item queries for API version 1.1.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/latest/A\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support item queries before API version 1.1.0', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/latest\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'treats hierarchical codelists as item schemes for API version 1.2.0', ->
expected = "http://test.com/hierarchicalcodelist/BIS/HCL/latest/HIERARCHY\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'BIS'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support hiearchy queries before API version 1.2.0', ->
expected = "http://test.com/hierarchicalcodelist/BIS/HCL/latest\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'BIS'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports multiple agencies for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB+BIS/CL_FREQ/latest/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB+BIS'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple agencies before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB+BIS'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple agencies not allowed in v1.2.0')
it 'supports multiple IDs for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ+CL_DECIMALS/latest/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ+CL_DECIMALS'
agency: 'ECB'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple agencies before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ+CL_DECIMALS'
agency: 'ECB'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple IDs not allowed in v1.2.0')
it 'supports multiple versions for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/1.0+1.1/all\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0+1.1'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple versions before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0+1.1'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple versions not allowed in v1.1.0')
it 'supports multiple items for API version 1.3.0 and above', ->
expected = "http://test.com/codelist/ECB/CL_FREQ/1.0/A+M\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0'
item: 'A+M'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support multiple items before API version 1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
version: '1.0'
item: 'A+M'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple items not allowed in v1.2.0')
it 'defaults to latest API version', ->
expected = "http://test.com/hierarchicalcodelist/ECB/HCL/latest/HIERARCHY\
?detail=full&references=none"
query = MetadataQuery.from({
resource: 'hierarchicalcodelist'
id: 'HCL'
agency: 'ECB'
item: 'HIERARCHY'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for metadata', ->
expected = "http://test.com/codelist"
query = MetadataQuery.from({resource: 'codelist'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (id)', ->
expected = "http://test.com/codelist/all/CL_FREQ"
query = MetadataQuery.from({resource: 'codelist', id: 'CL_FREQ'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (version)', ->
expected = "http://test.com/codelist/all/all/42"
query = MetadataQuery.from({resource: 'codelist', version: '42'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (item)', ->
expected = "http://test.com/codelist/all/all/latest/1"
query = MetadataQuery.from({resource: 'codelist', item: '1'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (item, old API)', ->
expected = "http://test.com/codelist"
query = MetadataQuery.from({resource: 'codelist', item: '1'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail)', ->
expected = "http://test.com/codelist?detail=allstubs"
query = MetadataQuery.from({resource: 'codelist', detail: 'allstubs'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (references)', ->
expected = "http://test.com/codelist?references=datastructure"
query = MetadataQuery.from({
resource: 'codelist'
references: 'datastructure'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail & refs)', ->
expected = "http://test.com/codelist?detail=allstubs&references=datastructure"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allstubs'
references: 'datastructure'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports referencepartial since v1.3.0', ->
expected = "http://test.com/codelist?detail=referencepartial"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencepartial'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports allcompletestubs since v1.3.0', ->
expected = "http://test.com/codelist?detail=allcompletestubs"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allcompletestubs'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports referencecompletestubs since v1.3.0', ->
expected = "http://test.com/codelist?detail=referencecompletestubs"
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencecompletestubs'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support referencepartial before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencepartial'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'referencepartial not allowed in v1.1.0')
it 'does not support allcompletestubs before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'allcompletestubs'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'allcompletestubs not allowed in v1.2.0')
it 'does not support referencecompletestubs before v1.3.0', ->
query = MetadataQuery.from({
resource: 'codelist'
detail: 'referencecompletestubs'
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'referencecompletestubs not allowed in v1.0.2')
it 'supports actualconstraint since v1.3.0', ->
expected = 'http://test.com/actualconstraint'
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports allowedconstraint since v1.3.0', ->
expected = 'http://test.com/allowedconstraint'
query = MetadataQuery.from({resource: 'allowedconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support actualconstraint before v1.3.0', ->
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'actualconstraint not allowed in v1.2.0')
it 'does not support allowedconstraint before v1.3.0', ->
query = MetadataQuery.from({resource: 'allowedconstraint'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'allowedconstraint not allowed in v1.0.2')
it 'supports actualconstraint since v1.3.0', ->
expected = 'http://test.com/actualconstraint'
query = MetadataQuery.from({resource: 'actualconstraint'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports VTL artefacts since v1.5.0 (type)', ->
expected = 'http://test.com/transformationscheme'
query = MetadataQuery.from({resource: 'transformationscheme'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support VTL artefacts before v1.5.0 (type)', ->
query = MetadataQuery.from({resource: 'transformationscheme'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'transformationscheme not allowed in v1.2.0')
it 'supports VTL artefacts since v1.5.0 (references)', ->
expected = 'http://test.com/codelist?references=transformationscheme'
query = MetadataQuery.from({resource: 'codelist', references: 'transformationscheme'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support VTL artefacts before v1.5.0 (references)', ->
query = MetadataQuery.from({resource: 'codelist', references: 'transformationscheme'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'transformationscheme not allowed as reference in v1.2.0')
describe 'for data queries', ->
it 'generates a URL for a full data query', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata&includeHistory=true\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: 'PI:KEY:<KEY>END_PI'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({
url: 'http://test.com'
api: ApiVersion.v1_1_0
})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a partial data query', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/all?\
detail=full&includeHistory=false"
query = DataQuery.from({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_1_0})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports history but only for API version 1.1.0 and above', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: 'PI:KEY:<KEY>END_PI'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_0_2})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'defaults to latest API', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/ECB?\
dimensionAtObservation=CURRENCY&detail=nodata&includeHistory=true\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z\
&firstNObservations=1&lastNObservations=1"
query = DataQuery.from({
flow: 'EXR'
key: 'PI:KEY:<KEY>END_PI'
provider: 'ECB'
obsDimension: 'CURRENCY'
detail: 'nodata'
history: true
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
firstNObs: 1
lastNObs: 1
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for data', ->
expected = "http://test.com/data/EXR"
query = DataQuery.from({flow: 'EXR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (provider)', ->
expected = "http://test.com/data/EXR/all/ECB"
query = DataQuery.from({flow: 'EXR', provider: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (start)', ->
expected = "http://test.com/data/EXR?startPeriod=2010"
query = DataQuery.from({flow: 'EXR', start: '2010'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (end)', ->
expected = "http://test.com/data/EXR?endPeriod=2010"
query = DataQuery.from({flow: 'EXR', end: '2010'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (updatedAfter)', ->
expected = "http://test.com/data/EXR?updatedAfter=2016-03-01T00:00:00Z"
query = DataQuery.from({
flow: 'EXR'
updatedAfter: '2016-03-01T00:00:00Z'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (firstNObs)', ->
expected = "http://test.com/data/EXR?firstNObservations=1"
query = DataQuery.from({flow: 'EXR', firstNObs: 1})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (lastNObs)', ->
expected = "http://test.com/data/EXR?lastNObservations=2"
query = DataQuery.from({flow: 'EXR', lastNObs: 2})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (detail)', ->
expected = "http://test.com/data/EXR?detail=dataonly"
query = DataQuery.from({flow: 'EXR', detail: 'dataonly'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (history)', ->
expected = "http://test.com/data/EXR?includeHistory=true"
query = DataQuery.from({flow: 'EXR', history: true})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (obsDim)', ->
expected = "http://test.com/data/EXR?dimensionAtObservation=CURR"
query = DataQuery.from({flow: 'EXR', obsDimension: 'CURR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds params when needed (various)', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A?\
updatedAfter=2016-03-01T00:00:00Z\
&startPeriod=2010&dimensionAtObservation=CURRENCY"
query = DataQuery.from({
flow: 'EXR'
key: 'PI:KEY:<KEY>END_PI'
obsDimension: 'CURRENCY'
start: '2010'
updatedAfter: '2016-03-01T00:00:00Z'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'supports multiple providers for API version 1.3.0 and above', ->
expected = "http://test.com/data/EXR/A..EUR.SP00.A/SDMX,ECB+BIS?\
updatedAfter=2016-03-01T00:00:00Z\
&startPeriod=2010&dimensionAtObservation=CURRENCY"
query = DataQuery.from({
flow: 'EXR'
key: 'PI:KEY:<KEY>END_PIA'
obsDimension: 'CURRENCY'
start: '2010'
updatedAfter: '2016-03-01T00:00:00Z'
provider: ['SDMX,ECB', 'BIS']
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'does not support providers before API version 1.3.0', ->
query = DataQuery.from({flow: 'EXR', provider: 'SDMX,ECB+BIS'})
service = Service.from({url: 'http://test.com', api: ApiVersion.v1_2_0})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Multiple providers not allowed in v1.2.0')
it 'throws an exception if no query is supplied', ->
test = -> new UrlGenerator().getUrl()
should.Throw(test, Error,
'not a valid SDMX data, metadata or availability query')
it 'throws an exception if the input is not a data or a metadata query', ->
test = -> new UrlGenerator().getUrl({test: 'Test'})
should.Throw(test, TypeError,
'not a valid SDMX data, metadata or availability query')
it 'throws an exception if no service is supplied', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
test = -> new UrlGenerator().getUrl query
should.Throw(test, Error, 'not a valid service')
it 'throws an exception if a service without a URL is supplied', ->
query = MetadataQuery.from({
resource: 'codelist'
id: 'CL_FREQ'
agency: 'ECB'
item: 'A'
})
test = -> new UrlGenerator().getUrl query, {id: 'test'}
should.Throw(test, ReferenceError, 'not a valid service')
describe 'for availability queries', ->
it 'generates a URL for a full availability query', ->
expected = 'http://test.com/availableconstraint/EXR/A..EUR.SP00.A/ECB/FREQ?\
mode=available&references=none\
&startPeriod=2010&endPeriod=2015&updatedAfter=2016-03-01T00:00:00Z'
query = AvailabilityQuery.from({
flow: 'EXR'
key: 'PI:KEY:<KEY>END_PI'
provider: 'ECB'
component: 'FREQ'
start: '2010'
end: '2015'
updatedAfter: '2016-03-01T00:00:00Z'
mode: 'available'
references: 'none'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a partial availability query', ->
expected = 'http://test.com/availableconstraint/EXR/A..EUR.SP00.A/all/all?\
mode=exact&references=none'
query = AvailabilityQuery.from({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'supports minimal query if proper query class is used', ->
expected = 'http://test.com/availableconstraint/EXR/all/all/all?\
mode=exact&references=none'
query = AvailabilityQuery.from({flow: 'EXR'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'does not support availability queries before v1.3.0', ->
query = AvailabilityQuery.from({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI'})
service = Service.from({url: 'http://test.com', api: 'v1.2.0'})
test = -> new UrlGenerator().getUrl(query, service)
should.Throw(test, Error, 'Availability query not supported in v1.2.0')
it 'offers to skip default values for availability', ->
expected = 'http://test.com/availableconstraint/EXR'
query = AvailabilityQuery.from({
flow: 'EXR'
mode: 'exact'
references: 'none'
})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (provider)', ->
expected = 'http://test.com/availableconstraint/EXR/all/ECB'
query = AvailabilityQuery.from({flow: 'EXR', provider: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (component)', ->
expected = 'http://test.com/availableconstraint/EXR/all/all/FREQ'
query = AvailabilityQuery.from({flow: 'EXR', component: 'FREQ'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (mode)', ->
expected = 'http://test.com/availableconstraint/EXR?mode=available'
query = AvailabilityQuery.from({flow: 'EXR', mode: 'available'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (references)', ->
expected = 'http://test.com/availableconstraint/EXR?references=codelist'
query = AvailabilityQuery.from({flow: 'EXR', references: 'codelist'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (start)', ->
expected = 'http://test.com/availableconstraint/EXR?startPeriod=2007'
query = AvailabilityQuery.from({flow: 'EXR', start: '2007'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (end)', ->
expected = 'http://test.com/availableconstraint/EXR?endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (start & ed)', ->
expected = 'http://test.com/availableconstraint/EXR?startPeriod=2007&\
endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', start: '2007', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (end)', ->
expected = 'http://test.com/availableconstraint/EXR?endPeriod=2073'
query = AvailabilityQuery.from({flow: 'EXR', end: '2073'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (updatedAfter)', ->
expected = 'http://test.com/availableconstraint/EXR?\
updatedAfter=2016-03-01T00:00:00Z'
query = AvailabilityQuery.from({
flow: 'EXR'
updatedAfter: '2016-03-01T00:00:00Z'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
describe 'for schema queries', ->
it 'generates a URL for a schema query', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/schema/dataflow\
/ECB/EXR/latest?explicitMeasure=false"
query = SchemaQuery.from({context: 'dataflow', id: 'EXR', agency: 'ECB'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'generates a URL for a schema query (with dimensionAtObservation)', ->
expected = "http://sdw-wsrest.ecb.europa.eu/service/schema/dataflow\
/ECB/EXR/latest?explicitMeasure=false&dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', obsDimension: 'TEST'})
service = Service.ECB
url = new UrlGenerator().getUrl(query, service)
url.should.equal expected
it 'offers to skip default values for schema', ->
expected = "http://test.com/schema/dataflow/ECB/EXR"
query = SchemaQuery.from({context: 'dataflow', id: 'EXR', agency: 'ECB'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (version)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR/1.1"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', version: '1.1'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (explicit)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR?explicitMeasure=true"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', explicit: true})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (obsDimension)', ->
expected =
"http://test.com/schema/dataflow/ECB/EXR?dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', obsDimension: 'TEST'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
it 'offers to skip defaults but adds them when needed (query params)', ->
expected = "http://test.com/schema/dataflow/ECB/EXR?explicitMeasure=true\
&dimensionAtObservation=TEST"
query = SchemaQuery.from(
{context: 'dataflow', id: 'EXR', agency: 'ECB', explicit: true,
obsDimension: 'TEST'})
service = Service.from({url: 'http://test.com'})
url = new UrlGenerator().getUrl(query, service, true)
url.should.equal expected
|
[
{
"context": " $http.post '/api/session/login',\n username: username,\n password: password\n .success (data, sta",
"end": 324,
"score": 0.9903574585914612,
"start": 316,
"tag": "USERNAME",
"value": "username"
},
{
"context": "/login',\n username: username,\n p... | frontend/scripts/vsvs.coffee | rao1219/Vedio | 0 | app = angular.module 'vsvs', [
'ngFileUpload'
'ngResource'
'ngProgressLite'
'ui.router'
'gettext'
'ui.bootstrap'
'toastr'
]
app.controller 'LoginController', ['$http', 'gettextCatalog', ($http, gettextCatalog) ->
@login = (username, password) ->
$http.post '/api/session/login',
username: username,
password: password
.success (data, status, headers, config) ->
alert data
.error (data, status, headers, config) ->
alert data
@register = (username, password) ->
alert gettextCatalog.getString(
'register as {{username}}:{{password}}',
username: username
password: password
)
return
]
app.controller 'LanguageController', ['gettextCatalog', (gettextCatalog) ->
@setLanguage = (lang) ->
gettextCatalog.setCurrentLanguage(lang)
gettextCatalog.loadRemote '/languages/messages-' + lang + '.json'
return
]
app.controller 'UploadController', ['$scope', 'toastr', 'gettextCatalog', ($scope, toastr, gettextCatalog) ->
$scope.fileList = []
$scope.progress = 45
@addFile = (files) ->
for file in files
file.status = 'pending'
$scope.fileList.push(file) if file not in $scope.fileList
console.log $scope.fileList
@validate = (file) ->
if file.name.split('.').pop() in ['webm', 'mp4', 'flv', 'mov']
toastr.info gettextCatalog.getString('Success: {{filename}} is uploading.',
filename: file.name
)
return true
else
toastr.warning gettextCatalog.getString('Failed: {{filename}} is not valid video.',
filename: file.name
)
return false
return
]
app.controller 'LoginController', [
'$http'
'gettextCatalog'
($http, gettextCatalog) ->
@login = (username, password) ->
$http.post '/login',
username: username,
password: password
.success (data, status, headers, config) ->
alert data
.error (data, status, headers, config) ->
alert data
@register = (username, password) ->
alert gettextCatalog.getString(
'register as {{username}}:{{password}}',
username: username
password: password
)
return
]
.controller 'LanguageController', [
'gettextCatalog'
(gettextCatalog) ->
@setLanguage = (lang) ->
gettextCatalog.setCurrentLanguage(lang)
gettextCatalog.loadRemote '/languages/messages-' + lang + '.json'
return
]
app.config [
'ngProgressLiteProvider'
(ngProgressLiteProvider) ->
ngProgressLiteProvider.settings.speed = 500
]
| 211487 | app = angular.module 'vsvs', [
'ngFileUpload'
'ngResource'
'ngProgressLite'
'ui.router'
'gettext'
'ui.bootstrap'
'toastr'
]
app.controller 'LoginController', ['$http', 'gettextCatalog', ($http, gettextCatalog) ->
@login = (username, password) ->
$http.post '/api/session/login',
username: username,
password: <PASSWORD>
.success (data, status, headers, config) ->
alert data
.error (data, status, headers, config) ->
alert data
@register = (username, password) ->
alert gettextCatalog.getString(
'register as {{username}}:{{password}}',
username: username
password: <PASSWORD>
)
return
]
app.controller 'LanguageController', ['gettextCatalog', (gettextCatalog) ->
@setLanguage = (lang) ->
gettextCatalog.setCurrentLanguage(lang)
gettextCatalog.loadRemote '/languages/messages-' + lang + '.json'
return
]
app.controller 'UploadController', ['$scope', 'toastr', 'gettextCatalog', ($scope, toastr, gettextCatalog) ->
$scope.fileList = []
$scope.progress = 45
@addFile = (files) ->
for file in files
file.status = 'pending'
$scope.fileList.push(file) if file not in $scope.fileList
console.log $scope.fileList
@validate = (file) ->
if file.name.split('.').pop() in ['webm', 'mp4', 'flv', 'mov']
toastr.info gettextCatalog.getString('Success: {{filename}} is uploading.',
filename: file.name
)
return true
else
toastr.warning gettextCatalog.getString('Failed: {{filename}} is not valid video.',
filename: file.name
)
return false
return
]
app.controller 'LoginController', [
'$http'
'gettextCatalog'
($http, gettextCatalog) ->
@login = (username, password) ->
$http.post '/login',
username: username,
password: <PASSWORD>
.success (data, status, headers, config) ->
alert data
.error (data, status, headers, config) ->
alert data
@register = (username, password) ->
alert gettextCatalog.getString(
'register as {{username}}:{{password}}',
username: username
password: <PASSWORD>
)
return
]
.controller 'LanguageController', [
'gettextCatalog'
(gettextCatalog) ->
@setLanguage = (lang) ->
gettextCatalog.setCurrentLanguage(lang)
gettextCatalog.loadRemote '/languages/messages-' + lang + '.json'
return
]
app.config [
'ngProgressLiteProvider'
(ngProgressLiteProvider) ->
ngProgressLiteProvider.settings.speed = 500
]
| true | app = angular.module 'vsvs', [
'ngFileUpload'
'ngResource'
'ngProgressLite'
'ui.router'
'gettext'
'ui.bootstrap'
'toastr'
]
app.controller 'LoginController', ['$http', 'gettextCatalog', ($http, gettextCatalog) ->
@login = (username, password) ->
$http.post '/api/session/login',
username: username,
password: PI:PASSWORD:<PASSWORD>END_PI
.success (data, status, headers, config) ->
alert data
.error (data, status, headers, config) ->
alert data
@register = (username, password) ->
alert gettextCatalog.getString(
'register as {{username}}:{{password}}',
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
)
return
]
app.controller 'LanguageController', ['gettextCatalog', (gettextCatalog) ->
@setLanguage = (lang) ->
gettextCatalog.setCurrentLanguage(lang)
gettextCatalog.loadRemote '/languages/messages-' + lang + '.json'
return
]
app.controller 'UploadController', ['$scope', 'toastr', 'gettextCatalog', ($scope, toastr, gettextCatalog) ->
$scope.fileList = []
$scope.progress = 45
@addFile = (files) ->
for file in files
file.status = 'pending'
$scope.fileList.push(file) if file not in $scope.fileList
console.log $scope.fileList
@validate = (file) ->
if file.name.split('.').pop() in ['webm', 'mp4', 'flv', 'mov']
toastr.info gettextCatalog.getString('Success: {{filename}} is uploading.',
filename: file.name
)
return true
else
toastr.warning gettextCatalog.getString('Failed: {{filename}} is not valid video.',
filename: file.name
)
return false
return
]
app.controller 'LoginController', [
'$http'
'gettextCatalog'
($http, gettextCatalog) ->
@login = (username, password) ->
$http.post '/login',
username: username,
password: PI:PASSWORD:<PASSWORD>END_PI
.success (data, status, headers, config) ->
alert data
.error (data, status, headers, config) ->
alert data
@register = (username, password) ->
alert gettextCatalog.getString(
'register as {{username}}:{{password}}',
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
)
return
]
.controller 'LanguageController', [
'gettextCatalog'
(gettextCatalog) ->
@setLanguage = (lang) ->
gettextCatalog.setCurrentLanguage(lang)
gettextCatalog.loadRemote '/languages/messages-' + lang + '.json'
return
]
app.config [
'ngProgressLiteProvider'
(ngProgressLiteProvider) ->
ngProgressLiteProvider.settings.speed = 500
]
|
[
{
"context": "USER_1 = firstName : 'Marian', lastName : 'Lumba', organization : 'Ne",
"end": 29,
"score": 0.9998060464859009,
"start": 23,
"tag": "NAME",
"value": "Marian"
},
{
"context": "USER_1 = firstName : 'Marian', lastName : 'Lumba', organization : 'Netflix'... | client/person/service.coffee | armw4/smart-table-clean-architecture | 0 | USER_1 = firstName : 'Marian', lastName : 'Lumba', organization : 'Netflix', socialSecurityNumber : '2222222222'
USER_2 = firstName : 'Sansom', lastName : 'Shawn', organization : 'Google', socialSecurityNumber : '2022222222'
USER_3 = firstName : 'Luis', lastName : 'Mayorga', organization : "McDonald's", socialSecurityNumber : '5122221222'
USER_4 = firstName : 'Cashias', lastName : 'Otoya', organization : 'Twitter', socialSecurityNumber : '6232220222'
USER_5 = firstName : 'Joey', lastName : 'Poindexter', organization : 'Github', socialSecurityNumber : '7242222222'
USER_6 = firstName : 'Sylvester', lastName : 'Livermore', organization : 'Github', socialSecurityNumber : '9282222222'
USER_7 = firstName : 'Julius', lastName : 'Wiliams', organization : 'Github', socialSecurityNumber : '2202222222'
USER_8 = firstName : 'Lanister', lastName : 'Mobaser', organization : 'Netflix', socialSecurityNumber : '4226222222'
USER_9 = firstName : 'Shay Shawy', lastName : 'Stokinov', organization : 'Google', socialSecurityNumber : '1228222222'
USER_10 = firstName : 'Brielle', lastName : 'Hallester', organization : 'Twitter', socialSecurityNumber : '1922222222'
PEOPLE = [
USER_1,
USER_2,
USER_3,
USER_4,
USER_5,
USER_6,
USER_7,
USER_8,
USER_9,
USER_10
]
angular
.module 'person', []
.service 'person', ($q) ->
find = (query, options) ->
# simulate IQueryable<T> in .NET. by default you're working
# against a query that represents ALL objects (select * from <table>).
searchResults = _(PEOPLE)
socialSecurityFilter = new RegExp query.socialSecurityNumber
deferred = $q.defer()
result = ->
if query.socialSecurityNumber
# partial match (starts with/contains)
searchResults =
searchResults
.filter (person) -> socialSecurityFilter.test(person.socialSecurityNumber)
if query.organization
# exact match
searchResults = searchResults.where organization: query.organization
deferred.resolve searchResults.value()
simulateDelay = options and options.async
delay = if simulateDelay then 1500 else 0
setTimeout result, delay
deferred.promise
findRemote: (query) -> find query, async: true
findLocal: (query) -> find query
page: (people, number, count) ->
skipCount = count * (number - 1)
_(people).slice(skipCount).take(count).value()
| 171613 | USER_1 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Netflix', socialSecurityNumber : '2222222222'
USER_2 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Google', socialSecurityNumber : '2022222222'
USER_3 = firstName : '<NAME>', lastName : '<NAME>', organization : "McDonald's", socialSecurityNumber : '5122221222'
USER_4 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Twitter', socialSecurityNumber : '6232220222'
USER_5 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Github', socialSecurityNumber : '7242222222'
USER_6 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Github', socialSecurityNumber : '9282222222'
USER_7 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Github', socialSecurityNumber : '2202222222'
USER_8 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Netflix', socialSecurityNumber : '4226222222'
USER_9 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Google', socialSecurityNumber : '1228222222'
USER_10 = firstName : '<NAME>', lastName : '<NAME>', organization : 'Twitter', socialSecurityNumber : '1922222222'
PEOPLE = [
USER_1,
USER_2,
USER_3,
USER_4,
USER_5,
USER_6,
USER_7,
USER_8,
USER_9,
USER_10
]
angular
.module 'person', []
.service 'person', ($q) ->
find = (query, options) ->
# simulate IQueryable<T> in .NET. by default you're working
# against a query that represents ALL objects (select * from <table>).
searchResults = _(PEOPLE)
socialSecurityFilter = new RegExp query.socialSecurityNumber
deferred = $q.defer()
result = ->
if query.socialSecurityNumber
# partial match (starts with/contains)
searchResults =
searchResults
.filter (person) -> socialSecurityFilter.test(person.socialSecurityNumber)
if query.organization
# exact match
searchResults = searchResults.where organization: query.organization
deferred.resolve searchResults.value()
simulateDelay = options and options.async
delay = if simulateDelay then 1500 else 0
setTimeout result, delay
deferred.promise
findRemote: (query) -> find query, async: true
findLocal: (query) -> find query
page: (people, number, count) ->
skipCount = count * (number - 1)
_(people).slice(skipCount).take(count).value()
| true | USER_1 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Netflix', socialSecurityNumber : '2222222222'
USER_2 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Google', socialSecurityNumber : '2022222222'
USER_3 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : "McDonald's", socialSecurityNumber : '5122221222'
USER_4 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Twitter', socialSecurityNumber : '6232220222'
USER_5 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Github', socialSecurityNumber : '7242222222'
USER_6 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Github', socialSecurityNumber : '9282222222'
USER_7 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Github', socialSecurityNumber : '2202222222'
USER_8 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Netflix', socialSecurityNumber : '4226222222'
USER_9 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Google', socialSecurityNumber : '1228222222'
USER_10 = firstName : 'PI:NAME:<NAME>END_PI', lastName : 'PI:NAME:<NAME>END_PI', organization : 'Twitter', socialSecurityNumber : '1922222222'
PEOPLE = [
USER_1,
USER_2,
USER_3,
USER_4,
USER_5,
USER_6,
USER_7,
USER_8,
USER_9,
USER_10
]
angular
.module 'person', []
.service 'person', ($q) ->
find = (query, options) ->
# simulate IQueryable<T> in .NET. by default you're working
# against a query that represents ALL objects (select * from <table>).
searchResults = _(PEOPLE)
socialSecurityFilter = new RegExp query.socialSecurityNumber
deferred = $q.defer()
result = ->
if query.socialSecurityNumber
# partial match (starts with/contains)
searchResults =
searchResults
.filter (person) -> socialSecurityFilter.test(person.socialSecurityNumber)
if query.organization
# exact match
searchResults = searchResults.where organization: query.organization
deferred.resolve searchResults.value()
simulateDelay = options and options.async
delay = if simulateDelay then 1500 else 0
setTimeout result, delay
deferred.promise
findRemote: (query) -> find query, async: true
findLocal: (query) -> find query
page: (people, number, count) ->
skipCount = count * (number - 1)
_(people).slice(skipCount).take(count).value()
|
[
{
"context": "oadData-persons', JSON.stringify(persons, ['id', 'firstName', 'lastName']))\n , 100)\n\n\n getTasks = ->\n",
"end": 1221,
"score": 0.993371844291687,
"start": 1212,
"tag": "NAME",
"value": "firstName"
},
{
"context": "ns', JSON.stringify(persons, ['id', 'firstNa... | src/app/components/data/data.service.coffee | bbasic/workload-planner | 0 | angular.module 'workloadPlanner'
.service 'workloadData', (localStorage, $log, $timeout) ->
'ngInject'
_persons = undefined
_tasks = undefined
_priorityMatrix = undefined
_nextId = {}
diff = (a, b) ->
if a.length > b.length
a.filter((i) -> b.indexOf(i) < 0)
else
b.filter((i) -> a.indexOf(i) < 0)
getPersons = ->
if _persons? then return _persons
_persons = JSON.parse(localStorage.getItem('workloadData-persons') || '[]')
return _persons
setPersons = (persons, person = undefined) ->
_persons = persons
if person?
matrix = getPriorityMatrix()
if person._deleted
$log.log 'person deleted', person
delete matrix[person.id]
else if person._added
$log.log 'person added', person
matrix[person.id] = {}
for t in getTasks()
sum = 0
for p in persons
sum += matrix[p.id][t.id]
matrix[person.id][t.id] = if sum == 0 then sum else Math.floor(sum / persons.length)
setPriorityMatrix(matrix)
$timeout(
-> localStorage.setItem('workloadData-persons', JSON.stringify(persons, ['id', 'firstName', 'lastName']))
, 100)
getTasks = ->
if _tasks? then return _tasks
_tasks = JSON.parse(localStorage.getItem('workloadData-tasks') || '[]')
return _tasks
setTasks = (tasks, task = undefined) ->
_tasks = tasks
if task?
ps = getPersons()
matrix = getPriorityMatrix()
if task._deleted
$log.log 'task deleted', task
for p in ps
per = matrix[p.id]
delete per[task.id]
else if task._added
$log.log 'task added', task
for p in ps
matrix[p.id][task.id] = 0
setPriorityMatrix(matrix)
$timeout(
-> localStorage.setItem('workloadData-tasks', JSON.stringify(tasks, ['id', 'taskName', 'activeDays']))
, 100)
_generatePriorityMatrix = ->
matrix = {}
ps = getPersons()
ts = getTasks()
for p in ps
matrix[p.id] = {}
for t in ts
matrix[p.id][t.id] = 0
return matrix
getPriorityMatrix = ->
if _priorityMatrix? then return _priorityMatrix
_priorityMatrix = JSON.parse(localStorage.getItem('workloadData-priorityMatrix') || '[]')
if angular.isArray(_priorityMatrix) then _priorityMatrix = _generatePriorityMatrix()
return _priorityMatrix
setPriorityMatrix = (priorityMatrix) ->
_priorityMatrix = priorityMatrix
$timeout(
-> localStorage.setItem('workloadData-priorityMatrix', JSON.stringify(priorityMatrix))
, 100)
getNextId = (who) ->
newId = 0
key = 'workloadData-'+who+'-id'
if _nextId[who]?
newId = _nextId[who] + 1
else
newId = parseInt(localStorage.getItem(key) || '0') + 1
_nextId[who] = newId
$timeout(
->localStorage.setItem(key, newId)
, 100)
newId
service =
getPersons: getPersons
setPersons: setPersons
getTasks: getTasks
setTasks: setTasks
nextId: getNextId
getPriorityMatrix: getPriorityMatrix
setPriorityMatrix: setPriorityMatrix
| 175339 | angular.module 'workloadPlanner'
.service 'workloadData', (localStorage, $log, $timeout) ->
'ngInject'
_persons = undefined
_tasks = undefined
_priorityMatrix = undefined
_nextId = {}
diff = (a, b) ->
if a.length > b.length
a.filter((i) -> b.indexOf(i) < 0)
else
b.filter((i) -> a.indexOf(i) < 0)
getPersons = ->
if _persons? then return _persons
_persons = JSON.parse(localStorage.getItem('workloadData-persons') || '[]')
return _persons
setPersons = (persons, person = undefined) ->
_persons = persons
if person?
matrix = getPriorityMatrix()
if person._deleted
$log.log 'person deleted', person
delete matrix[person.id]
else if person._added
$log.log 'person added', person
matrix[person.id] = {}
for t in getTasks()
sum = 0
for p in persons
sum += matrix[p.id][t.id]
matrix[person.id][t.id] = if sum == 0 then sum else Math.floor(sum / persons.length)
setPriorityMatrix(matrix)
$timeout(
-> localStorage.setItem('workloadData-persons', JSON.stringify(persons, ['id', '<NAME>', '<NAME>']))
, 100)
getTasks = ->
if _tasks? then return _tasks
_tasks = JSON.parse(localStorage.getItem('workloadData-tasks') || '[]')
return _tasks
setTasks = (tasks, task = undefined) ->
_tasks = tasks
if task?
ps = getPersons()
matrix = getPriorityMatrix()
if task._deleted
$log.log 'task deleted', task
for p in ps
per = matrix[p.id]
delete per[task.id]
else if task._added
$log.log 'task added', task
for p in ps
matrix[p.id][task.id] = 0
setPriorityMatrix(matrix)
$timeout(
-> localStorage.setItem('workloadData-tasks', JSON.stringify(tasks, ['id', 'taskName', 'activeDays']))
, 100)
_generatePriorityMatrix = ->
matrix = {}
ps = getPersons()
ts = getTasks()
for p in ps
matrix[p.id] = {}
for t in ts
matrix[p.id][t.id] = 0
return matrix
getPriorityMatrix = ->
if _priorityMatrix? then return _priorityMatrix
_priorityMatrix = JSON.parse(localStorage.getItem('workloadData-priorityMatrix') || '[]')
if angular.isArray(_priorityMatrix) then _priorityMatrix = _generatePriorityMatrix()
return _priorityMatrix
setPriorityMatrix = (priorityMatrix) ->
_priorityMatrix = priorityMatrix
$timeout(
-> localStorage.setItem('workloadData-priorityMatrix', JSON.stringify(priorityMatrix))
, 100)
getNextId = (who) ->
newId = 0
key = '<KEY>'
if _nextId[who]?
newId = _nextId[who] + 1
else
newId = parseInt(localStorage.getItem(key) || '0') + 1
_nextId[who] = newId
$timeout(
->localStorage.setItem(key, newId)
, 100)
newId
service =
getPersons: getPersons
setPersons: setPersons
getTasks: getTasks
setTasks: setTasks
nextId: getNextId
getPriorityMatrix: getPriorityMatrix
setPriorityMatrix: setPriorityMatrix
| true | angular.module 'workloadPlanner'
.service 'workloadData', (localStorage, $log, $timeout) ->
'ngInject'
_persons = undefined
_tasks = undefined
_priorityMatrix = undefined
_nextId = {}
diff = (a, b) ->
if a.length > b.length
a.filter((i) -> b.indexOf(i) < 0)
else
b.filter((i) -> a.indexOf(i) < 0)
getPersons = ->
if _persons? then return _persons
_persons = JSON.parse(localStorage.getItem('workloadData-persons') || '[]')
return _persons
setPersons = (persons, person = undefined) ->
_persons = persons
if person?
matrix = getPriorityMatrix()
if person._deleted
$log.log 'person deleted', person
delete matrix[person.id]
else if person._added
$log.log 'person added', person
matrix[person.id] = {}
for t in getTasks()
sum = 0
for p in persons
sum += matrix[p.id][t.id]
matrix[person.id][t.id] = if sum == 0 then sum else Math.floor(sum / persons.length)
setPriorityMatrix(matrix)
$timeout(
-> localStorage.setItem('workloadData-persons', JSON.stringify(persons, ['id', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']))
, 100)
getTasks = ->
if _tasks? then return _tasks
_tasks = JSON.parse(localStorage.getItem('workloadData-tasks') || '[]')
return _tasks
setTasks = (tasks, task = undefined) ->
_tasks = tasks
if task?
ps = getPersons()
matrix = getPriorityMatrix()
if task._deleted
$log.log 'task deleted', task
for p in ps
per = matrix[p.id]
delete per[task.id]
else if task._added
$log.log 'task added', task
for p in ps
matrix[p.id][task.id] = 0
setPriorityMatrix(matrix)
$timeout(
-> localStorage.setItem('workloadData-tasks', JSON.stringify(tasks, ['id', 'taskName', 'activeDays']))
, 100)
_generatePriorityMatrix = ->
matrix = {}
ps = getPersons()
ts = getTasks()
for p in ps
matrix[p.id] = {}
for t in ts
matrix[p.id][t.id] = 0
return matrix
getPriorityMatrix = ->
if _priorityMatrix? then return _priorityMatrix
_priorityMatrix = JSON.parse(localStorage.getItem('workloadData-priorityMatrix') || '[]')
if angular.isArray(_priorityMatrix) then _priorityMatrix = _generatePriorityMatrix()
return _priorityMatrix
setPriorityMatrix = (priorityMatrix) ->
_priorityMatrix = priorityMatrix
$timeout(
-> localStorage.setItem('workloadData-priorityMatrix', JSON.stringify(priorityMatrix))
, 100)
getNextId = (who) ->
newId = 0
key = 'PI:KEY:<KEY>END_PI'
if _nextId[who]?
newId = _nextId[who] + 1
else
newId = parseInt(localStorage.getItem(key) || '0') + 1
_nextId[who] = newId
$timeout(
->localStorage.setItem(key, newId)
, 100)
newId
service =
getPersons: getPersons
setPersons: setPersons
getTasks: getTasks
setTasks: setTasks
nextId: getNextId
getPriorityMatrix: getPriorityMatrix
setPriorityMatrix: setPriorityMatrix
|
[
{
"context": " <div id=\"turbo-area\" refresh=\"turbo-area\">Hi bob</div>\n </body>\n </html>\n \"\"\"\n ],\n",
"end": 733,
"score": 0.5223674774169922,
"start": 730,
"tag": "NAME",
"value": "bob"
}
] | test/javascripts/fixtures/js/routes.coffee | fakeNetflix/Shopify-repo-turbograft | 221 | window.ROUTES = {
serverError: [
500,
{'Content-Type':'text/html'},
'error!'
],
validationError: [
422,
{'Content-Type':'text/html'},
'error!'
],
noContentType: [
500,
{},
'error!'
],
xhrRedirectedToHeader: [
200,
{
'X-XHR-Redirected-To': 'test-location'
},
''
],
otherXhrRedirectedToHeader: [
200,
{
'X-XHR-Redirected-To': 'other-location'
},
''
],
noScriptsOrLinkInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi there!</title>
</head>
<body>
<div>YOLO</div>
<div id="turbo-area" refresh="turbo-area">Hi bob</div>
</body>
</html>
"""
],
singleScriptInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleScriptInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="bar"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHeadTrackTrueOneChanged: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area">Merp</div>
</body>
</html>
"""
],
twoScriptsInHeadOneBroken: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script
src=""
id="broken-script"
data-turbolinks-track="broken"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area">
Text content even though a script broke
</div>
</body>
</html>
"""
],
differentSingleScriptInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="bar"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleScriptInHeadWithDifferentSourceButSameName: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
secondLibraryOnly: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadABC: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadACB: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadBAC: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadBCA: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadCAB: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadCBA: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleLinkInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="bar"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="true"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="true"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadTrackTrueOneChanged: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['a.css']}' data-turbolinks-track="true"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="true"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadReverseOrder: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="bar"></link>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
inlineScriptInBody: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<script id="turbo-area" refresh="turbo-area">window.parent.globalStub()</script>
</body>
</html>
"""
],
inlineScriptInBodyTurbolinksEvalFalse: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<script data-turbolinks-eval="false" id="turbo-area" refresh="turbo-area">window.parent.globalStub()</script>
</body>
</html>
"""
],
responseWithRefreshAlways: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<div id="div1" refresh="div1">
<div id="div2" refresh-always>Refresh-always</div>
</div>
</body>
</html>
"""
]
}
| 203351 | window.ROUTES = {
serverError: [
500,
{'Content-Type':'text/html'},
'error!'
],
validationError: [
422,
{'Content-Type':'text/html'},
'error!'
],
noContentType: [
500,
{},
'error!'
],
xhrRedirectedToHeader: [
200,
{
'X-XHR-Redirected-To': 'test-location'
},
''
],
otherXhrRedirectedToHeader: [
200,
{
'X-XHR-Redirected-To': 'other-location'
},
''
],
noScriptsOrLinkInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi there!</title>
</head>
<body>
<div>YOLO</div>
<div id="turbo-area" refresh="turbo-area">Hi <NAME></div>
</body>
</html>
"""
],
singleScriptInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleScriptInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="bar"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHeadTrackTrueOneChanged: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area">Merp</div>
</body>
</html>
"""
],
twoScriptsInHeadOneBroken: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script
src=""
id="broken-script"
data-turbolinks-track="broken"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area">
Text content even though a script broke
</div>
</body>
</html>
"""
],
differentSingleScriptInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="bar"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleScriptInHeadWithDifferentSourceButSameName: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
secondLibraryOnly: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadABC: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadACB: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadBAC: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadBCA: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadCAB: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadCBA: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleLinkInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="bar"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="true"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="true"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadTrackTrueOneChanged: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['a.css']}' data-turbolinks-track="true"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="true"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadReverseOrder: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="bar"></link>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
inlineScriptInBody: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<script id="turbo-area" refresh="turbo-area">window.parent.globalStub()</script>
</body>
</html>
"""
],
inlineScriptInBodyTurbolinksEvalFalse: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<script data-turbolinks-eval="false" id="turbo-area" refresh="turbo-area">window.parent.globalStub()</script>
</body>
</html>
"""
],
responseWithRefreshAlways: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<div id="div1" refresh="div1">
<div id="div2" refresh-always>Refresh-always</div>
</div>
</body>
</html>
"""
]
}
| true | window.ROUTES = {
serverError: [
500,
{'Content-Type':'text/html'},
'error!'
],
validationError: [
422,
{'Content-Type':'text/html'},
'error!'
],
noContentType: [
500,
{},
'error!'
],
xhrRedirectedToHeader: [
200,
{
'X-XHR-Redirected-To': 'test-location'
},
''
],
otherXhrRedirectedToHeader: [
200,
{
'X-XHR-Redirected-To': 'other-location'
},
''
],
noScriptsOrLinkInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi there!</title>
</head>
<body>
<div>YOLO</div>
<div id="turbo-area" refresh="turbo-area">Hi PI:NAME:<NAME>END_PI</div>
</body>
</html>
"""
],
singleScriptInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleScriptInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="bar"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoScriptsInHeadTrackTrueOneChanged: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="true"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area">Merp</div>
</body>
</html>
"""
],
twoScriptsInHeadOneBroken: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script
src=""
id="broken-script"
data-turbolinks-track="broken"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['foo.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area">
Text content even though a script broke
</div>
</body>
</html>
"""
],
differentSingleScriptInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="bar"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleScriptInHeadWithDifferentSourceButSameName: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['bar.js']}'
data-turbolinks-track="foo"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
secondLibraryOnly: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadABC: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadACB: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadBAC: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadBCA: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadCAB: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
threeScriptsInHeadCBA: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<script src='#{ASSET_FIXTURES['c.js']}'
data-turbolinks-track="c"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['b.js']}'
data-turbolinks-track="b"
type="text/javascript"></script>
<script src='#{ASSET_FIXTURES['a.js']}'
data-turbolinks-track="a"
type="text/javascript"></script>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
singleLinkInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHead: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="bar"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadTrackTrue: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="true"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="true"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadTrackTrueOneChanged: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['a.css']}' data-turbolinks-track="true"></link>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="true"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
twoLinksInHeadReverseOrder: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<link href='#{ASSET_FIXTURES['bar.css']}' data-turbolinks-track="bar"></link>
<link href='#{ASSET_FIXTURES['foo.css']}' data-turbolinks-track="foo"></link>
<title>Hi there!</title>
</head>
<body>
<div id="turbo-area" refresh="turbo-area"></div>
</body>
</html>
"""
],
inlineScriptInBody: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<script id="turbo-area" refresh="turbo-area">window.parent.globalStub()</script>
</body>
</html>
"""
],
inlineScriptInBodyTurbolinksEvalFalse: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<script data-turbolinks-eval="false" id="turbo-area" refresh="turbo-area">window.parent.globalStub()</script>
</body>
</html>
"""
],
responseWithRefreshAlways: [
200,
{'Content-Type':'text/html'},
"""
<!doctype html>
<html>
<head>
<title>Hi</title>
</head>
<body>
<div id="div1" refresh="div1">
<div id="div2" refresh-always>Refresh-always</div>
</div>
</body>
</html>
"""
]
}
|
[
{
"context": "xamples right next to their source code. Enjoy! --Curran Kelleher, April 2013\n#\n# [Colored Canvas](../examples/01_c",
"end": 495,
"score": 0.9999041557312012,
"start": 480,
"tag": "NAME",
"value": "Curran Kelleher"
}
] | docs/examples.coffee | curran/canvas-vis | 2 | # Canvas-Vis Examples
# ===================
#
# This docrment is a collection of examples that use the Canvas-vis library. This file is built from `examples.coffee` in `build.sh`, which uses [Docco](http://jashkenas.github.io/docco/). Because Docco supports [Markdown](http://daringfireball.net/projects/markdown/) with inline HTML in comments, it is possible to execute `examples.coffee` within this document, producing running examples right next to their source code. Enjoy! --Curran Kelleher, April 2013
#
# [Colored Canvas](../examples/01_coloredCanvas.html)
# --------------
# <canvas id="coloredCanvas"></canvas>
#
# An example of
#
# * Creating a `Component`
# * Defining its `paint` method
# * Using the `graphicsDirty` event to schedule repainting
# * Binding a component to a Canvas
require ['cv/Component', 'cv/bindToCanvas'], (Component, bindToCanvas) ->
ColoredCanvas = Component.extend
initialize: ->
setInterval (=> @trigger 'graphicsDirty'), 1000
paint: (ctx, bounds) ->
ctx.fillStyle = randomColor()
ctx.fillRect bounds.x, bounds.y, bounds.w, bounds.h
randomColor = -> "rgb(#{r()},#{r()},#{r()})"
r = -> Math.floor(Math.random() * 255)
bindToCanvas 'coloredCanvas', new ColoredCanvas
# [Scatter Plot](../examples/02_ScatterPlot.html)
# --------------
# <canvas id="scatterPlot" width="450" height="450"></canvas>
require ['cv/Component', 'cv/bindToCanvas', 'cv/readCSV',
'cv/Viewport', 'cv/Rectangle', 'cv/Varset', 'cv/Scale', 'cv/mark']
, (Component, bindToCanvas, readCSV,
Viewport, Rectangle, Varset, Scale, mark) ->
readCSV '../data/iris.csv', (err, columns) ->
xVar = Varset.fromVariable columns['petal length']
yVar = Varset.fromVariable columns['sepal length']
varset = Varset.cross xVar, yVar
scales = [new Scale(1), new Scale(2)]
scale.init varset for scale in scales
ScatterPlot = Component.extend
paint: (ctx, bounds) ->
viewport.dest.copy bounds
for tuple in varset.tuples()
(point position tuple).render ctx, viewport
position = (tuple) ->
mark()
.x(scales[0].value tuple)
.y(scales[1].value tuple)
point = (mark) ->
mark.size(0.05)
.shape('circle')
.fillStyle('rgba(0,0,0,0.2)')
viewport = new Viewport
bindToCanvas 'scatterPlot', new ScatterPlot
# [Grammar of Graphics](../examples/03_GrammarOfGraphics.html)
# ------------------------------------------------------------
# <canvas id="grammarOfGraphics" width="450" height="450"></canvas>
# <textarea rows="20" cols="40" id="expressionBox">loading...</textarea>
# <div style="color:red" id='errorDiv'></div>
require ['cv/Component', 'cv/bindToCanvas', 'cv/readCSV',
'cv/Viewport', 'cv/Rectangle', 'cv/mark','cv/grammarOfGraphics']
, (Component, bindToCanvas, readCSV,
Viewport, Rectangle, mark, grammarOfGraphics) ->
initialExpr = """
DATA: x = "petal length"
DATA: y = "sepal length"
TRANS: x = x
TRANS: y = y
SCALE: linear(dim(1))
SCALE: linear(dim(2))
COORD: rect(dim(1, 2))
GUIDE: axis(dim(1))
GUIDE: axis(dim(2))
ELEMENT: point(position(x*y))
"""
readCSV '../data/iris.csv', (err, variables) ->
[keys, scales, keyToMark] = grammarOfGraphics.execute variables, initialExpr
viewport = new Viewport
GGComponent = Component.extend
paint: (ctx, bounds) ->
ctx.clearRect 0, 0, bounds.w, bounds.h
viewport.dest.copy bounds
for key in keys
(keyToMark key, scales).render ctx, viewport
component = new GGComponent
bindToCanvas 'grammarOfGraphics', component
changeExpr = (expr)->
[keys, scales, keyToMark] = grammarOfGraphics.execute variables, expr
component.trigger 'graphicsDirty'
expressionBox.value = initialExpr
expressionBox.addEventListener 'input', ->
try
errorDiv.innerHTML = ''
changeExpr expressionBox.value
catch error
errorDiv.innerHTML = error
# Roadmap
# =======
#
# * Bertin example from p.43
# * Nested Components example
# * Timeline of Population Data
# * Pan & Zoom example
# * Zoomable Scatter Plot of Iris Data
# * Zoomable Timeline of Population Data (A)
# * Parallel Coordinates of Iris Data (B)
# * Brushing & Linking Example containing A and B
# * Map of labeled US counties using Quadstream (C)
# * Zoomable Choropleth Map
# * Color Maps
# * HeatMap
# <script src="../lib/underscore.js"></script>
# <script src="../lib/backbone.js"></script>
# <script src="../lib/coffee-script.js"></script>
# <script src="../requireConfig.js"> </script>
# <script src="../lib/require-jquery.js"></script>
# <script type="text/coffeescript" src="examples.coffee"> </script>
| 175561 | # Canvas-Vis Examples
# ===================
#
# This docrment is a collection of examples that use the Canvas-vis library. This file is built from `examples.coffee` in `build.sh`, which uses [Docco](http://jashkenas.github.io/docco/). Because Docco supports [Markdown](http://daringfireball.net/projects/markdown/) with inline HTML in comments, it is possible to execute `examples.coffee` within this document, producing running examples right next to their source code. Enjoy! --<NAME>, April 2013
#
# [Colored Canvas](../examples/01_coloredCanvas.html)
# --------------
# <canvas id="coloredCanvas"></canvas>
#
# An example of
#
# * Creating a `Component`
# * Defining its `paint` method
# * Using the `graphicsDirty` event to schedule repainting
# * Binding a component to a Canvas
require ['cv/Component', 'cv/bindToCanvas'], (Component, bindToCanvas) ->
ColoredCanvas = Component.extend
initialize: ->
setInterval (=> @trigger 'graphicsDirty'), 1000
paint: (ctx, bounds) ->
ctx.fillStyle = randomColor()
ctx.fillRect bounds.x, bounds.y, bounds.w, bounds.h
randomColor = -> "rgb(#{r()},#{r()},#{r()})"
r = -> Math.floor(Math.random() * 255)
bindToCanvas 'coloredCanvas', new ColoredCanvas
# [Scatter Plot](../examples/02_ScatterPlot.html)
# --------------
# <canvas id="scatterPlot" width="450" height="450"></canvas>
require ['cv/Component', 'cv/bindToCanvas', 'cv/readCSV',
'cv/Viewport', 'cv/Rectangle', 'cv/Varset', 'cv/Scale', 'cv/mark']
, (Component, bindToCanvas, readCSV,
Viewport, Rectangle, Varset, Scale, mark) ->
readCSV '../data/iris.csv', (err, columns) ->
xVar = Varset.fromVariable columns['petal length']
yVar = Varset.fromVariable columns['sepal length']
varset = Varset.cross xVar, yVar
scales = [new Scale(1), new Scale(2)]
scale.init varset for scale in scales
ScatterPlot = Component.extend
paint: (ctx, bounds) ->
viewport.dest.copy bounds
for tuple in varset.tuples()
(point position tuple).render ctx, viewport
position = (tuple) ->
mark()
.x(scales[0].value tuple)
.y(scales[1].value tuple)
point = (mark) ->
mark.size(0.05)
.shape('circle')
.fillStyle('rgba(0,0,0,0.2)')
viewport = new Viewport
bindToCanvas 'scatterPlot', new ScatterPlot
# [Grammar of Graphics](../examples/03_GrammarOfGraphics.html)
# ------------------------------------------------------------
# <canvas id="grammarOfGraphics" width="450" height="450"></canvas>
# <textarea rows="20" cols="40" id="expressionBox">loading...</textarea>
# <div style="color:red" id='errorDiv'></div>
require ['cv/Component', 'cv/bindToCanvas', 'cv/readCSV',
'cv/Viewport', 'cv/Rectangle', 'cv/mark','cv/grammarOfGraphics']
, (Component, bindToCanvas, readCSV,
Viewport, Rectangle, mark, grammarOfGraphics) ->
initialExpr = """
DATA: x = "petal length"
DATA: y = "sepal length"
TRANS: x = x
TRANS: y = y
SCALE: linear(dim(1))
SCALE: linear(dim(2))
COORD: rect(dim(1, 2))
GUIDE: axis(dim(1))
GUIDE: axis(dim(2))
ELEMENT: point(position(x*y))
"""
readCSV '../data/iris.csv', (err, variables) ->
[keys, scales, keyToMark] = grammarOfGraphics.execute variables, initialExpr
viewport = new Viewport
GGComponent = Component.extend
paint: (ctx, bounds) ->
ctx.clearRect 0, 0, bounds.w, bounds.h
viewport.dest.copy bounds
for key in keys
(keyToMark key, scales).render ctx, viewport
component = new GGComponent
bindToCanvas 'grammarOfGraphics', component
changeExpr = (expr)->
[keys, scales, keyToMark] = grammarOfGraphics.execute variables, expr
component.trigger 'graphicsDirty'
expressionBox.value = initialExpr
expressionBox.addEventListener 'input', ->
try
errorDiv.innerHTML = ''
changeExpr expressionBox.value
catch error
errorDiv.innerHTML = error
# Roadmap
# =======
#
# * Bertin example from p.43
# * Nested Components example
# * Timeline of Population Data
# * Pan & Zoom example
# * Zoomable Scatter Plot of Iris Data
# * Zoomable Timeline of Population Data (A)
# * Parallel Coordinates of Iris Data (B)
# * Brushing & Linking Example containing A and B
# * Map of labeled US counties using Quadstream (C)
# * Zoomable Choropleth Map
# * Color Maps
# * HeatMap
# <script src="../lib/underscore.js"></script>
# <script src="../lib/backbone.js"></script>
# <script src="../lib/coffee-script.js"></script>
# <script src="../requireConfig.js"> </script>
# <script src="../lib/require-jquery.js"></script>
# <script type="text/coffeescript" src="examples.coffee"> </script>
| true | # Canvas-Vis Examples
# ===================
#
# This docrment is a collection of examples that use the Canvas-vis library. This file is built from `examples.coffee` in `build.sh`, which uses [Docco](http://jashkenas.github.io/docco/). Because Docco supports [Markdown](http://daringfireball.net/projects/markdown/) with inline HTML in comments, it is possible to execute `examples.coffee` within this document, producing running examples right next to their source code. Enjoy! --PI:NAME:<NAME>END_PI, April 2013
#
# [Colored Canvas](../examples/01_coloredCanvas.html)
# --------------
# <canvas id="coloredCanvas"></canvas>
#
# An example of
#
# * Creating a `Component`
# * Defining its `paint` method
# * Using the `graphicsDirty` event to schedule repainting
# * Binding a component to a Canvas
require ['cv/Component', 'cv/bindToCanvas'], (Component, bindToCanvas) ->
ColoredCanvas = Component.extend
initialize: ->
setInterval (=> @trigger 'graphicsDirty'), 1000
paint: (ctx, bounds) ->
ctx.fillStyle = randomColor()
ctx.fillRect bounds.x, bounds.y, bounds.w, bounds.h
randomColor = -> "rgb(#{r()},#{r()},#{r()})"
r = -> Math.floor(Math.random() * 255)
bindToCanvas 'coloredCanvas', new ColoredCanvas
# [Scatter Plot](../examples/02_ScatterPlot.html)
# --------------
# <canvas id="scatterPlot" width="450" height="450"></canvas>
require ['cv/Component', 'cv/bindToCanvas', 'cv/readCSV',
'cv/Viewport', 'cv/Rectangle', 'cv/Varset', 'cv/Scale', 'cv/mark']
, (Component, bindToCanvas, readCSV,
Viewport, Rectangle, Varset, Scale, mark) ->
readCSV '../data/iris.csv', (err, columns) ->
xVar = Varset.fromVariable columns['petal length']
yVar = Varset.fromVariable columns['sepal length']
varset = Varset.cross xVar, yVar
scales = [new Scale(1), new Scale(2)]
scale.init varset for scale in scales
ScatterPlot = Component.extend
paint: (ctx, bounds) ->
viewport.dest.copy bounds
for tuple in varset.tuples()
(point position tuple).render ctx, viewport
position = (tuple) ->
mark()
.x(scales[0].value tuple)
.y(scales[1].value tuple)
point = (mark) ->
mark.size(0.05)
.shape('circle')
.fillStyle('rgba(0,0,0,0.2)')
viewport = new Viewport
bindToCanvas 'scatterPlot', new ScatterPlot
# [Grammar of Graphics](../examples/03_GrammarOfGraphics.html)
# ------------------------------------------------------------
# <canvas id="grammarOfGraphics" width="450" height="450"></canvas>
# <textarea rows="20" cols="40" id="expressionBox">loading...</textarea>
# <div style="color:red" id='errorDiv'></div>
require ['cv/Component', 'cv/bindToCanvas', 'cv/readCSV',
'cv/Viewport', 'cv/Rectangle', 'cv/mark','cv/grammarOfGraphics']
, (Component, bindToCanvas, readCSV,
Viewport, Rectangle, mark, grammarOfGraphics) ->
initialExpr = """
DATA: x = "petal length"
DATA: y = "sepal length"
TRANS: x = x
TRANS: y = y
SCALE: linear(dim(1))
SCALE: linear(dim(2))
COORD: rect(dim(1, 2))
GUIDE: axis(dim(1))
GUIDE: axis(dim(2))
ELEMENT: point(position(x*y))
"""
readCSV '../data/iris.csv', (err, variables) ->
[keys, scales, keyToMark] = grammarOfGraphics.execute variables, initialExpr
viewport = new Viewport
GGComponent = Component.extend
paint: (ctx, bounds) ->
ctx.clearRect 0, 0, bounds.w, bounds.h
viewport.dest.copy bounds
for key in keys
(keyToMark key, scales).render ctx, viewport
component = new GGComponent
bindToCanvas 'grammarOfGraphics', component
changeExpr = (expr)->
[keys, scales, keyToMark] = grammarOfGraphics.execute variables, expr
component.trigger 'graphicsDirty'
expressionBox.value = initialExpr
expressionBox.addEventListener 'input', ->
try
errorDiv.innerHTML = ''
changeExpr expressionBox.value
catch error
errorDiv.innerHTML = error
# Roadmap
# =======
#
# * Bertin example from p.43
# * Nested Components example
# * Timeline of Population Data
# * Pan & Zoom example
# * Zoomable Scatter Plot of Iris Data
# * Zoomable Timeline of Population Data (A)
# * Parallel Coordinates of Iris Data (B)
# * Brushing & Linking Example containing A and B
# * Map of labeled US counties using Quadstream (C)
# * Zoomable Choropleth Map
# * Color Maps
# * HeatMap
# <script src="../lib/underscore.js"></script>
# <script src="../lib/backbone.js"></script>
# <script src="../lib/coffee-script.js"></script>
# <script src="../requireConfig.js"> </script>
# <script src="../lib/require-jquery.js"></script>
# <script type="text/coffeescript" src="examples.coffee"> </script>
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9987474083900452,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/disabled/test-cat.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.
common = require("../common.js")
assert = require("assert")
http = require("http")
console.log "hello world"
body = "exports.A = function() { return \"A\";}"
server = http.createServer((req, res) ->
console.log "req?"
res.sendHeader 200,
"Content-Length": body.length
"Content-Type": "text/plain"
res.sendBody body
res.finish()
return
)
server.listen common.PORT
errors = 0
successes = 0
promise = process.cat("http://localhost:" + common.PORT, "utf8")
promise.addCallback (content) ->
assert.equal body, content
server.close()
successes += 1
return
promise.addErrback ->
errors += 1
return
dirname = process.path.dirname(__filename)
fixtures = process.path.join(dirname, "fixtures")
x = process.path.join(fixtures, "x.txt")
promise = process.cat(x, "utf8")
promise.addCallback (content) ->
assert.equal "xyz", content.replace(/[\r\n]/, "")
successes += 1
return
promise.addErrback ->
errors += 1
return
process.on "exit", ->
assert.equal 2, successes
assert.equal 0, errors
return
| 67596 | # 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.
common = require("../common.js")
assert = require("assert")
http = require("http")
console.log "hello world"
body = "exports.A = function() { return \"A\";}"
server = http.createServer((req, res) ->
console.log "req?"
res.sendHeader 200,
"Content-Length": body.length
"Content-Type": "text/plain"
res.sendBody body
res.finish()
return
)
server.listen common.PORT
errors = 0
successes = 0
promise = process.cat("http://localhost:" + common.PORT, "utf8")
promise.addCallback (content) ->
assert.equal body, content
server.close()
successes += 1
return
promise.addErrback ->
errors += 1
return
dirname = process.path.dirname(__filename)
fixtures = process.path.join(dirname, "fixtures")
x = process.path.join(fixtures, "x.txt")
promise = process.cat(x, "utf8")
promise.addCallback (content) ->
assert.equal "xyz", content.replace(/[\r\n]/, "")
successes += 1
return
promise.addErrback ->
errors += 1
return
process.on "exit", ->
assert.equal 2, successes
assert.equal 0, errors
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.
common = require("../common.js")
assert = require("assert")
http = require("http")
console.log "hello world"
body = "exports.A = function() { return \"A\";}"
server = http.createServer((req, res) ->
console.log "req?"
res.sendHeader 200,
"Content-Length": body.length
"Content-Type": "text/plain"
res.sendBody body
res.finish()
return
)
server.listen common.PORT
errors = 0
successes = 0
promise = process.cat("http://localhost:" + common.PORT, "utf8")
promise.addCallback (content) ->
assert.equal body, content
server.close()
successes += 1
return
promise.addErrback ->
errors += 1
return
dirname = process.path.dirname(__filename)
fixtures = process.path.join(dirname, "fixtures")
x = process.path.join(fixtures, "x.txt")
promise = process.cat(x, "utf8")
promise.addCallback (content) ->
assert.equal "xyz", content.replace(/[\r\n]/, "")
successes += 1
return
promise.addErrback ->
errors += 1
return
process.on "exit", ->
assert.equal 2, successes
assert.equal 0, errors
return
|
[
{
"context": " is 10\nok b is 20\nok c is 30\n\nperson = {\n name: \"Moe\"\n family: {\n 'elder-brother': {\n address",
"end": 670,
"score": 0.9997063875198364,
"start": 667,
"tag": "NAME",
"value": "Moe"
},
{
"context": "addresses: [one, {city: b}]}}} = person\n\nok a is \... | QProjectManager/node_modules/jade/support/coffee-script/test/test_pattern_matching.coffee | rkoyama1623/Quantum | 35 | # Simple variable swapping.
a = -1
b = -2
[a, b] = [b, a]
eq a, -2
eq b, -1
func = ->
[a, b] = [b, a]
eq func().join(' '), '-1 -2'
eq a, -1
eq b, -2
#713
eq (onetwo = [1, 2]), [a, b] = [c, d] = onetwo
ok a is c is 1 and b is d is 2
# Array destructuring, including splats.
[x,y...,z] = [1,2,3,4,5]
ok x is 1
ok y.length is 3
ok z is 5
[x, [y, mids..., last], z..., end] = [1, [10, 20, 30, 40], 2,3,4, 5]
ok x is 1
ok y is 10
ok mids.length is 2 and mids[1] is 30
ok last is 40
ok z.length is 3 and z[2] is 4
ok end is 5
# Object destructuring.
obj = {x: 10, y: 20, z: 30}
{x: a, y: b, z: c} = obj
ok a is 10
ok b is 20
ok c is 30
person = {
name: "Moe"
family: {
'elder-brother': {
addresses: [
"first"
{
street: "101 Deercreek Ln."
city: "Moquasset NY, 10021"
}
]
}
}
}
{name: a, family: {'elder-brother': {addresses: [one, {city: b}]}}} = person
ok a is "Moe"
ok b is "Moquasset NY, 10021"
test = {
person: {
address: [
"------"
"Street 101"
"Apt 101"
"City 101"
]
}
}
{person: {address: [ignore, addr...]}} = test
ok addr.join(', ') is "Street 101, Apt 101, City 101"
# Pattern matching against an expression.
[a, b] = if true then [2, 1] else [1, 2]
ok a is 2
ok b is 1
# Pattern matching with object shorthand.
person = {
name: "Bob"
age: 26
dogs: ["Prince", "Bowie"]
}
{name, age, dogs: [first, second]} = person
ok name is "Bob"
ok age is 26
ok first is "Prince"
ok second is "Bowie"
# Pattern matching within for..loops
persons = {
George: { name: "Bob" },
Bob: { name: "Alice" }
Christopher: { name: "Stan" }
}
join1 = "#{key}: #{name}" for key, { name } of persons
eq join1.join(' / '), "George: Bob / Bob: Alice / Christopher: Stan"
persons = [
{ name: "Bob", parent: { name: "George" } },
{ name: "Alice", parent: { name: "Bob" } },
{ name: "Stan", parent: { name: "Christopher" } }
]
join2 = "#{parent}: #{name}" for { name, parent: { name: parent } } in persons
eq join1.join(' '), join2.join(' ')
persons = [['Bob', ['George']], ['Alice', ['Bob']], ['Stan', ['Christopher']]]
join3 = "#{parent}: #{name}" for [name, [parent]] in persons
eq join2.join(' '), join3.join(' ')
# Pattern matching doesn't clash with implicit block objects.
obj = a: 101
func = -> true
if func func
{a} = obj
ok a is 101
[x] = {0: y} = {'0': z} = [Math.random()]
ok x is y is z, 'destructuring in multiple'
# Destructuring into an object.
obj =
func: (list, object) ->
[@one, @two] = list
{@a, @b} = object
{@a} = object # must not unroll this
null
obj.func [1, 2], a: 'a', b: 'b'
eq obj.one, 1
eq obj.two, 2
eq obj.a, 'a'
eq obj.b, 'b'
| 179379 | # Simple variable swapping.
a = -1
b = -2
[a, b] = [b, a]
eq a, -2
eq b, -1
func = ->
[a, b] = [b, a]
eq func().join(' '), '-1 -2'
eq a, -1
eq b, -2
#713
eq (onetwo = [1, 2]), [a, b] = [c, d] = onetwo
ok a is c is 1 and b is d is 2
# Array destructuring, including splats.
[x,y...,z] = [1,2,3,4,5]
ok x is 1
ok y.length is 3
ok z is 5
[x, [y, mids..., last], z..., end] = [1, [10, 20, 30, 40], 2,3,4, 5]
ok x is 1
ok y is 10
ok mids.length is 2 and mids[1] is 30
ok last is 40
ok z.length is 3 and z[2] is 4
ok end is 5
# Object destructuring.
obj = {x: 10, y: 20, z: 30}
{x: a, y: b, z: c} = obj
ok a is 10
ok b is 20
ok c is 30
person = {
name: "<NAME>"
family: {
'elder-brother': {
addresses: [
"first"
{
street: "101 Deercreek Ln."
city: "Moquasset NY, 10021"
}
]
}
}
}
{name: a, family: {'elder-brother': {addresses: [one, {city: b}]}}} = person
ok a is "<NAME>"
ok b is "Moquasset NY, 10021"
test = {
person: {
address: [
"------"
"Street 101"
"Apt 101"
"City 101"
]
}
}
{person: {address: [ignore, addr...]}} = test
ok addr.join(', ') is "Street 101, Apt 101, City 101"
# Pattern matching against an expression.
[a, b] = if true then [2, 1] else [1, 2]
ok a is 2
ok b is 1
# Pattern matching with object shorthand.
person = {
name: "<NAME>"
age: 26
dogs: ["<NAME>", "<NAME>"]
}
{name, age, dogs: [first, second]} = person
ok name is "<NAME>"
ok age is 26
ok first is "<NAME>"
ok second is "<NAME>"
# Pattern matching within for..loops
persons = {
<NAME>: { name: "<NAME>" },
<NAME>: { name: "<NAME>" }
<NAME>: { name: "<NAME>" }
}
join1 = "#{key}: #{name}" for key, { name } of persons
eq join1.join(' / '), "<NAME>: <NAME> / <NAME>: <NAME> / <NAME>: <NAME>"
persons = [
{ name: "<NAME>", parent: { name: "<NAME>" } },
{ name: "<NAME>", parent: { name: "<NAME>" } },
{ name: "<NAME>", parent: { name: "<NAME>" } }
]
join2 = "#{parent}: #{name}" for { name, parent: { name: parent } } in persons
eq join1.join(' '), join2.join(' ')
persons = [['<NAME>', ['<NAME>']], ['<NAME>', ['<NAME>']], ['<NAME>', ['<NAME>']]]
join3 = "#{parent}: #{name}" for [name, [parent]] in persons
eq join2.join(' '), join3.join(' ')
# Pattern matching doesn't clash with implicit block objects.
obj = a: 101
func = -> true
if func func
{a} = obj
ok a is 101
[x] = {0: y} = {'0': z} = [Math.random()]
ok x is y is z, 'destructuring in multiple'
# Destructuring into an object.
obj =
func: (list, object) ->
[@one, @two] = list
{@a, @b} = object
{@a} = object # must not unroll this
null
obj.func [1, 2], a: 'a', b: 'b'
eq obj.one, 1
eq obj.two, 2
eq obj.a, 'a'
eq obj.b, 'b'
| true | # Simple variable swapping.
a = -1
b = -2
[a, b] = [b, a]
eq a, -2
eq b, -1
func = ->
[a, b] = [b, a]
eq func().join(' '), '-1 -2'
eq a, -1
eq b, -2
#713
eq (onetwo = [1, 2]), [a, b] = [c, d] = onetwo
ok a is c is 1 and b is d is 2
# Array destructuring, including splats.
[x,y...,z] = [1,2,3,4,5]
ok x is 1
ok y.length is 3
ok z is 5
[x, [y, mids..., last], z..., end] = [1, [10, 20, 30, 40], 2,3,4, 5]
ok x is 1
ok y is 10
ok mids.length is 2 and mids[1] is 30
ok last is 40
ok z.length is 3 and z[2] is 4
ok end is 5
# Object destructuring.
obj = {x: 10, y: 20, z: 30}
{x: a, y: b, z: c} = obj
ok a is 10
ok b is 20
ok c is 30
person = {
name: "PI:NAME:<NAME>END_PI"
family: {
'elder-brother': {
addresses: [
"first"
{
street: "101 Deercreek Ln."
city: "Moquasset NY, 10021"
}
]
}
}
}
{name: a, family: {'elder-brother': {addresses: [one, {city: b}]}}} = person
ok a is "PI:NAME:<NAME>END_PI"
ok b is "Moquasset NY, 10021"
test = {
person: {
address: [
"------"
"Street 101"
"Apt 101"
"City 101"
]
}
}
{person: {address: [ignore, addr...]}} = test
ok addr.join(', ') is "Street 101, Apt 101, City 101"
# Pattern matching against an expression.
[a, b] = if true then [2, 1] else [1, 2]
ok a is 2
ok b is 1
# Pattern matching with object shorthand.
person = {
name: "PI:NAME:<NAME>END_PI"
age: 26
dogs: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
}
{name, age, dogs: [first, second]} = person
ok name is "PI:NAME:<NAME>END_PI"
ok age is 26
ok first is "PI:NAME:<NAME>END_PI"
ok second is "PI:NAME:<NAME>END_PI"
# Pattern matching within for..loops
persons = {
PI:NAME:<NAME>END_PI: { name: "PI:NAME:<NAME>END_PI" },
PI:NAME:<NAME>END_PI: { name: "PI:NAME:<NAME>END_PI" }
PI:NAME:<NAME>END_PI: { name: "PI:NAME:<NAME>END_PI" }
}
join1 = "#{key}: #{name}" for key, { name } of persons
eq join1.join(' / '), "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"
persons = [
{ name: "PI:NAME:<NAME>END_PI", parent: { name: "PI:NAME:<NAME>END_PI" } },
{ name: "PI:NAME:<NAME>END_PI", parent: { name: "PI:NAME:<NAME>END_PI" } },
{ name: "PI:NAME:<NAME>END_PI", parent: { name: "PI:NAME:<NAME>END_PI" } }
]
join2 = "#{parent}: #{name}" for { name, parent: { name: parent } } in persons
eq join1.join(' '), join2.join(' ')
persons = [['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']]]
join3 = "#{parent}: #{name}" for [name, [parent]] in persons
eq join2.join(' '), join3.join(' ')
# Pattern matching doesn't clash with implicit block objects.
obj = a: 101
func = -> true
if func func
{a} = obj
ok a is 101
[x] = {0: y} = {'0': z} = [Math.random()]
ok x is y is z, 'destructuring in multiple'
# Destructuring into an object.
obj =
func: (list, object) ->
[@one, @two] = list
{@a, @b} = object
{@a} = object # must not unroll this
null
obj.func [1, 2], a: 'a', b: 'b'
eq obj.one, 1
eq obj.two, 2
eq obj.a, 'a'
eq obj.b, 'b'
|
[
{
"context": "name: 'b', slug: 'b', count: 2},\n # {name: 'b b', slug: 'b-b', count: 2},\n # {name: 'c', slu",
"end": 3636,
"score": 0.8704686164855957,
"start": 3635,
"tag": "NAME",
"value": "b"
},
{
"context": "name: 'b', slug: 'b', count: 2},\n # {name: 'b b', slug:... | bower_components/chaplin-utils/src/chaplin-utils.coffee | Luciekimotho/HDX-Hackathon | 0 | class ChapinUtils
constructor: (options) ->
# required
@mediator = options.mediator
@site = options.site
@enable = options.enable
@verbosity = options.verbosity
@urls = options.urls
# optional
@time = options?.time
@localhost = options?.localhost
@ua = options?.ua
@google = options?.google
JQUERY_EVENTS: """
blur focus focusin focusout load resize scroll unload click dblclick
mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave
change select submit keydown keypress keyup error
"""
init: =>
Minilog
.enable()
.pipe new Minilog.backends.jQuery
url: @urls.logger
interval: @log_interval
@logger = Minilog @site.id
@log_interval = @time?.logger ? 5000
@scroll_time = @time?.scroll ? 750
@analytics = @google?.analytics
@google_analytics_id = "#{@analytics?.id}-#{@analytics?.site_number}"
initGA: =>
if @localhost
cookie_domain = {cookieDomain: 'none'}
else
cookie_domain = 'auto'
ga 'create', @google_analytics_id, cookie_domain
ga 'require', 'displayfeatures'
changeURL: (pageId, params=null) ->
url = if params? then "#{pageId}?#{$.param(params)}" else pageId
Backbone.history.navigate url, trigger: false
smoothScroll: (postion) =>
$('html, body').animate scrollTop: postion, @scroll_time, 'linear'
filterCollection: (collection, query) ->
if query?.filterby?.key and query?.filterby?.value
new Chaplin.Collection collection.filter (model) ->
model.get(query.filterby.key) is JSON.parse query.filterby.value
else
collection
makeFilterer: (filterby, query) ->
(model) ->
if query and query.filterby?.key and query.filterby?.value
filter1 = model.get(query.filterby.key) is query.filterby.value
else
filter1 = true
return filter1 unless filterby?.key and filterby?.value
if filterby?.token
model_values = _.pluck(model.get(filterby.key), filterby.token)
else
model_values = model.get(filterby.key)
if _.isArray(model_values)
model_slugs = _.map(model_values, (value) -> s.slugify value)
filter2 = filterby.value in model_slugs
else
filter2 = filterby.value is s.slugify(model_values)
filter1 and filter2
makeComparator: (sortby, orderby) =>
(model) -> (if orderby is 'asc' then 1 else -1) * model.get sortby
getTags: (collection, options) ->
return [] unless collection.length > 0
options = options ? {}
attr = options.attr ? 'k:tags'
sortby = options.sortby ? 'count'
orderby = if options.orderby is 'asc' then 1 else -1
token = options.token
n = options.n
start = options.start ? 0
flattened = _.flatten collection.pluck attr
# ['a', 'c', 'B', 'b', 'b b', 'c'] or if tokenized
# [{token: 'a'}, {token: 'c'}, {token: 'B'}, {token: 'b'}, {token: 'b b'}]
all = if token then _.pluck(flattened, token) else flattened
# ['a', 'c', 'B', 'b', 'b b', 'c']
counts = _.countBy all, (name) -> name?.toLowerCase()
# {a: 1, c: 2, b: 2, b b: 1}
collected = ({name, slug: s.slugify(name), count} for name, count of counts)
# [
# {name: 'a', slug: 'a', count: 1},
# {name: 'c', slug: 'c', count: 2},
# {name: 'b', slug: 'b', count: 2},
# {name: 'b b', slug: 'b-b', count: 1},
# ]
cleaned = _.reject collected, (tag) -> tag.name in ['', 'undefined']
presorted = _.sortBy cleaned, 'name'
# [
# {name: 'a', slug: 'a', count: 1},
# {name: 'b', slug: 'b', count: 2},
# {name: 'b b', slug: 'b-b', count: 2},
# {name: 'c', slug: 'c', count: 1},
# ]
sorted = _.sortBy(presorted, (name) -> orderby * name[sortby])
# [
# {name: 'b', slug: 'b', count: 2},
# {name: 'b b', slug: 'b-b', count: 2},
# {name: 'a', slug: 'a', count: 1},
# {name: 'c', slug: 'c', count: 1},
# ]
if n then sorted[start...start + n] else sorted[start..]
checkIDs: ->
$('[id]').each ->
ids = $('[id="' + this.id + '"]')
if (ids.length > 1 and ids[0] is this)
console.warn "Multiple IDs for ##{this.id}"
# Logging helper
# ---------------------
_getPriority: (level) ->
switch level
when 'debug' then 1
when 'info' then 2
when 'warn' then 3
when 'error' then 4
when 'pageview' then 5
when 'screenview' then 6
when 'event' then 7
when 'transaction' then 8
when 'item' then 9
when 'social' then 10
else 0
log: (message, level='debug', options) =>
priority = @_getPriority level
url = @mediator.url
options = options ? {}
local_enabled = @enable.logger.local
remote_enabled = @enable.logger.remote
tracking_enabled = @analytics?.id and @enable.tracker
local_priority = priority >= @verbosity.logger.local
remote_priority = priority >= @verbosity.logger.remote
tracker_priority = priority >= @verbosity.tracker
log_local = local_enabled and local_priority
log_remote = remote_enabled and remote_priority
track = tracking_enabled and tracker_priority
if log_local and priority >= @verbosity.tracker
console.log "#{level} for #{url}"
else if log_local
console.log message
if log_remote or track
user_options =
time: (new Date()).getTime()
user: @mediator?.user?.get('email') ? @mediator?.user?.email
if log_remote
text = JSON.stringify message
message = if text.length > 512 then "size exceeded" else message
data = _.extend {message}, user_options
@logger[level] data
if track
ga (tracker) =>
hit_options =
v: 1
tid: @google_analytics_id
cid: tracker.get 'clientId'
uid: @mediator?.user?.get('id') ? @mediator?.user?.id
# uip: ip address
dr: document.referrer or 'direct'
ua: @ua
gclid: @google?.adwords_id
dclid: @google?.displayads_id
sr: "#{screen.width}x#{screen.height}"
vp: "#{$(window).width()}x#{$(window).height()}"
t: level
an: @site.title
aid: @site.id
av: @site.version
dp: url
dh: document.location.hostname
dt: message
switch level
when 'event'
hit_options = _.extend hit_options,
ec: options.category
ea: options.action
ev: options?.value
el: options?.label ? 'N/A'
when 'transaction'
hit_options = _.extend hit_options,
ti: options.trxn_id
tr: options?.amount ? 0
ts: options?.shipping ? 0
tt: options?.tax ? 0
cu: options?.cur ? 'USD'
ta: options?.affiliation ? 'N/A'
when 'item'
hit_options = _.extend hit_options,
ti: options.trxn_id
in: options.name
ip: options?.amount ? 0
iq: options?.qty ? 1
cu: options?.cur ? 'USD'
ic: options?.sku ? 'N/A'
iv: options?.category ? 'N/A'
when 'social'
hit_options = _.extend hit_options,
sn: options?.network ? 'facebook'
sa: options?.action ? 'like'
st: options?.target ? url
if level is 'experiment'
hit_options = _.extend hit_options,
xid: options.xid
xvar: options?.xvar ? 'A'
data = _.extend options, user_options, hit_options
$.post @urls.tracker, data
if module?.exports
# Commonjs
exports = module.exports = ChapinUtils
else if exports?
# Node.js
exports.ChapinUtils = ChapinUtils
else if define?.amd?
# Requirejs
define [], -> ChapinUtils
@ChapinUtils = ChapinUtils
else if window? or require?
# Browser
window.ChapinUtils = ChapinUtils
else
@ChapinUtils = ChapinUtils
| 3376 | class ChapinUtils
constructor: (options) ->
# required
@mediator = options.mediator
@site = options.site
@enable = options.enable
@verbosity = options.verbosity
@urls = options.urls
# optional
@time = options?.time
@localhost = options?.localhost
@ua = options?.ua
@google = options?.google
JQUERY_EVENTS: """
blur focus focusin focusout load resize scroll unload click dblclick
mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave
change select submit keydown keypress keyup error
"""
init: =>
Minilog
.enable()
.pipe new Minilog.backends.jQuery
url: @urls.logger
interval: @log_interval
@logger = Minilog @site.id
@log_interval = @time?.logger ? 5000
@scroll_time = @time?.scroll ? 750
@analytics = @google?.analytics
@google_analytics_id = "#{@analytics?.id}-#{@analytics?.site_number}"
initGA: =>
if @localhost
cookie_domain = {cookieDomain: 'none'}
else
cookie_domain = 'auto'
ga 'create', @google_analytics_id, cookie_domain
ga 'require', 'displayfeatures'
changeURL: (pageId, params=null) ->
url = if params? then "#{pageId}?#{$.param(params)}" else pageId
Backbone.history.navigate url, trigger: false
smoothScroll: (postion) =>
$('html, body').animate scrollTop: postion, @scroll_time, 'linear'
filterCollection: (collection, query) ->
if query?.filterby?.key and query?.filterby?.value
new Chaplin.Collection collection.filter (model) ->
model.get(query.filterby.key) is JSON.parse query.filterby.value
else
collection
makeFilterer: (filterby, query) ->
(model) ->
if query and query.filterby?.key and query.filterby?.value
filter1 = model.get(query.filterby.key) is query.filterby.value
else
filter1 = true
return filter1 unless filterby?.key and filterby?.value
if filterby?.token
model_values = _.pluck(model.get(filterby.key), filterby.token)
else
model_values = model.get(filterby.key)
if _.isArray(model_values)
model_slugs = _.map(model_values, (value) -> s.slugify value)
filter2 = filterby.value in model_slugs
else
filter2 = filterby.value is s.slugify(model_values)
filter1 and filter2
makeComparator: (sortby, orderby) =>
(model) -> (if orderby is 'asc' then 1 else -1) * model.get sortby
getTags: (collection, options) ->
return [] unless collection.length > 0
options = options ? {}
attr = options.attr ? 'k:tags'
sortby = options.sortby ? 'count'
orderby = if options.orderby is 'asc' then 1 else -1
token = options.token
n = options.n
start = options.start ? 0
flattened = _.flatten collection.pluck attr
# ['a', 'c', 'B', 'b', 'b b', 'c'] or if tokenized
# [{token: 'a'}, {token: 'c'}, {token: 'B'}, {token: 'b'}, {token: 'b b'}]
all = if token then _.pluck(flattened, token) else flattened
# ['a', 'c', 'B', 'b', 'b b', 'c']
counts = _.countBy all, (name) -> name?.toLowerCase()
# {a: 1, c: 2, b: 2, b b: 1}
collected = ({name, slug: s.slugify(name), count} for name, count of counts)
# [
# {name: 'a', slug: 'a', count: 1},
# {name: 'c', slug: 'c', count: 2},
# {name: 'b', slug: 'b', count: 2},
# {name: 'b b', slug: 'b-b', count: 1},
# ]
cleaned = _.reject collected, (tag) -> tag.name in ['', 'undefined']
presorted = _.sortBy cleaned, 'name'
# [
# {name: 'a', slug: 'a', count: 1},
# {name: 'b', slug: 'b', count: 2},
# {name: 'b <NAME>', slug: 'b-b', count: 2},
# {name: 'c', slug: 'c', count: 1},
# ]
sorted = _.sortBy(presorted, (name) -> orderby * name[sortby])
# [
# {name: 'b', slug: 'b', count: 2},
# {name: 'b <NAME>', slug: 'b-b', count: 2},
# {name: 'a', slug: 'a', count: 1},
# {name: 'c', slug: 'c', count: 1},
# ]
if n then sorted[start...start + n] else sorted[start..]
checkIDs: ->
$('[id]').each ->
ids = $('[id="' + this.id + '"]')
if (ids.length > 1 and ids[0] is this)
console.warn "Multiple IDs for ##{this.id}"
# Logging helper
# ---------------------
_getPriority: (level) ->
switch level
when 'debug' then 1
when 'info' then 2
when 'warn' then 3
when 'error' then 4
when 'pageview' then 5
when 'screenview' then 6
when 'event' then 7
when 'transaction' then 8
when 'item' then 9
when 'social' then 10
else 0
log: (message, level='debug', options) =>
priority = @_getPriority level
url = @mediator.url
options = options ? {}
local_enabled = @enable.logger.local
remote_enabled = @enable.logger.remote
tracking_enabled = @analytics?.id and @enable.tracker
local_priority = priority >= @verbosity.logger.local
remote_priority = priority >= @verbosity.logger.remote
tracker_priority = priority >= @verbosity.tracker
log_local = local_enabled and local_priority
log_remote = remote_enabled and remote_priority
track = tracking_enabled and tracker_priority
if log_local and priority >= @verbosity.tracker
console.log "#{level} for #{url}"
else if log_local
console.log message
if log_remote or track
user_options =
time: (new Date()).getTime()
user: @mediator?.user?.get('email') ? @mediator?.user?.email
if log_remote
text = JSON.stringify message
message = if text.length > 512 then "size exceeded" else message
data = _.extend {message}, user_options
@logger[level] data
if track
ga (tracker) =>
hit_options =
v: 1
tid: @google_analytics_id
cid: tracker.get 'clientId'
uid: @mediator?.user?.get('id') ? @mediator?.user?.id
# uip: ip address
dr: document.referrer or 'direct'
ua: @ua
gclid: @google?.adwords_id
dclid: @google?.displayads_id
sr: "#{screen.width}x#{screen.height}"
vp: "#{$(window).width()}x#{$(window).height()}"
t: level
an: @site.title
aid: @site.id
av: @site.version
dp: url
dh: document.location.hostname
dt: message
switch level
when 'event'
hit_options = _.extend hit_options,
ec: options.category
ea: options.action
ev: options?.value
el: options?.label ? 'N/A'
when 'transaction'
hit_options = _.extend hit_options,
ti: options.trxn_id
tr: options?.amount ? 0
ts: options?.shipping ? 0
tt: options?.tax ? 0
cu: options?.cur ? 'USD'
ta: options?.affiliation ? 'N/A'
when 'item'
hit_options = _.extend hit_options,
ti: options.trxn_id
in: options.name
ip: options?.amount ? 0
iq: options?.qty ? 1
cu: options?.cur ? 'USD'
ic: options?.sku ? 'N/A'
iv: options?.category ? 'N/A'
when 'social'
hit_options = _.extend hit_options,
sn: options?.network ? 'facebook'
sa: options?.action ? 'like'
st: options?.target ? url
if level is 'experiment'
hit_options = _.extend hit_options,
xid: options.xid
xvar: options?.xvar ? 'A'
data = _.extend options, user_options, hit_options
$.post @urls.tracker, data
if module?.exports
# Commonjs
exports = module.exports = ChapinUtils
else if exports?
# Node.js
exports.ChapinUtils = ChapinUtils
else if define?.amd?
# Requirejs
define [], -> ChapinUtils
@ChapinUtils = ChapinUtils
else if window? or require?
# Browser
window.ChapinUtils = ChapinUtils
else
@ChapinUtils = ChapinUtils
| true | class ChapinUtils
constructor: (options) ->
# required
@mediator = options.mediator
@site = options.site
@enable = options.enable
@verbosity = options.verbosity
@urls = options.urls
# optional
@time = options?.time
@localhost = options?.localhost
@ua = options?.ua
@google = options?.google
JQUERY_EVENTS: """
blur focus focusin focusout load resize scroll unload click dblclick
mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave
change select submit keydown keypress keyup error
"""
init: =>
Minilog
.enable()
.pipe new Minilog.backends.jQuery
url: @urls.logger
interval: @log_interval
@logger = Minilog @site.id
@log_interval = @time?.logger ? 5000
@scroll_time = @time?.scroll ? 750
@analytics = @google?.analytics
@google_analytics_id = "#{@analytics?.id}-#{@analytics?.site_number}"
initGA: =>
if @localhost
cookie_domain = {cookieDomain: 'none'}
else
cookie_domain = 'auto'
ga 'create', @google_analytics_id, cookie_domain
ga 'require', 'displayfeatures'
changeURL: (pageId, params=null) ->
url = if params? then "#{pageId}?#{$.param(params)}" else pageId
Backbone.history.navigate url, trigger: false
smoothScroll: (postion) =>
$('html, body').animate scrollTop: postion, @scroll_time, 'linear'
filterCollection: (collection, query) ->
if query?.filterby?.key and query?.filterby?.value
new Chaplin.Collection collection.filter (model) ->
model.get(query.filterby.key) is JSON.parse query.filterby.value
else
collection
makeFilterer: (filterby, query) ->
(model) ->
if query and query.filterby?.key and query.filterby?.value
filter1 = model.get(query.filterby.key) is query.filterby.value
else
filter1 = true
return filter1 unless filterby?.key and filterby?.value
if filterby?.token
model_values = _.pluck(model.get(filterby.key), filterby.token)
else
model_values = model.get(filterby.key)
if _.isArray(model_values)
model_slugs = _.map(model_values, (value) -> s.slugify value)
filter2 = filterby.value in model_slugs
else
filter2 = filterby.value is s.slugify(model_values)
filter1 and filter2
makeComparator: (sortby, orderby) =>
(model) -> (if orderby is 'asc' then 1 else -1) * model.get sortby
getTags: (collection, options) ->
return [] unless collection.length > 0
options = options ? {}
attr = options.attr ? 'k:tags'
sortby = options.sortby ? 'count'
orderby = if options.orderby is 'asc' then 1 else -1
token = options.token
n = options.n
start = options.start ? 0
flattened = _.flatten collection.pluck attr
# ['a', 'c', 'B', 'b', 'b b', 'c'] or if tokenized
# [{token: 'a'}, {token: 'c'}, {token: 'B'}, {token: 'b'}, {token: 'b b'}]
all = if token then _.pluck(flattened, token) else flattened
# ['a', 'c', 'B', 'b', 'b b', 'c']
counts = _.countBy all, (name) -> name?.toLowerCase()
# {a: 1, c: 2, b: 2, b b: 1}
collected = ({name, slug: s.slugify(name), count} for name, count of counts)
# [
# {name: 'a', slug: 'a', count: 1},
# {name: 'c', slug: 'c', count: 2},
# {name: 'b', slug: 'b', count: 2},
# {name: 'b b', slug: 'b-b', count: 1},
# ]
cleaned = _.reject collected, (tag) -> tag.name in ['', 'undefined']
presorted = _.sortBy cleaned, 'name'
# [
# {name: 'a', slug: 'a', count: 1},
# {name: 'b', slug: 'b', count: 2},
# {name: 'b PI:NAME:<NAME>END_PI', slug: 'b-b', count: 2},
# {name: 'c', slug: 'c', count: 1},
# ]
sorted = _.sortBy(presorted, (name) -> orderby * name[sortby])
# [
# {name: 'b', slug: 'b', count: 2},
# {name: 'b PI:NAME:<NAME>END_PI', slug: 'b-b', count: 2},
# {name: 'a', slug: 'a', count: 1},
# {name: 'c', slug: 'c', count: 1},
# ]
if n then sorted[start...start + n] else sorted[start..]
checkIDs: ->
$('[id]').each ->
ids = $('[id="' + this.id + '"]')
if (ids.length > 1 and ids[0] is this)
console.warn "Multiple IDs for ##{this.id}"
# Logging helper
# ---------------------
_getPriority: (level) ->
switch level
when 'debug' then 1
when 'info' then 2
when 'warn' then 3
when 'error' then 4
when 'pageview' then 5
when 'screenview' then 6
when 'event' then 7
when 'transaction' then 8
when 'item' then 9
when 'social' then 10
else 0
log: (message, level='debug', options) =>
priority = @_getPriority level
url = @mediator.url
options = options ? {}
local_enabled = @enable.logger.local
remote_enabled = @enable.logger.remote
tracking_enabled = @analytics?.id and @enable.tracker
local_priority = priority >= @verbosity.logger.local
remote_priority = priority >= @verbosity.logger.remote
tracker_priority = priority >= @verbosity.tracker
log_local = local_enabled and local_priority
log_remote = remote_enabled and remote_priority
track = tracking_enabled and tracker_priority
if log_local and priority >= @verbosity.tracker
console.log "#{level} for #{url}"
else if log_local
console.log message
if log_remote or track
user_options =
time: (new Date()).getTime()
user: @mediator?.user?.get('email') ? @mediator?.user?.email
if log_remote
text = JSON.stringify message
message = if text.length > 512 then "size exceeded" else message
data = _.extend {message}, user_options
@logger[level] data
if track
ga (tracker) =>
hit_options =
v: 1
tid: @google_analytics_id
cid: tracker.get 'clientId'
uid: @mediator?.user?.get('id') ? @mediator?.user?.id
# uip: ip address
dr: document.referrer or 'direct'
ua: @ua
gclid: @google?.adwords_id
dclid: @google?.displayads_id
sr: "#{screen.width}x#{screen.height}"
vp: "#{$(window).width()}x#{$(window).height()}"
t: level
an: @site.title
aid: @site.id
av: @site.version
dp: url
dh: document.location.hostname
dt: message
switch level
when 'event'
hit_options = _.extend hit_options,
ec: options.category
ea: options.action
ev: options?.value
el: options?.label ? 'N/A'
when 'transaction'
hit_options = _.extend hit_options,
ti: options.trxn_id
tr: options?.amount ? 0
ts: options?.shipping ? 0
tt: options?.tax ? 0
cu: options?.cur ? 'USD'
ta: options?.affiliation ? 'N/A'
when 'item'
hit_options = _.extend hit_options,
ti: options.trxn_id
in: options.name
ip: options?.amount ? 0
iq: options?.qty ? 1
cu: options?.cur ? 'USD'
ic: options?.sku ? 'N/A'
iv: options?.category ? 'N/A'
when 'social'
hit_options = _.extend hit_options,
sn: options?.network ? 'facebook'
sa: options?.action ? 'like'
st: options?.target ? url
if level is 'experiment'
hit_options = _.extend hit_options,
xid: options.xid
xvar: options?.xvar ? 'A'
data = _.extend options, user_options, hit_options
$.post @urls.tracker, data
if module?.exports
# Commonjs
exports = module.exports = ChapinUtils
else if exports?
# Node.js
exports.ChapinUtils = ChapinUtils
else if define?.amd?
# Requirejs
define [], -> ChapinUtils
@ChapinUtils = ChapinUtils
else if window? or require?
# Browser
window.ChapinUtils = ChapinUtils
else
@ChapinUtils = ChapinUtils
|
[
{
"context": "in entityKeys\n\n for searchTerm in [undefined, 'dopamine']\n\n for currentState in [undefined, 'some_de",
"end": 190,
"score": 0.7213444113731384,
"start": 182,
"tag": "PASSWORD",
"value": "dopamine"
}
] | src/glados/static/coffee/tests/DynamicURLs/SearchURLsTests.coffee | BNext-IQT/glados-frontend-chembl-main-interface | 33 | describe 'Search URLs', ->
entityKeys = _.keys(glados.Settings.ES_KEY_2_SEARCH_PATH)
entityKeys.unshift('all')
for entityKey in entityKeys
for searchTerm in [undefined, 'dopamine']
for currentState in [undefined, 'some_defined_state']
for fragmentOnly in [true, false]
test = (entityKey, searchTerm, currentState, fragmentOnly) ->
it "URL for #{entityKey}, searchTerm: '#{searchTerm}', state: '#{currentState}', fragmentOnly: '#{fragmentOnly}'", ->
searchURLGot = SearchModel.getInstance().getSearchURL(entityKey, searchTerm, currentState, fragmentOnly)
tab = 'all'
if entityKey? and _.has(glados.Settings.ES_KEY_2_SEARCH_PATH, entityKey)
tab = glados.Settings.ES_KEY_2_SEARCH_PATH[entityKey]
searchURLMustBe = ''
if not fragmentOnly
searchURLMustBe += glados.Settings.GLADOS_MAIN_ROUTER_BASE_URL
searchURLMustBe += "search_results/#{tab}"
else
searchURLMustBe += "#search_results/#{tab}"
if searchTerm? and _.isString(searchTerm) and searchTerm.trim().length > 0
searchURLMustBe += "/query=" + encodeURIComponent(searchTerm)
if currentState?
searchURLMustBe += "/state=#{currentState}"
expect(searchURLGot).toBe(searchURLMustBe)
test(entityKey, searchTerm, currentState, fragmentOnly) | 144348 | describe 'Search URLs', ->
entityKeys = _.keys(glados.Settings.ES_KEY_2_SEARCH_PATH)
entityKeys.unshift('all')
for entityKey in entityKeys
for searchTerm in [undefined, '<PASSWORD>']
for currentState in [undefined, 'some_defined_state']
for fragmentOnly in [true, false]
test = (entityKey, searchTerm, currentState, fragmentOnly) ->
it "URL for #{entityKey}, searchTerm: '#{searchTerm}', state: '#{currentState}', fragmentOnly: '#{fragmentOnly}'", ->
searchURLGot = SearchModel.getInstance().getSearchURL(entityKey, searchTerm, currentState, fragmentOnly)
tab = 'all'
if entityKey? and _.has(glados.Settings.ES_KEY_2_SEARCH_PATH, entityKey)
tab = glados.Settings.ES_KEY_2_SEARCH_PATH[entityKey]
searchURLMustBe = ''
if not fragmentOnly
searchURLMustBe += glados.Settings.GLADOS_MAIN_ROUTER_BASE_URL
searchURLMustBe += "search_results/#{tab}"
else
searchURLMustBe += "#search_results/#{tab}"
if searchTerm? and _.isString(searchTerm) and searchTerm.trim().length > 0
searchURLMustBe += "/query=" + encodeURIComponent(searchTerm)
if currentState?
searchURLMustBe += "/state=#{currentState}"
expect(searchURLGot).toBe(searchURLMustBe)
test(entityKey, searchTerm, currentState, fragmentOnly) | true | describe 'Search URLs', ->
entityKeys = _.keys(glados.Settings.ES_KEY_2_SEARCH_PATH)
entityKeys.unshift('all')
for entityKey in entityKeys
for searchTerm in [undefined, 'PI:PASSWORD:<PASSWORD>END_PI']
for currentState in [undefined, 'some_defined_state']
for fragmentOnly in [true, false]
test = (entityKey, searchTerm, currentState, fragmentOnly) ->
it "URL for #{entityKey}, searchTerm: '#{searchTerm}', state: '#{currentState}', fragmentOnly: '#{fragmentOnly}'", ->
searchURLGot = SearchModel.getInstance().getSearchURL(entityKey, searchTerm, currentState, fragmentOnly)
tab = 'all'
if entityKey? and _.has(glados.Settings.ES_KEY_2_SEARCH_PATH, entityKey)
tab = glados.Settings.ES_KEY_2_SEARCH_PATH[entityKey]
searchURLMustBe = ''
if not fragmentOnly
searchURLMustBe += glados.Settings.GLADOS_MAIN_ROUTER_BASE_URL
searchURLMustBe += "search_results/#{tab}"
else
searchURLMustBe += "#search_results/#{tab}"
if searchTerm? and _.isString(searchTerm) and searchTerm.trim().length > 0
searchURLMustBe += "/query=" + encodeURIComponent(searchTerm)
if currentState?
searchURLMustBe += "/state=#{currentState}"
expect(searchURLGot).toBe(searchURLMustBe)
test(entityKey, searchTerm, currentState, fragmentOnly) |
[
{
"context": " Backbone.sync.args[0][1].id.should.equal '530ebe92139b21efd6000071'\n Backbone.sync.args[0][1].i",
"end": 588,
"score": 0.5147683024406433,
"start": 587,
"tag": "KEY",
"value": "2"
},
{
"context": "kbone.sync.args[0][1].id.should.equal '530ebe92139b21efd6000071'\n... | src/mobile/apps/shows/test/routes.coffee | kanaabe/force | 1 | _ = require 'underscore'
sinon = require 'sinon'
moment = require 'moment'
Backbone = require 'backbone'
PartnerShow = require '../../../models/show'
{ fabricate } = require 'antigravity'
routes = require '../routes'
describe 'Shows routes', ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe '#index', ->
beforeEach ->
@res = render: sinon.stub()
it 'fetches the set and renders the index template with featured cities', (done)->
routes.index {}, @res
Backbone.sync.args[0][1].id.should.equal '530ebe92139b21efd6000071'
Backbone.sync.args[0][1].item_type.should.equal 'PartnerShow'
Backbone.sync.args[0][2].url.should.containEql 'api/v1/set/530ebe92139b21efd6000071/items'
Backbone.sync.args[0][2].success [fabricate 'show']
_.defer => _.defer =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].featuredCities.length.should.equal 10
done()
describe '#city', ->
beforeEach ->
@res = render: sinon.stub(), locals: sd: sinon.stub()
@next = sinon.stub()
it 'nexts if the city is not valid', ->
routes.city { params: city: 'meow' }, @res, @next
@next.called.should.be.true()
it 'renders the city template', (done) ->
routes.city { params: city: 'new-york' }, @res, @next
_.defer => _.defer =>
@res.render.called.should.be.true()
@res.render.args[0][0].should.equal 'city'
@res.render.args[0][1].city.name.should.equal 'New York'
done()
describe '#all-cities', ->
beforeEach ->
@res = render: sinon.stub()
it 'renders the all-cities template', (done) ->
routes.all_cities {}, @res, @next
_.defer => _.defer =>
@res.render.called.should.be.true()
@res.render.args[0][0].should.equal 'all_cities'
@res.render.args[0][1].cities.length.should.be.above 83
done()
| 84085 | _ = require 'underscore'
sinon = require 'sinon'
moment = require 'moment'
Backbone = require 'backbone'
PartnerShow = require '../../../models/show'
{ fabricate } = require 'antigravity'
routes = require '../routes'
describe 'Shows routes', ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe '#index', ->
beforeEach ->
@res = render: sinon.stub()
it 'fetches the set and renders the index template with featured cities', (done)->
routes.index {}, @res
Backbone.sync.args[0][1].id.should.equal '530ebe9<KEY>139<KEY>21efd6000071'
Backbone.sync.args[0][1].item_type.should.equal 'PartnerShow'
Backbone.sync.args[0][2].url.should.containEql 'api/v1/set/530ebe92139b21efd6000071/items'
Backbone.sync.args[0][2].success [fabricate 'show']
_.defer => _.defer =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].featuredCities.length.should.equal 10
done()
describe '#city', ->
beforeEach ->
@res = render: sinon.stub(), locals: sd: sinon.stub()
@next = sinon.stub()
it 'nexts if the city is not valid', ->
routes.city { params: city: 'meow' }, @res, @next
@next.called.should.be.true()
it 'renders the city template', (done) ->
routes.city { params: city: 'new-york' }, @res, @next
_.defer => _.defer =>
@res.render.called.should.be.true()
@res.render.args[0][0].should.equal 'city'
@res.render.args[0][1].city.name.should.equal 'New York'
done()
describe '#all-cities', ->
beforeEach ->
@res = render: sinon.stub()
it 'renders the all-cities template', (done) ->
routes.all_cities {}, @res, @next
_.defer => _.defer =>
@res.render.called.should.be.true()
@res.render.args[0][0].should.equal 'all_cities'
@res.render.args[0][1].cities.length.should.be.above 83
done()
| true | _ = require 'underscore'
sinon = require 'sinon'
moment = require 'moment'
Backbone = require 'backbone'
PartnerShow = require '../../../models/show'
{ fabricate } = require 'antigravity'
routes = require '../routes'
describe 'Shows routes', ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe '#index', ->
beforeEach ->
@res = render: sinon.stub()
it 'fetches the set and renders the index template with featured cities', (done)->
routes.index {}, @res
Backbone.sync.args[0][1].id.should.equal '530ebe9PI:KEY:<KEY>END_PI139PI:KEY:<KEY>END_PI21efd6000071'
Backbone.sync.args[0][1].item_type.should.equal 'PartnerShow'
Backbone.sync.args[0][2].url.should.containEql 'api/v1/set/530ebe92139b21efd6000071/items'
Backbone.sync.args[0][2].success [fabricate 'show']
_.defer => _.defer =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].featuredCities.length.should.equal 10
done()
describe '#city', ->
beforeEach ->
@res = render: sinon.stub(), locals: sd: sinon.stub()
@next = sinon.stub()
it 'nexts if the city is not valid', ->
routes.city { params: city: 'meow' }, @res, @next
@next.called.should.be.true()
it 'renders the city template', (done) ->
routes.city { params: city: 'new-york' }, @res, @next
_.defer => _.defer =>
@res.render.called.should.be.true()
@res.render.args[0][0].should.equal 'city'
@res.render.args[0][1].city.name.should.equal 'New York'
done()
describe '#all-cities', ->
beforeEach ->
@res = render: sinon.stub()
it 'renders the all-cities template', (done) ->
routes.all_cities {}, @res, @next
_.defer => _.defer =>
@res.render.called.should.be.true()
@res.render.args[0][0].should.equal 'all_cities'
@res.render.args[0][1].cities.length.should.be.above 83
done()
|
[
{
"context": " },(msg)=>\n @setMusicList msg.files\n\n #@app.client.sendRequest {\n # name: \"list_public_project_f",
"end": 5079,
"score": 0.8473628163337708,
"start": 5069,
"tag": "EMAIL",
"value": "app.client"
}
] | static/js/explore/projectdetails.coffee | francishero/microstudio | 0 | class @ProjectDetails
constructor:(@app)->
@menu = ["code","sprites","sounds","music","doc"]
for s in @menu
do (s)=>
document.getElementById("project-contents-menu-#{s}").addEventListener "click",()=>
@setSection s
@splitbar = new SplitBar("explore-project-details","horizontal")
@splitbar.setPosition(45)
@editor = ace.edit "project-contents-view-editor"
@editor.$blockScrolling = Infinity
@editor.setTheme("ace/theme/tomorrow_night_bright")
@editor.getSession().setMode("ace/mode/microscript")
@editor.setReadOnly(true)
@editor.getSession().setOptions
tabSize: 2
useSoftTabs: true
useWorker: false # disables lua autocorrection ; preserves syntax coloring
document.querySelector("#project-contents-source-import").addEventListener "click",()=>
return if not @app.project?
file = @selected_source
return if not file?
return if @imported_sources[file]
@imported_sources[file] = true
name = file.split(".")[0]
count = 1
while @app.project.getSource(name)?
count += 1
name = file.split(".")[0]+count
file = name+".ms"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "ms/#{file}"
content: @sources[@selected_source]
},(msg)=>
@app.project.updateSourceList()
@setSelectedSource(@selected_source)
document.querySelector("#project-contents-doc-import").addEventListener "click",()=>
return if not @app.project?
return if @imported_doc or not @doc?
@imported_doc = true
value = @app.doc_editor.editor.getValue()
if value? and value.length>0
value = value + "\n\n"+@doc
else
value = @doc
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "doc/doc.md"
content: value
},(msg)=>
@app.project.loadDoc()
document.querySelector("#project-contents-doc-import").classList.add "done"
document.querySelector("#project-contents-doc-import i").classList.add "fa-check"
document.querySelector("#project-contents-doc-import i").classList.remove "fa-download"
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get "Doc imported"
document.getElementById("post-project-comment-button").addEventListener "click",()=>
text = document.querySelector("#post-project-comment textarea").value
if text? and text.length>0
@postComment(text)
document.querySelector("#post-project-comment textarea").value = ""
document.getElementById("login-to-post-comment").addEventListener "click",()=>
@app.appui.showLoginPanel()
document.getElementById("validate-to-post-comment").addEventListener "click",()=>
@app.appui.setMainSection("usersettings")
set:(@project)->
@splitbar.update()
@sources = []
@sprites = []
@sounds = []
@music = []
@maps = []
@imported_sources = {}
@imported_doc = false
document.querySelector("#project-contents-doc-import").classList.remove "done"
document.querySelector("#project-contents-doc-import").style.display = if @app.project? then "block" else "none"
document.querySelector("#project-contents-source-import").style.display = if @app.project? then "block" else "none"
if @app.project?
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get("Import doc to")+" "+@app.project.title
document.querySelector("#project-contents-view .code-list").innerHTML = ""
document.querySelector("#project-contents-view .sprite-list").innerHTML = ""
document.querySelector("#project-contents-view .sound-list").innerHTML = ""
document.querySelector("#project-contents-view .music-list").innerHTML = ""
#document.querySelector("#project-contents-view .maps").innerHTML = ""
document.querySelector("#project-contents-view .doc-render").innerHTML = ""
section = "code"
for t in @project.tags
if t.indexOf("sprite")>=0
section = "sprites"
else if t.indexOf("tutorial")>=0 or t.indexOf("tutoriel")>=0
section = "doc"
if @project.type == "tutorial"
section = "doc"
@setSection(section)
@sources = {}
@selected_source = null
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "ms"
},(msg)=>
@setSourceList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sprites"
},(msg)=>
@setSpriteList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sounds"
},(msg)=>
@setSoundList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "music"
},(msg)=>
@setMusicList msg.files
#@app.client.sendRequest {
# name: "list_public_project_files"
# project: @project.id
# folder: "maps"
#},(msg)=>
# @setMapList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "doc"
},(msg)=>
@setDocList msg.files
@updateComments()
@updateCredentials()
a = document.querySelector("#project-contents-view .sprites .export-panel a")
a.href = "/#{@project.owner}/#{@project.slug}/export/sprites/"
a.download = "#{@project.slug}_sprites.zip"
updateCredentials:()->
if @app.user?
document.getElementById("login-to-post-comment").style.display = "none"
if @app.user.flags.validated
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "block"
else
document.getElementById("validate-to-post-comment").style.display = "inline-block"
document.getElementById("post-project-comment").style.display = "none"
else
document.getElementById("login-to-post-comment").style.display = "inline-block"
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "none"
loadFile:(url,callback)->
req = new XMLHttpRequest()
req.onreadystatechange = (event) =>
if req.readyState == XMLHttpRequest.DONE
if req.status == 200
callback(req.responseText)
req.open "GET",url
req.send()
setSection:(section)->
for s in @menu
if s == section
document.getElementById("project-contents-menu-#{s}").classList.add "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "block"
else
document.getElementById("project-contents-menu-#{s}").classList.remove "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "none"
return
createSourceEntry:(file)->
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "ms/#{file}"
},(msg)=>
@sources[file] = msg.content
div = document.createElement "div"
div.innerHTML = "<i class='fa fa-file'></i> #{file.split(".")[0]}"
document.querySelector("#project-contents-view .code-list").appendChild div
div.id = "project-contents-view-source-#{file}"
div.addEventListener "click",()=>@setSelectedSource(file)
if not @selected_source?
@setSelectedSource(file)
setSelectedSource:(file)->
@selected_source = file
for key of @sources
if key == file
document.getElementById("project-contents-view-source-#{key}").classList.add "selected"
else
document.getElementById("project-contents-view-source-#{key}").classList.remove "selected"
@editor.setValue @sources[file],-1
return if not @app.project?
if @imported_sources[file]
document.querySelector("#project-contents-source-import").classList.add "done"
document.querySelector("#project-contents-source-import i").classList.remove "fa-download"
document.querySelector("#project-contents-source-import i").classList.add "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Source file imported")
else
document.querySelector("#project-contents-source-import").classList.remove "done"
document.querySelector("#project-contents-source-import i").classList.add "fa-download"
document.querySelector("#project-contents-source-import i").classList.remove "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Import source file to")+" "+@app.project.title
setSourceList:(files)->
for f in files
@createSourceEntry(f.file)
return
createSpriteBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "sprite"
img = @createSpriteThumb(new Sprite(location.origin+"/#{@project.owner}/#{@project.slug}/#{file}",null,prefs))
div.appendChild img
if @app.project?
button = document.createElement "div"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-download"
button.appendChild i
span = document.createElement "span"
span.innerText = @app.translator.get("Import to project")+" #{@app.project.title}"
button.appendChild span
clicked = false
button.addEventListener "click",()=>
return if clicked
clicked = true
source = new Image
source.crossOrigin = "Anonymous"
source.src = location.origin+"/#{@project.owner}/#{@project.slug}/#{file}"
source.onload = ()=>
canvas = document.createElement "canvas"
canvas.width = source.width
canvas.height = source.height
canvas.getContext("2d").drawImage source,0,0
name = file.split(".")[0]
count = 1
while @app.project.getSprite(name)?
count += 1
name = file.split(".")[0]+count
file = name+".png"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{file}"
content: canvas.toDataURL().split(",")[1]
properties: prefs
},(msg)=>
@app.project.updateSpriteList()
div.style.width = "0px"
setTimeout (()=>div.style.display = "none"),1000
div.appendChild button
document.querySelector("#project-contents-view .sprite-list").appendChild div
createSpriteThumb:(sprite)->
canvas = document.createElement "canvas"
canvas.width = 100
canvas.height = 100
sprite.loaded = ()=>
context = canvas.getContext "2d"
frame = sprite.frames[0].getCanvas()
r = Math.min(100/frame.width,100/frame.height)
context.imageSmoothingEnabled = false
w = r*frame.width
h = r*frame.height
context.drawImage frame,50-w/2,50-h/2,w,h
mouseover = false
update = ()=>
if mouseover and sprite.frames.length>1
requestAnimationFrame ()=>update()
return if sprite.frames.length<1
dt = 1000/sprite.fps
t = Date.now()
frame = if mouseover then Math.floor(t/dt)%sprite.frames.length else 0
context = canvas.getContext "2d"
context.imageSmoothingEnabled = false
context.clearRect 0,0,100,100
frame = sprite.frames[frame].getCanvas()
r = Math.min(100/frame.width,100/frame.height)
w = r*frame.width
h = r*frame.height
context.drawImage frame,50-w/2,50-h/2,w,h
canvas.addEventListener "mouseenter",()=>
mouseover = true
update()
canvas.addEventListener "mouseout",()=>
mouseover = false
canvas.updateSprite = update
canvas
setSpriteList:(files)->
for f in files
@createSpriteBox(f.file,f.properties)
return
createImportButton:(div,file,folder)->
button = document.createElement "div"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-download"
button.appendChild i
span = document.createElement "span"
span.innerText = @app.translator.get("Import to project")+" #{@app.project.title}"
button.appendChild span
clicked = false
button.addEventListener "click",()=>
return if clicked
clicked = true
source = new Image
source.crossOrigin = "Anonymous"
source.src = location.origin+"/#{@project.owner}/#{@project.slug}/#{file}"
source.onload = ()=>
canvas = document.createElement "canvas"
canvas.width = source.width
canvas.height = source.height
canvas.getContext("2d").drawImage source,0,0
name = file.split(".")[0]
count = 1
while @app.project.getSprite(name)?
count += 1
name = file.split(".")[0]+count
file = name+".png"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{file}"
content: canvas.toDataURL().split(",")[1]
properties: prefs
},(msg)=>
@app.project.updateSpriteList()
div.style.width = "0px"
setTimeout (()=>div.style.display = "none"),1000
createSoundBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "sound"
img = new Image
img.src = location.origin+"/#{@project.owner}/#{@project.slug}/sounds_th/#{file.replace(".wav",".png")}"
div.appendChild img
div.appendChild document.createElement "br"
span = document.createElement "span"
span.innerText = file.split(".")[0]
div.appendChild span
div.addEventListener "click",()=>
url = location.origin+"/#{@project.owner}/#{@project.slug}/sounds/#{file}"
audio = new Audio(url)
audio.play()
funk = ()->
audio.pause()
document.body.removeEventListener "mousedown",funk
document.body.addEventListener "mousedown",funk
# if @app.project?
# createImportButton div
document.querySelector("#project-contents-view .sound-list").appendChild div
setSoundList:(files)->
if files.length>0
document.getElementById("project-contents-menu-sounds").style.display = "block"
else
document.getElementById("project-contents-menu-sounds").style.display = "none"
for f in files
@createSoundBox(f.file)
return
createMusicBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "music"
img = new Image
img.src = location.origin+"/#{@project.owner}/#{@project.slug}/music_th/#{file.replace(".mp3",".png")}"
div.appendChild img
div.appendChild document.createElement "br"
span = document.createElement "span"
span.innerText = file.split(".")[0]
div.appendChild span
div.addEventListener "click",()=>
url = location.origin+"/#{@project.owner}/#{@project.slug}/music/#{file}"
audio = new Audio(url)
audio.play()
funk = ()->
audio.pause()
document.body.removeEventListener "mousedown",funk
document.body.addEventListener "mousedown",funk
# if @app.project?
# createImportButton div
document.querySelector("#project-contents-view .music-list").appendChild div
setMusicList:(files)->
if files.length>0
document.getElementById("project-contents-menu-music").style.display = "block"
else
document.getElementById("project-contents-menu-music").style.display = "none"
for f in files
@createMusicBox(f.file,f.properties)
return
setMapList:(files)->
console.info files
setDocList:(files)->
if files.length>0
document.getElementById("project-contents-menu-doc").style.display = "block"
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "doc/#{files[0].file}"
},(msg)=>
@doc = msg.content
if @doc? and @doc.trim().length>0
document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize marked msg.content
else
document.getElementById("project-contents-menu-doc").style.display = "none"
else
document.getElementById("project-contents-menu-doc").style.display = "none"
#console.info files
updateComments:()->
@app.client.sendRequest {
name: "get_project_comments"
project: @project.id
},(msg)=>
e = document.getElementById("project-comment-list")
e.innerHTML = ""
if msg.comments?
for c in msg.comments
@createCommentBox(c)
return
createCommentBox:(c)->
console.info c
div = document.createElement("div")
div.classList.add "comment"
author = document.createElement("div")
author.classList.add "author"
i = document.createElement("i")
i.classList.add "fa"
i.classList.add "fa-user"
span = document.createElement "span"
span.innerText = c.user
author.appendChild i
author.appendChild span
author = @app.appui.createUserTag(c.user,c.user_info.tier)
time = document.createElement "div"
time.classList.add "time"
t = (Date.now()-c.time)/60000
if t<2
tt = @app.translator.get("now")
else if t<120
tt = @app.translator.get("%NUM% minutes ago").replace("%NUM%",Math.round(t))
else
t /= 60
if t<48
tt = @app.translator.get("%NUM% hours ago").replace("%NUM%",Math.round(t))
else
t/= 24
if t<14
tt = @app.translator.get("%NUM% days ago").replace("%NUM%",Math.round(t))
else if t<30
tt = @app.translator.get("%NUM% weeks ago").replace("%NUM%",Math.round(t/7))
else
tt = new Date(c.time).toLocaleDateString(@app.translator.lang,{ year: 'numeric', month: 'long', day: 'numeric' })
time.innerText = tt
div.appendChild time
div.appendChild author
if @app.user? and (@app.user.nick == c.user or @app.user.flags.admin)
buttons = document.createElement "div"
buttons.classList.add "buttons"
#buttons.appendChild @createButton "edit","Edit","green",()=>
# @editComment c
#buttons.appendChild document.createElement "br"
buttons.appendChild @createButton "trash","Delete","red",()=>
@deleteComment c
div.appendChild buttons
contents = document.createElement "div"
contents.classList.add "contents"
contents.innerHTML = DOMPurify.sanitize marked c.text
div.appendChild contents
clear = document.createElement "div"
clear.style = "clear:both"
div.appendChild clear
document.getElementById("project-comment-list").appendChild div
createButton:(icon,text,color,callback)->
button = document.createElement "div"
button.classList.add "small"+color+"button"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-#{icon}"
button.appendChild i
span = document.createElement "span"
span.innerText = text
button.appendChild span
button.addEventListener "click",()=>callback()
button
postComment:(text)->
@app.client.sendRequest {
name: "add_project_comment"
project: @project.id
text: text
},(msg)=>
@updateComments()
editComment:(id,text)->
deleteComment:(c)->
if confirm @app.translator.get("Do you really want to delete this comment?")
@app.client.sendRequest {
name: "delete_project_comment"
project: @project.id
id: c.id
},(msg)=>
@updateComments()
| 57833 | class @ProjectDetails
constructor:(@app)->
@menu = ["code","sprites","sounds","music","doc"]
for s in @menu
do (s)=>
document.getElementById("project-contents-menu-#{s}").addEventListener "click",()=>
@setSection s
@splitbar = new SplitBar("explore-project-details","horizontal")
@splitbar.setPosition(45)
@editor = ace.edit "project-contents-view-editor"
@editor.$blockScrolling = Infinity
@editor.setTheme("ace/theme/tomorrow_night_bright")
@editor.getSession().setMode("ace/mode/microscript")
@editor.setReadOnly(true)
@editor.getSession().setOptions
tabSize: 2
useSoftTabs: true
useWorker: false # disables lua autocorrection ; preserves syntax coloring
document.querySelector("#project-contents-source-import").addEventListener "click",()=>
return if not @app.project?
file = @selected_source
return if not file?
return if @imported_sources[file]
@imported_sources[file] = true
name = file.split(".")[0]
count = 1
while @app.project.getSource(name)?
count += 1
name = file.split(".")[0]+count
file = name+".ms"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "ms/#{file}"
content: @sources[@selected_source]
},(msg)=>
@app.project.updateSourceList()
@setSelectedSource(@selected_source)
document.querySelector("#project-contents-doc-import").addEventListener "click",()=>
return if not @app.project?
return if @imported_doc or not @doc?
@imported_doc = true
value = @app.doc_editor.editor.getValue()
if value? and value.length>0
value = value + "\n\n"+@doc
else
value = @doc
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "doc/doc.md"
content: value
},(msg)=>
@app.project.loadDoc()
document.querySelector("#project-contents-doc-import").classList.add "done"
document.querySelector("#project-contents-doc-import i").classList.add "fa-check"
document.querySelector("#project-contents-doc-import i").classList.remove "fa-download"
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get "Doc imported"
document.getElementById("post-project-comment-button").addEventListener "click",()=>
text = document.querySelector("#post-project-comment textarea").value
if text? and text.length>0
@postComment(text)
document.querySelector("#post-project-comment textarea").value = ""
document.getElementById("login-to-post-comment").addEventListener "click",()=>
@app.appui.showLoginPanel()
document.getElementById("validate-to-post-comment").addEventListener "click",()=>
@app.appui.setMainSection("usersettings")
set:(@project)->
@splitbar.update()
@sources = []
@sprites = []
@sounds = []
@music = []
@maps = []
@imported_sources = {}
@imported_doc = false
document.querySelector("#project-contents-doc-import").classList.remove "done"
document.querySelector("#project-contents-doc-import").style.display = if @app.project? then "block" else "none"
document.querySelector("#project-contents-source-import").style.display = if @app.project? then "block" else "none"
if @app.project?
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get("Import doc to")+" "+@app.project.title
document.querySelector("#project-contents-view .code-list").innerHTML = ""
document.querySelector("#project-contents-view .sprite-list").innerHTML = ""
document.querySelector("#project-contents-view .sound-list").innerHTML = ""
document.querySelector("#project-contents-view .music-list").innerHTML = ""
#document.querySelector("#project-contents-view .maps").innerHTML = ""
document.querySelector("#project-contents-view .doc-render").innerHTML = ""
section = "code"
for t in @project.tags
if t.indexOf("sprite")>=0
section = "sprites"
else if t.indexOf("tutorial")>=0 or t.indexOf("tutoriel")>=0
section = "doc"
if @project.type == "tutorial"
section = "doc"
@setSection(section)
@sources = {}
@selected_source = null
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "ms"
},(msg)=>
@setSourceList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sprites"
},(msg)=>
@setSpriteList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sounds"
},(msg)=>
@setSoundList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "music"
},(msg)=>
@setMusicList msg.files
#@<EMAIL>.sendRequest {
# name: "list_public_project_files"
# project: @project.id
# folder: "maps"
#},(msg)=>
# @setMapList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "doc"
},(msg)=>
@setDocList msg.files
@updateComments()
@updateCredentials()
a = document.querySelector("#project-contents-view .sprites .export-panel a")
a.href = "/#{@project.owner}/#{@project.slug}/export/sprites/"
a.download = "#{@project.slug}_sprites.zip"
updateCredentials:()->
if @app.user?
document.getElementById("login-to-post-comment").style.display = "none"
if @app.user.flags.validated
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "block"
else
document.getElementById("validate-to-post-comment").style.display = "inline-block"
document.getElementById("post-project-comment").style.display = "none"
else
document.getElementById("login-to-post-comment").style.display = "inline-block"
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "none"
loadFile:(url,callback)->
req = new XMLHttpRequest()
req.onreadystatechange = (event) =>
if req.readyState == XMLHttpRequest.DONE
if req.status == 200
callback(req.responseText)
req.open "GET",url
req.send()
setSection:(section)->
for s in @menu
if s == section
document.getElementById("project-contents-menu-#{s}").classList.add "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "block"
else
document.getElementById("project-contents-menu-#{s}").classList.remove "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "none"
return
createSourceEntry:(file)->
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "ms/#{file}"
},(msg)=>
@sources[file] = msg.content
div = document.createElement "div"
div.innerHTML = "<i class='fa fa-file'></i> #{file.split(".")[0]}"
document.querySelector("#project-contents-view .code-list").appendChild div
div.id = "project-contents-view-source-#{file}"
div.addEventListener "click",()=>@setSelectedSource(file)
if not @selected_source?
@setSelectedSource(file)
setSelectedSource:(file)->
@selected_source = file
for key of @sources
if key == file
document.getElementById("project-contents-view-source-#{key}").classList.add "selected"
else
document.getElementById("project-contents-view-source-#{key}").classList.remove "selected"
@editor.setValue @sources[file],-1
return if not @app.project?
if @imported_sources[file]
document.querySelector("#project-contents-source-import").classList.add "done"
document.querySelector("#project-contents-source-import i").classList.remove "fa-download"
document.querySelector("#project-contents-source-import i").classList.add "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Source file imported")
else
document.querySelector("#project-contents-source-import").classList.remove "done"
document.querySelector("#project-contents-source-import i").classList.add "fa-download"
document.querySelector("#project-contents-source-import i").classList.remove "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Import source file to")+" "+@app.project.title
setSourceList:(files)->
for f in files
@createSourceEntry(f.file)
return
createSpriteBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "sprite"
img = @createSpriteThumb(new Sprite(location.origin+"/#{@project.owner}/#{@project.slug}/#{file}",null,prefs))
div.appendChild img
if @app.project?
button = document.createElement "div"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-download"
button.appendChild i
span = document.createElement "span"
span.innerText = @app.translator.get("Import to project")+" #{@app.project.title}"
button.appendChild span
clicked = false
button.addEventListener "click",()=>
return if clicked
clicked = true
source = new Image
source.crossOrigin = "Anonymous"
source.src = location.origin+"/#{@project.owner}/#{@project.slug}/#{file}"
source.onload = ()=>
canvas = document.createElement "canvas"
canvas.width = source.width
canvas.height = source.height
canvas.getContext("2d").drawImage source,0,0
name = file.split(".")[0]
count = 1
while @app.project.getSprite(name)?
count += 1
name = file.split(".")[0]+count
file = name+".png"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{file}"
content: canvas.toDataURL().split(",")[1]
properties: prefs
},(msg)=>
@app.project.updateSpriteList()
div.style.width = "0px"
setTimeout (()=>div.style.display = "none"),1000
div.appendChild button
document.querySelector("#project-contents-view .sprite-list").appendChild div
createSpriteThumb:(sprite)->
canvas = document.createElement "canvas"
canvas.width = 100
canvas.height = 100
sprite.loaded = ()=>
context = canvas.getContext "2d"
frame = sprite.frames[0].getCanvas()
r = Math.min(100/frame.width,100/frame.height)
context.imageSmoothingEnabled = false
w = r*frame.width
h = r*frame.height
context.drawImage frame,50-w/2,50-h/2,w,h
mouseover = false
update = ()=>
if mouseover and sprite.frames.length>1
requestAnimationFrame ()=>update()
return if sprite.frames.length<1
dt = 1000/sprite.fps
t = Date.now()
frame = if mouseover then Math.floor(t/dt)%sprite.frames.length else 0
context = canvas.getContext "2d"
context.imageSmoothingEnabled = false
context.clearRect 0,0,100,100
frame = sprite.frames[frame].getCanvas()
r = Math.min(100/frame.width,100/frame.height)
w = r*frame.width
h = r*frame.height
context.drawImage frame,50-w/2,50-h/2,w,h
canvas.addEventListener "mouseenter",()=>
mouseover = true
update()
canvas.addEventListener "mouseout",()=>
mouseover = false
canvas.updateSprite = update
canvas
setSpriteList:(files)->
for f in files
@createSpriteBox(f.file,f.properties)
return
createImportButton:(div,file,folder)->
button = document.createElement "div"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-download"
button.appendChild i
span = document.createElement "span"
span.innerText = @app.translator.get("Import to project")+" #{@app.project.title}"
button.appendChild span
clicked = false
button.addEventListener "click",()=>
return if clicked
clicked = true
source = new Image
source.crossOrigin = "Anonymous"
source.src = location.origin+"/#{@project.owner}/#{@project.slug}/#{file}"
source.onload = ()=>
canvas = document.createElement "canvas"
canvas.width = source.width
canvas.height = source.height
canvas.getContext("2d").drawImage source,0,0
name = file.split(".")[0]
count = 1
while @app.project.getSprite(name)?
count += 1
name = file.split(".")[0]+count
file = name+".png"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{file}"
content: canvas.toDataURL().split(",")[1]
properties: prefs
},(msg)=>
@app.project.updateSpriteList()
div.style.width = "0px"
setTimeout (()=>div.style.display = "none"),1000
createSoundBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "sound"
img = new Image
img.src = location.origin+"/#{@project.owner}/#{@project.slug}/sounds_th/#{file.replace(".wav",".png")}"
div.appendChild img
div.appendChild document.createElement "br"
span = document.createElement "span"
span.innerText = file.split(".")[0]
div.appendChild span
div.addEventListener "click",()=>
url = location.origin+"/#{@project.owner}/#{@project.slug}/sounds/#{file}"
audio = new Audio(url)
audio.play()
funk = ()->
audio.pause()
document.body.removeEventListener "mousedown",funk
document.body.addEventListener "mousedown",funk
# if @app.project?
# createImportButton div
document.querySelector("#project-contents-view .sound-list").appendChild div
setSoundList:(files)->
if files.length>0
document.getElementById("project-contents-menu-sounds").style.display = "block"
else
document.getElementById("project-contents-menu-sounds").style.display = "none"
for f in files
@createSoundBox(f.file)
return
createMusicBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "music"
img = new Image
img.src = location.origin+"/#{@project.owner}/#{@project.slug}/music_th/#{file.replace(".mp3",".png")}"
div.appendChild img
div.appendChild document.createElement "br"
span = document.createElement "span"
span.innerText = file.split(".")[0]
div.appendChild span
div.addEventListener "click",()=>
url = location.origin+"/#{@project.owner}/#{@project.slug}/music/#{file}"
audio = new Audio(url)
audio.play()
funk = ()->
audio.pause()
document.body.removeEventListener "mousedown",funk
document.body.addEventListener "mousedown",funk
# if @app.project?
# createImportButton div
document.querySelector("#project-contents-view .music-list").appendChild div
setMusicList:(files)->
if files.length>0
document.getElementById("project-contents-menu-music").style.display = "block"
else
document.getElementById("project-contents-menu-music").style.display = "none"
for f in files
@createMusicBox(f.file,f.properties)
return
setMapList:(files)->
console.info files
setDocList:(files)->
if files.length>0
document.getElementById("project-contents-menu-doc").style.display = "block"
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "doc/#{files[0].file}"
},(msg)=>
@doc = msg.content
if @doc? and @doc.trim().length>0
document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize marked msg.content
else
document.getElementById("project-contents-menu-doc").style.display = "none"
else
document.getElementById("project-contents-menu-doc").style.display = "none"
#console.info files
updateComments:()->
@app.client.sendRequest {
name: "get_project_comments"
project: @project.id
},(msg)=>
e = document.getElementById("project-comment-list")
e.innerHTML = ""
if msg.comments?
for c in msg.comments
@createCommentBox(c)
return
createCommentBox:(c)->
console.info c
div = document.createElement("div")
div.classList.add "comment"
author = document.createElement("div")
author.classList.add "author"
i = document.createElement("i")
i.classList.add "fa"
i.classList.add "fa-user"
span = document.createElement "span"
span.innerText = c.user
author.appendChild i
author.appendChild span
author = @app.appui.createUserTag(c.user,c.user_info.tier)
time = document.createElement "div"
time.classList.add "time"
t = (Date.now()-c.time)/60000
if t<2
tt = @app.translator.get("now")
else if t<120
tt = @app.translator.get("%NUM% minutes ago").replace("%NUM%",Math.round(t))
else
t /= 60
if t<48
tt = @app.translator.get("%NUM% hours ago").replace("%NUM%",Math.round(t))
else
t/= 24
if t<14
tt = @app.translator.get("%NUM% days ago").replace("%NUM%",Math.round(t))
else if t<30
tt = @app.translator.get("%NUM% weeks ago").replace("%NUM%",Math.round(t/7))
else
tt = new Date(c.time).toLocaleDateString(@app.translator.lang,{ year: 'numeric', month: 'long', day: 'numeric' })
time.innerText = tt
div.appendChild time
div.appendChild author
if @app.user? and (@app.user.nick == c.user or @app.user.flags.admin)
buttons = document.createElement "div"
buttons.classList.add "buttons"
#buttons.appendChild @createButton "edit","Edit","green",()=>
# @editComment c
#buttons.appendChild document.createElement "br"
buttons.appendChild @createButton "trash","Delete","red",()=>
@deleteComment c
div.appendChild buttons
contents = document.createElement "div"
contents.classList.add "contents"
contents.innerHTML = DOMPurify.sanitize marked c.text
div.appendChild contents
clear = document.createElement "div"
clear.style = "clear:both"
div.appendChild clear
document.getElementById("project-comment-list").appendChild div
createButton:(icon,text,color,callback)->
button = document.createElement "div"
button.classList.add "small"+color+"button"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-#{icon}"
button.appendChild i
span = document.createElement "span"
span.innerText = text
button.appendChild span
button.addEventListener "click",()=>callback()
button
postComment:(text)->
@app.client.sendRequest {
name: "add_project_comment"
project: @project.id
text: text
},(msg)=>
@updateComments()
editComment:(id,text)->
deleteComment:(c)->
if confirm @app.translator.get("Do you really want to delete this comment?")
@app.client.sendRequest {
name: "delete_project_comment"
project: @project.id
id: c.id
},(msg)=>
@updateComments()
| true | class @ProjectDetails
constructor:(@app)->
@menu = ["code","sprites","sounds","music","doc"]
for s in @menu
do (s)=>
document.getElementById("project-contents-menu-#{s}").addEventListener "click",()=>
@setSection s
@splitbar = new SplitBar("explore-project-details","horizontal")
@splitbar.setPosition(45)
@editor = ace.edit "project-contents-view-editor"
@editor.$blockScrolling = Infinity
@editor.setTheme("ace/theme/tomorrow_night_bright")
@editor.getSession().setMode("ace/mode/microscript")
@editor.setReadOnly(true)
@editor.getSession().setOptions
tabSize: 2
useSoftTabs: true
useWorker: false # disables lua autocorrection ; preserves syntax coloring
document.querySelector("#project-contents-source-import").addEventListener "click",()=>
return if not @app.project?
file = @selected_source
return if not file?
return if @imported_sources[file]
@imported_sources[file] = true
name = file.split(".")[0]
count = 1
while @app.project.getSource(name)?
count += 1
name = file.split(".")[0]+count
file = name+".ms"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "ms/#{file}"
content: @sources[@selected_source]
},(msg)=>
@app.project.updateSourceList()
@setSelectedSource(@selected_source)
document.querySelector("#project-contents-doc-import").addEventListener "click",()=>
return if not @app.project?
return if @imported_doc or not @doc?
@imported_doc = true
value = @app.doc_editor.editor.getValue()
if value? and value.length>0
value = value + "\n\n"+@doc
else
value = @doc
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "doc/doc.md"
content: value
},(msg)=>
@app.project.loadDoc()
document.querySelector("#project-contents-doc-import").classList.add "done"
document.querySelector("#project-contents-doc-import i").classList.add "fa-check"
document.querySelector("#project-contents-doc-import i").classList.remove "fa-download"
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get "Doc imported"
document.getElementById("post-project-comment-button").addEventListener "click",()=>
text = document.querySelector("#post-project-comment textarea").value
if text? and text.length>0
@postComment(text)
document.querySelector("#post-project-comment textarea").value = ""
document.getElementById("login-to-post-comment").addEventListener "click",()=>
@app.appui.showLoginPanel()
document.getElementById("validate-to-post-comment").addEventListener "click",()=>
@app.appui.setMainSection("usersettings")
set:(@project)->
@splitbar.update()
@sources = []
@sprites = []
@sounds = []
@music = []
@maps = []
@imported_sources = {}
@imported_doc = false
document.querySelector("#project-contents-doc-import").classList.remove "done"
document.querySelector("#project-contents-doc-import").style.display = if @app.project? then "block" else "none"
document.querySelector("#project-contents-source-import").style.display = if @app.project? then "block" else "none"
if @app.project?
document.querySelector("#project-contents-doc-import span").innerText = @app.translator.get("Import doc to")+" "+@app.project.title
document.querySelector("#project-contents-view .code-list").innerHTML = ""
document.querySelector("#project-contents-view .sprite-list").innerHTML = ""
document.querySelector("#project-contents-view .sound-list").innerHTML = ""
document.querySelector("#project-contents-view .music-list").innerHTML = ""
#document.querySelector("#project-contents-view .maps").innerHTML = ""
document.querySelector("#project-contents-view .doc-render").innerHTML = ""
section = "code"
for t in @project.tags
if t.indexOf("sprite")>=0
section = "sprites"
else if t.indexOf("tutorial")>=0 or t.indexOf("tutoriel")>=0
section = "doc"
if @project.type == "tutorial"
section = "doc"
@setSection(section)
@sources = {}
@selected_source = null
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "ms"
},(msg)=>
@setSourceList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sprites"
},(msg)=>
@setSpriteList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "sounds"
},(msg)=>
@setSoundList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "music"
},(msg)=>
@setMusicList msg.files
#@PI:EMAIL:<EMAIL>END_PI.sendRequest {
# name: "list_public_project_files"
# project: @project.id
# folder: "maps"
#},(msg)=>
# @setMapList msg.files
@app.client.sendRequest {
name: "list_public_project_files"
project: @project.id
folder: "doc"
},(msg)=>
@setDocList msg.files
@updateComments()
@updateCredentials()
a = document.querySelector("#project-contents-view .sprites .export-panel a")
a.href = "/#{@project.owner}/#{@project.slug}/export/sprites/"
a.download = "#{@project.slug}_sprites.zip"
updateCredentials:()->
if @app.user?
document.getElementById("login-to-post-comment").style.display = "none"
if @app.user.flags.validated
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "block"
else
document.getElementById("validate-to-post-comment").style.display = "inline-block"
document.getElementById("post-project-comment").style.display = "none"
else
document.getElementById("login-to-post-comment").style.display = "inline-block"
document.getElementById("validate-to-post-comment").style.display = "none"
document.getElementById("post-project-comment").style.display = "none"
loadFile:(url,callback)->
req = new XMLHttpRequest()
req.onreadystatechange = (event) =>
if req.readyState == XMLHttpRequest.DONE
if req.status == 200
callback(req.responseText)
req.open "GET",url
req.send()
setSection:(section)->
for s in @menu
if s == section
document.getElementById("project-contents-menu-#{s}").classList.add "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "block"
else
document.getElementById("project-contents-menu-#{s}").classList.remove "selected"
document.querySelector("#project-contents-view .#{s}").style.display = "none"
return
createSourceEntry:(file)->
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "ms/#{file}"
},(msg)=>
@sources[file] = msg.content
div = document.createElement "div"
div.innerHTML = "<i class='fa fa-file'></i> #{file.split(".")[0]}"
document.querySelector("#project-contents-view .code-list").appendChild div
div.id = "project-contents-view-source-#{file}"
div.addEventListener "click",()=>@setSelectedSource(file)
if not @selected_source?
@setSelectedSource(file)
setSelectedSource:(file)->
@selected_source = file
for key of @sources
if key == file
document.getElementById("project-contents-view-source-#{key}").classList.add "selected"
else
document.getElementById("project-contents-view-source-#{key}").classList.remove "selected"
@editor.setValue @sources[file],-1
return if not @app.project?
if @imported_sources[file]
document.querySelector("#project-contents-source-import").classList.add "done"
document.querySelector("#project-contents-source-import i").classList.remove "fa-download"
document.querySelector("#project-contents-source-import i").classList.add "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Source file imported")
else
document.querySelector("#project-contents-source-import").classList.remove "done"
document.querySelector("#project-contents-source-import i").classList.add "fa-download"
document.querySelector("#project-contents-source-import i").classList.remove "fa-check"
document.querySelector("#project-contents-source-import span").innerText = @app.translator.get("Import source file to")+" "+@app.project.title
setSourceList:(files)->
for f in files
@createSourceEntry(f.file)
return
createSpriteBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "sprite"
img = @createSpriteThumb(new Sprite(location.origin+"/#{@project.owner}/#{@project.slug}/#{file}",null,prefs))
div.appendChild img
if @app.project?
button = document.createElement "div"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-download"
button.appendChild i
span = document.createElement "span"
span.innerText = @app.translator.get("Import to project")+" #{@app.project.title}"
button.appendChild span
clicked = false
button.addEventListener "click",()=>
return if clicked
clicked = true
source = new Image
source.crossOrigin = "Anonymous"
source.src = location.origin+"/#{@project.owner}/#{@project.slug}/#{file}"
source.onload = ()=>
canvas = document.createElement "canvas"
canvas.width = source.width
canvas.height = source.height
canvas.getContext("2d").drawImage source,0,0
name = file.split(".")[0]
count = 1
while @app.project.getSprite(name)?
count += 1
name = file.split(".")[0]+count
file = name+".png"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{file}"
content: canvas.toDataURL().split(",")[1]
properties: prefs
},(msg)=>
@app.project.updateSpriteList()
div.style.width = "0px"
setTimeout (()=>div.style.display = "none"),1000
div.appendChild button
document.querySelector("#project-contents-view .sprite-list").appendChild div
createSpriteThumb:(sprite)->
canvas = document.createElement "canvas"
canvas.width = 100
canvas.height = 100
sprite.loaded = ()=>
context = canvas.getContext "2d"
frame = sprite.frames[0].getCanvas()
r = Math.min(100/frame.width,100/frame.height)
context.imageSmoothingEnabled = false
w = r*frame.width
h = r*frame.height
context.drawImage frame,50-w/2,50-h/2,w,h
mouseover = false
update = ()=>
if mouseover and sprite.frames.length>1
requestAnimationFrame ()=>update()
return if sprite.frames.length<1
dt = 1000/sprite.fps
t = Date.now()
frame = if mouseover then Math.floor(t/dt)%sprite.frames.length else 0
context = canvas.getContext "2d"
context.imageSmoothingEnabled = false
context.clearRect 0,0,100,100
frame = sprite.frames[frame].getCanvas()
r = Math.min(100/frame.width,100/frame.height)
w = r*frame.width
h = r*frame.height
context.drawImage frame,50-w/2,50-h/2,w,h
canvas.addEventListener "mouseenter",()=>
mouseover = true
update()
canvas.addEventListener "mouseout",()=>
mouseover = false
canvas.updateSprite = update
canvas
setSpriteList:(files)->
for f in files
@createSpriteBox(f.file,f.properties)
return
createImportButton:(div,file,folder)->
button = document.createElement "div"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-download"
button.appendChild i
span = document.createElement "span"
span.innerText = @app.translator.get("Import to project")+" #{@app.project.title}"
button.appendChild span
clicked = false
button.addEventListener "click",()=>
return if clicked
clicked = true
source = new Image
source.crossOrigin = "Anonymous"
source.src = location.origin+"/#{@project.owner}/#{@project.slug}/#{file}"
source.onload = ()=>
canvas = document.createElement "canvas"
canvas.width = source.width
canvas.height = source.height
canvas.getContext("2d").drawImage source,0,0
name = file.split(".")[0]
count = 1
while @app.project.getSprite(name)?
count += 1
name = file.split(".")[0]+count
file = name+".png"
@app.client.sendRequest {
name: "write_project_file"
project: @app.project.id
file: "sprites/#{file}"
content: canvas.toDataURL().split(",")[1]
properties: prefs
},(msg)=>
@app.project.updateSpriteList()
div.style.width = "0px"
setTimeout (()=>div.style.display = "none"),1000
createSoundBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "sound"
img = new Image
img.src = location.origin+"/#{@project.owner}/#{@project.slug}/sounds_th/#{file.replace(".wav",".png")}"
div.appendChild img
div.appendChild document.createElement "br"
span = document.createElement "span"
span.innerText = file.split(".")[0]
div.appendChild span
div.addEventListener "click",()=>
url = location.origin+"/#{@project.owner}/#{@project.slug}/sounds/#{file}"
audio = new Audio(url)
audio.play()
funk = ()->
audio.pause()
document.body.removeEventListener "mousedown",funk
document.body.addEventListener "mousedown",funk
# if @app.project?
# createImportButton div
document.querySelector("#project-contents-view .sound-list").appendChild div
setSoundList:(files)->
if files.length>0
document.getElementById("project-contents-menu-sounds").style.display = "block"
else
document.getElementById("project-contents-menu-sounds").style.display = "none"
for f in files
@createSoundBox(f.file)
return
createMusicBox:(file,prefs)->
div = document.createElement "div"
div.classList.add "music"
img = new Image
img.src = location.origin+"/#{@project.owner}/#{@project.slug}/music_th/#{file.replace(".mp3",".png")}"
div.appendChild img
div.appendChild document.createElement "br"
span = document.createElement "span"
span.innerText = file.split(".")[0]
div.appendChild span
div.addEventListener "click",()=>
url = location.origin+"/#{@project.owner}/#{@project.slug}/music/#{file}"
audio = new Audio(url)
audio.play()
funk = ()->
audio.pause()
document.body.removeEventListener "mousedown",funk
document.body.addEventListener "mousedown",funk
# if @app.project?
# createImportButton div
document.querySelector("#project-contents-view .music-list").appendChild div
setMusicList:(files)->
if files.length>0
document.getElementById("project-contents-menu-music").style.display = "block"
else
document.getElementById("project-contents-menu-music").style.display = "none"
for f in files
@createMusicBox(f.file,f.properties)
return
setMapList:(files)->
console.info files
setDocList:(files)->
if files.length>0
document.getElementById("project-contents-menu-doc").style.display = "block"
@app.client.sendRequest {
name: "read_public_project_file"
project: @project.id
file: "doc/#{files[0].file}"
},(msg)=>
@doc = msg.content
if @doc? and @doc.trim().length>0
document.querySelector("#project-contents-view .doc-render").innerHTML = DOMPurify.sanitize marked msg.content
else
document.getElementById("project-contents-menu-doc").style.display = "none"
else
document.getElementById("project-contents-menu-doc").style.display = "none"
#console.info files
updateComments:()->
@app.client.sendRequest {
name: "get_project_comments"
project: @project.id
},(msg)=>
e = document.getElementById("project-comment-list")
e.innerHTML = ""
if msg.comments?
for c in msg.comments
@createCommentBox(c)
return
createCommentBox:(c)->
console.info c
div = document.createElement("div")
div.classList.add "comment"
author = document.createElement("div")
author.classList.add "author"
i = document.createElement("i")
i.classList.add "fa"
i.classList.add "fa-user"
span = document.createElement "span"
span.innerText = c.user
author.appendChild i
author.appendChild span
author = @app.appui.createUserTag(c.user,c.user_info.tier)
time = document.createElement "div"
time.classList.add "time"
t = (Date.now()-c.time)/60000
if t<2
tt = @app.translator.get("now")
else if t<120
tt = @app.translator.get("%NUM% minutes ago").replace("%NUM%",Math.round(t))
else
t /= 60
if t<48
tt = @app.translator.get("%NUM% hours ago").replace("%NUM%",Math.round(t))
else
t/= 24
if t<14
tt = @app.translator.get("%NUM% days ago").replace("%NUM%",Math.round(t))
else if t<30
tt = @app.translator.get("%NUM% weeks ago").replace("%NUM%",Math.round(t/7))
else
tt = new Date(c.time).toLocaleDateString(@app.translator.lang,{ year: 'numeric', month: 'long', day: 'numeric' })
time.innerText = tt
div.appendChild time
div.appendChild author
if @app.user? and (@app.user.nick == c.user or @app.user.flags.admin)
buttons = document.createElement "div"
buttons.classList.add "buttons"
#buttons.appendChild @createButton "edit","Edit","green",()=>
# @editComment c
#buttons.appendChild document.createElement "br"
buttons.appendChild @createButton "trash","Delete","red",()=>
@deleteComment c
div.appendChild buttons
contents = document.createElement "div"
contents.classList.add "contents"
contents.innerHTML = DOMPurify.sanitize marked c.text
div.appendChild contents
clear = document.createElement "div"
clear.style = "clear:both"
div.appendChild clear
document.getElementById("project-comment-list").appendChild div
createButton:(icon,text,color,callback)->
button = document.createElement "div"
button.classList.add "small"+color+"button"
i = document.createElement "i"
i.classList.add "fa"
i.classList.add "fa-#{icon}"
button.appendChild i
span = document.createElement "span"
span.innerText = text
button.appendChild span
button.addEventListener "click",()=>callback()
button
postComment:(text)->
@app.client.sendRequest {
name: "add_project_comment"
project: @project.id
text: text
},(msg)=>
@updateComments()
editComment:(id,text)->
deleteComment:(c)->
if confirm @app.translator.get("Do you really want to delete this comment?")
@app.client.sendRequest {
name: "delete_project_comment"
project: @project.id
id: c.id
},(msg)=>
@updateComments()
|
[
{
"context": "->\n\n\tbeforeEach ->\n\t\t@user =\n\t\t\t_id: @user_id = \"31j2lk21kjl\"\n\t\t@User = \n\t\t\tfindOne:sinon.stub()\n\t\t\tupdate: si",
"end": 377,
"score": 0.8215489387512207,
"start": 367,
"tag": "PASSWORD",
"value": "1j2lk21kjl"
},
{
"context": "p://sl.example.com\"}... | test/unit/coffee/User/UserRegistrationHandlerTests.coffee | dtu-compute/web-sharelatex | 0 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../app/js/Features/User/UserRegistrationHandler'
sinon = require("sinon")
expect = require("chai").expect
describe "UserRegistrationHandler", ->
beforeEach ->
@user =
_id: @user_id = "31j2lk21kjl"
@User =
findOne:sinon.stub()
update: sinon.stub().callsArgWith(2)
@UserCreator =
createNewUser:sinon.stub().callsArgWith(1, null, @user)
@AuthenticationManager =
setUserPassword: sinon.stub().callsArgWith(2)
@NewsLetterManager =
subscribe: sinon.stub().callsArgWith(1)
@EmailHandler =
sendEmail:sinon.stub().callsArgWith(2)
@OneTimeTokenHandler =
getNewToken: sinon.stub()
@handler = SandboxedModule.require modulePath, requires:
"../../models/User": {User:@User}
"./UserCreator": @UserCreator
"../Authentication/AuthenticationManager":@AuthenticationManager
"../Newsletter/NewsletterManager":@NewsLetterManager
"logger-sharelatex": @logger = { log: sinon.stub() }
"crypto": @crypto = {}
"../Email/EmailHandler": @EmailHandler
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler
"../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() }
"settings-sharelatex": @settings = {siteUrl: "http://sl.example.com"}
@passingRequest = {email:"something@email.com", password:"123"}
describe 'validate Register Request', ->
it 'allow working account through', ->
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal true
it 'not allow not valid email through ', ()->
@passingRequest.email = "notemail"
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
it 'not allow no email through ', ->
@passingRequest.email = ""
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
it 'not allow no password through ', ()->
@passingRequest.password= ""
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
describe "registerNewUser", ->
describe "holdingAccount", (done)->
beforeEach ->
@user.holdingAccount = true
@handler._registrationRequestIsValid = sinon.stub().returns true
@User.findOne.callsArgWith(1, null, @user)
it "should not create a new user if there is a holding account there", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.called.should.equal false
done()
it "should set holding account to false", (done)->
@handler.registerNewUser @passingRequest, (err)=>
update = @User.update.args[0]
assert.deepEqual update[0], {_id:@user._id}
assert.deepEqual update[1], {"$set":{holdingAccount:false}}
done()
describe "invalidRequest", ->
it "should not create a new user if the the request is not valid", (done)->
@handler._registrationRequestIsValid = sinon.stub().returns false
@handler.registerNewUser @passingRequest, (err)=>
expect(err).to.exist
@UserCreator.createNewUser.called.should.equal false
done()
it "should return email registered in the error if there is a non holdingAccount there", (done)->
@User.findOne.callsArgWith(1, null, @user = {holdingAccount:false})
@handler.registerNewUser @passingRequest, (err, user)=>
err.should.deep.equal new Error("EmailAlreadyRegistered")
user.should.deep.equal @user
done()
describe "validRequest", ->
beforeEach ->
@handler._registrationRequestIsValid = sinon.stub().returns true
@User.findOne.callsArgWith 1
it "should create a new user", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.calledWith({email:@passingRequest.email, holdingAccount:false, first_name:@passingRequest.first_name, last_name:@passingRequest.last_name}).should.equal true
done()
it 'lower case email', (done)->
@passingRequest.email = "soMe@eMail.cOm"
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.args[0][0].email.should.equal "some@email.com"
done()
it 'trim white space from email', (done)->
@passingRequest.email = " some@email.com "
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.args[0][0].email.should.equal "some@email.com"
done()
it "should set the password", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@AuthenticationManager.setUserPassword.calledWith(@user._id, @passingRequest.password).should.equal true
done()
it "should add the user to the news letter manager", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@NewsLetterManager.subscribe.calledWith(@user).should.equal true
done()
it "should track the registration event", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@AnalyticsManager.recordEvent
.calledWith(@user._id, "user-registered")
.should.equal true
done()
it "should call the ReferalAllocator", (done)->
done()
describe "registerNewUserAndSendActivationEmail", ->
beforeEach ->
@email = "email@example.com"
@crypto.randomBytes = sinon.stub().returns({toString: () => @password = "mock-password"})
@OneTimeTokenHandler.getNewToken.callsArgWith(2, null, @token = "mock-token")
@handler.registerNewUser = sinon.stub()
@callback = sinon.stub()
describe "with a new user", ->
beforeEach ->
@handler.registerNewUser.callsArgWith(1, null, @user)
@handler.registerNewUserAndSendActivationEmail @email, @callback
it "should ask the UserRegistrationHandler to register user", ->
@handler.registerNewUser
.calledWith({
email: @email
password: @password
}).should.equal true
it "should generate a new password reset token", ->
@OneTimeTokenHandler.getNewToken
.calledWith(@user_id, expiresIn: 7 * 24 * 60 * 60)
.should.equal true
it "should send a registered email", ->
@EmailHandler.sendEmail
.calledWith("registered", {
to: @user.email
setNewPasswordUrl: "#{@settings.siteUrl}/user/activate?token=#{@token}&user_id=#{@user_id}"
})
.should.equal true
it "should return the user", ->
@callback
.calledWith(null, @user, "#{@settings.siteUrl}/user/activate?token=#{@token}&user_id=#{@user_id}")
.should.equal true
describe "with a user that already exists", ->
beforeEach ->
@handler.registerNewUser.callsArgWith(1, new Error("EmailAlreadyRegistered"), @user)
@handler.registerNewUserAndSendActivationEmail @email, @callback
it "should still generate a new password token and email", ->
@OneTimeTokenHandler.getNewToken.called.should.equal true
@EmailHandler.sendEmail.called.should.equal true | 206030 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../app/js/Features/User/UserRegistrationHandler'
sinon = require("sinon")
expect = require("chai").expect
describe "UserRegistrationHandler", ->
beforeEach ->
@user =
_id: @user_id = "3<PASSWORD>"
@User =
findOne:sinon.stub()
update: sinon.stub().callsArgWith(2)
@UserCreator =
createNewUser:sinon.stub().callsArgWith(1, null, @user)
@AuthenticationManager =
setUserPassword: sinon.stub().callsArgWith(2)
@NewsLetterManager =
subscribe: sinon.stub().callsArgWith(1)
@EmailHandler =
sendEmail:sinon.stub().callsArgWith(2)
@OneTimeTokenHandler =
getNewToken: sinon.stub()
@handler = SandboxedModule.require modulePath, requires:
"../../models/User": {User:@User}
"./UserCreator": @UserCreator
"../Authentication/AuthenticationManager":@AuthenticationManager
"../Newsletter/NewsletterManager":@NewsLetterManager
"logger-sharelatex": @logger = { log: sinon.stub() }
"crypto": @crypto = {}
"../Email/EmailHandler": @EmailHandler
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler
"../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() }
"settings-sharelatex": @settings = {siteUrl: "http://sl.example.com"}
@passingRequest = {email:"<EMAIL>", password:"<PASSWORD>"}
describe 'validate Register Request', ->
it 'allow working account through', ->
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal true
it 'not allow not valid email through ', ()->
@passingRequest.email = "notemail"
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
it 'not allow no email through ', ->
@passingRequest.email = ""
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
it 'not allow no password through ', ()->
@passingRequest.password= ""
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
describe "registerNewUser", ->
describe "holdingAccount", (done)->
beforeEach ->
@user.holdingAccount = true
@handler._registrationRequestIsValid = sinon.stub().returns true
@User.findOne.callsArgWith(1, null, @user)
it "should not create a new user if there is a holding account there", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.called.should.equal false
done()
it "should set holding account to false", (done)->
@handler.registerNewUser @passingRequest, (err)=>
update = @User.update.args[0]
assert.deepEqual update[0], {_id:@user._id}
assert.deepEqual update[1], {"$set":{holdingAccount:false}}
done()
describe "invalidRequest", ->
it "should not create a new user if the the request is not valid", (done)->
@handler._registrationRequestIsValid = sinon.stub().returns false
@handler.registerNewUser @passingRequest, (err)=>
expect(err).to.exist
@UserCreator.createNewUser.called.should.equal false
done()
it "should return email registered in the error if there is a non holdingAccount there", (done)->
@User.findOne.callsArgWith(1, null, @user = {holdingAccount:false})
@handler.registerNewUser @passingRequest, (err, user)=>
err.should.deep.equal new Error("EmailAlreadyRegistered")
user.should.deep.equal @user
done()
describe "validRequest", ->
beforeEach ->
@handler._registrationRequestIsValid = sinon.stub().returns true
@User.findOne.callsArgWith 1
it "should create a new user", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.calledWith({email:@passingRequest.email, holdingAccount:false, first_name:@passingRequest.first_name, last_name:@passingRequest.last_name}).should.equal true
done()
it 'lower case email', (done)->
@passingRequest.email = "<EMAIL>"
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.args[0][0].email.should.equal "<EMAIL>"
done()
it 'trim white space from email', (done)->
@passingRequest.email = " <EMAIL> "
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.args[0][0].email.should.equal "<EMAIL>"
done()
it "should set the password", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@AuthenticationManager.setUserPassword.calledWith(@user._id, @passingRequest.password).should.equal true
done()
it "should add the user to the news letter manager", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@NewsLetterManager.subscribe.calledWith(@user).should.equal true
done()
it "should track the registration event", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@AnalyticsManager.recordEvent
.calledWith(@user._id, "user-registered")
.should.equal true
done()
it "should call the ReferalAllocator", (done)->
done()
describe "registerNewUserAndSendActivationEmail", ->
beforeEach ->
@email = "<EMAIL>"
@crypto.randomBytes = sinon.stub().returns({toString: () => @password = "<PASSWORD>"})
@OneTimeTokenHandler.getNewToken.callsArgWith(2, null, @token = "mock-token")
@handler.registerNewUser = sinon.stub()
@callback = sinon.stub()
describe "with a new user", ->
beforeEach ->
@handler.registerNewUser.callsArgWith(1, null, @user)
@handler.registerNewUserAndSendActivationEmail @email, @callback
it "should ask the UserRegistrationHandler to register user", ->
@handler.registerNewUser
.calledWith({
email: @email
password: <PASSWORD>
}).should.equal true
it "should generate a new password reset token", ->
@OneTimeTokenHandler.getNewToken
.calledWith(@user_id, expiresIn: 7 * 24 * 60 * 60)
.should.equal true
it "should send a registered email", ->
@EmailHandler.sendEmail
.calledWith("registered", {
to: @user.email
setNewPasswordUrl: "#{@settings.siteUrl}/user/activate?token=#{@token}&user_id=#{@user_id}"
})
.should.equal true
it "should return the user", ->
@callback
.calledWith(null, @user, "#{@settings.siteUrl}/user/activate?token=#{@token}&user_id=#{@user_id}")
.should.equal true
describe "with a user that already exists", ->
beforeEach ->
@handler.registerNewUser.callsArgWith(1, new Error("EmailAlreadyRegistered"), @user)
@handler.registerNewUserAndSendActivationEmail @email, @callback
it "should still generate a new password token and email", ->
@OneTimeTokenHandler.getNewToken.called.should.equal true
@EmailHandler.sendEmail.called.should.equal true | true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../app/js/Features/User/UserRegistrationHandler'
sinon = require("sinon")
expect = require("chai").expect
describe "UserRegistrationHandler", ->
beforeEach ->
@user =
_id: @user_id = "3PI:PASSWORD:<PASSWORD>END_PI"
@User =
findOne:sinon.stub()
update: sinon.stub().callsArgWith(2)
@UserCreator =
createNewUser:sinon.stub().callsArgWith(1, null, @user)
@AuthenticationManager =
setUserPassword: sinon.stub().callsArgWith(2)
@NewsLetterManager =
subscribe: sinon.stub().callsArgWith(1)
@EmailHandler =
sendEmail:sinon.stub().callsArgWith(2)
@OneTimeTokenHandler =
getNewToken: sinon.stub()
@handler = SandboxedModule.require modulePath, requires:
"../../models/User": {User:@User}
"./UserCreator": @UserCreator
"../Authentication/AuthenticationManager":@AuthenticationManager
"../Newsletter/NewsletterManager":@NewsLetterManager
"logger-sharelatex": @logger = { log: sinon.stub() }
"crypto": @crypto = {}
"../Email/EmailHandler": @EmailHandler
"../Security/OneTimeTokenHandler": @OneTimeTokenHandler
"../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() }
"settings-sharelatex": @settings = {siteUrl: "http://sl.example.com"}
@passingRequest = {email:"PI:EMAIL:<EMAIL>END_PI", password:"PI:PASSWORD:<PASSWORD>END_PI"}
describe 'validate Register Request', ->
it 'allow working account through', ->
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal true
it 'not allow not valid email through ', ()->
@passingRequest.email = "notemail"
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
it 'not allow no email through ', ->
@passingRequest.email = ""
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
it 'not allow no password through ', ()->
@passingRequest.password= ""
result = @handler._registrationRequestIsValid @passingRequest
result.should.equal false
describe "registerNewUser", ->
describe "holdingAccount", (done)->
beforeEach ->
@user.holdingAccount = true
@handler._registrationRequestIsValid = sinon.stub().returns true
@User.findOne.callsArgWith(1, null, @user)
it "should not create a new user if there is a holding account there", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.called.should.equal false
done()
it "should set holding account to false", (done)->
@handler.registerNewUser @passingRequest, (err)=>
update = @User.update.args[0]
assert.deepEqual update[0], {_id:@user._id}
assert.deepEqual update[1], {"$set":{holdingAccount:false}}
done()
describe "invalidRequest", ->
it "should not create a new user if the the request is not valid", (done)->
@handler._registrationRequestIsValid = sinon.stub().returns false
@handler.registerNewUser @passingRequest, (err)=>
expect(err).to.exist
@UserCreator.createNewUser.called.should.equal false
done()
it "should return email registered in the error if there is a non holdingAccount there", (done)->
@User.findOne.callsArgWith(1, null, @user = {holdingAccount:false})
@handler.registerNewUser @passingRequest, (err, user)=>
err.should.deep.equal new Error("EmailAlreadyRegistered")
user.should.deep.equal @user
done()
describe "validRequest", ->
beforeEach ->
@handler._registrationRequestIsValid = sinon.stub().returns true
@User.findOne.callsArgWith 1
it "should create a new user", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.calledWith({email:@passingRequest.email, holdingAccount:false, first_name:@passingRequest.first_name, last_name:@passingRequest.last_name}).should.equal true
done()
it 'lower case email', (done)->
@passingRequest.email = "PI:EMAIL:<EMAIL>END_PI"
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.args[0][0].email.should.equal "PI:EMAIL:<EMAIL>END_PI"
done()
it 'trim white space from email', (done)->
@passingRequest.email = " PI:EMAIL:<EMAIL>END_PI "
@handler.registerNewUser @passingRequest, (err)=>
@UserCreator.createNewUser.args[0][0].email.should.equal "PI:EMAIL:<EMAIL>END_PI"
done()
it "should set the password", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@AuthenticationManager.setUserPassword.calledWith(@user._id, @passingRequest.password).should.equal true
done()
it "should add the user to the news letter manager", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@NewsLetterManager.subscribe.calledWith(@user).should.equal true
done()
it "should track the registration event", (done)->
@handler.registerNewUser @passingRequest, (err)=>
@AnalyticsManager.recordEvent
.calledWith(@user._id, "user-registered")
.should.equal true
done()
it "should call the ReferalAllocator", (done)->
done()
describe "registerNewUserAndSendActivationEmail", ->
beforeEach ->
@email = "PI:EMAIL:<EMAIL>END_PI"
@crypto.randomBytes = sinon.stub().returns({toString: () => @password = "PI:PASSWORD:<PASSWORD>END_PI"})
@OneTimeTokenHandler.getNewToken.callsArgWith(2, null, @token = "mock-token")
@handler.registerNewUser = sinon.stub()
@callback = sinon.stub()
describe "with a new user", ->
beforeEach ->
@handler.registerNewUser.callsArgWith(1, null, @user)
@handler.registerNewUserAndSendActivationEmail @email, @callback
it "should ask the UserRegistrationHandler to register user", ->
@handler.registerNewUser
.calledWith({
email: @email
password: PI:PASSWORD:<PASSWORD>END_PI
}).should.equal true
it "should generate a new password reset token", ->
@OneTimeTokenHandler.getNewToken
.calledWith(@user_id, expiresIn: 7 * 24 * 60 * 60)
.should.equal true
it "should send a registered email", ->
@EmailHandler.sendEmail
.calledWith("registered", {
to: @user.email
setNewPasswordUrl: "#{@settings.siteUrl}/user/activate?token=#{@token}&user_id=#{@user_id}"
})
.should.equal true
it "should return the user", ->
@callback
.calledWith(null, @user, "#{@settings.siteUrl}/user/activate?token=#{@token}&user_id=#{@user_id}")
.should.equal true
describe "with a user that already exists", ->
beforeEach ->
@handler.registerNewUser.callsArgWith(1, new Error("EmailAlreadyRegistered"), @user)
@handler.registerNewUserAndSendActivationEmail @email, @callback
it "should still generate a new password token and email", ->
@OneTimeTokenHandler.getNewToken.called.should.equal true
@EmailHandler.sendEmail.called.should.equal true |
[
{
"context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ",
"end": 194,
"score": 0.9999220967292786,
"start": 178,
"tag": "EMAIL",
"value": "info@chaibio.com"
}
] | frontend/javascripts/app/directives/test_in_progress.js.coffee | MakerButt/chaipcr | 1 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>
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.
###
window.ChaiBioTech.ngApp
.directive 'testInProgress', [
'Status'
'$interval'
'Experiment'
'AmplificationChartHelper'
'TestInProgressHelper'
(Status, $interval, Experiment, AmplificationChartHelper, TestInProgressHelper) ->
restrict: 'EA'
scope:
experimentId: '='
replace: true
templateUrl: 'app/views/directives/test-in-progress.html'
link: ($scope, elem) ->
$scope.completionStatus = null
$scope.is_holding = false
updateIsHolding = (data) ->
$scope.is_holding = TestInProgressHelper.set_holding(data, $scope.experiment)
updateData = (data) ->
if (!$scope.completionStatus and (data?.experiment_controller?.machine.state is 'idle' or data?.experiment_controller?.machine.state is 'complete') or !$scope.experiment) and $scope.experimentId
Experiment.get(id: $scope.experimentId).then (resp) ->
$scope.data = data
$scope.completionStatus = resp.experiment.completion_status
$scope.experiment = resp.experiment
else
$scope.data = data
if Status.getData() then updateData Status.getData()
$scope.$on 'status:data:updated', (e, data) ->
updateData data
updateIsHolding data
$scope.timeRemaining = TestInProgressHelper.timeRemaining(data)
$scope.barWidth = ->
if $scope.data and $scope.data.experiment_controller.machine.state is 'running'
exp = $scope.data.experiment_controller.experiment
width = exp.run_duration/exp.estimated_duration
if width > 1 then width = 1
width
else
0
] | 50335 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>>
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.
###
window.ChaiBioTech.ngApp
.directive 'testInProgress', [
'Status'
'$interval'
'Experiment'
'AmplificationChartHelper'
'TestInProgressHelper'
(Status, $interval, Experiment, AmplificationChartHelper, TestInProgressHelper) ->
restrict: 'EA'
scope:
experimentId: '='
replace: true
templateUrl: 'app/views/directives/test-in-progress.html'
link: ($scope, elem) ->
$scope.completionStatus = null
$scope.is_holding = false
updateIsHolding = (data) ->
$scope.is_holding = TestInProgressHelper.set_holding(data, $scope.experiment)
updateData = (data) ->
if (!$scope.completionStatus and (data?.experiment_controller?.machine.state is 'idle' or data?.experiment_controller?.machine.state is 'complete') or !$scope.experiment) and $scope.experimentId
Experiment.get(id: $scope.experimentId).then (resp) ->
$scope.data = data
$scope.completionStatus = resp.experiment.completion_status
$scope.experiment = resp.experiment
else
$scope.data = data
if Status.getData() then updateData Status.getData()
$scope.$on 'status:data:updated', (e, data) ->
updateData data
updateIsHolding data
$scope.timeRemaining = TestInProgressHelper.timeRemaining(data)
$scope.barWidth = ->
if $scope.data and $scope.data.experiment_controller.machine.state is 'running'
exp = $scope.data.experiment_controller.experiment
width = exp.run_duration/exp.estimated_duration
if width > 1 then width = 1
width
else
0
] | true | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>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.
###
window.ChaiBioTech.ngApp
.directive 'testInProgress', [
'Status'
'$interval'
'Experiment'
'AmplificationChartHelper'
'TestInProgressHelper'
(Status, $interval, Experiment, AmplificationChartHelper, TestInProgressHelper) ->
restrict: 'EA'
scope:
experimentId: '='
replace: true
templateUrl: 'app/views/directives/test-in-progress.html'
link: ($scope, elem) ->
$scope.completionStatus = null
$scope.is_holding = false
updateIsHolding = (data) ->
$scope.is_holding = TestInProgressHelper.set_holding(data, $scope.experiment)
updateData = (data) ->
if (!$scope.completionStatus and (data?.experiment_controller?.machine.state is 'idle' or data?.experiment_controller?.machine.state is 'complete') or !$scope.experiment) and $scope.experimentId
Experiment.get(id: $scope.experimentId).then (resp) ->
$scope.data = data
$scope.completionStatus = resp.experiment.completion_status
$scope.experiment = resp.experiment
else
$scope.data = data
if Status.getData() then updateData Status.getData()
$scope.$on 'status:data:updated', (e, data) ->
updateData data
updateIsHolding data
$scope.timeRemaining = TestInProgressHelper.timeRemaining(data)
$scope.barWidth = ->
if $scope.data and $scope.data.experiment_controller.machine.state is 'running'
exp = $scope.data.experiment_controller.experiment
width = exp.run_duration/exp.estimated_duration
if width > 1 then width = 1
width
else
0
] |
[
{
"context": "warn` by default.\n '''\n\n tokens: [ 'DEBUGGER', 'IDENTIFIER' ]\n\n lintToken: (token, tokenApi",
"end": 340,
"score": 0.7553045749664307,
"start": 332,
"tag": "KEY",
"value": "DEBUGGER"
}
] | src/rules/no_debugger.coffee | AsaAyers/coffeelint | 0 |
module.exports = class NoDebugger
rule:
name: 'no_debugger'
level: 'warn'
message: 'Found debugging code'
console: false
description: '''
This rule detects `debugger` and optionally `console` calls
This rule is `warn` by default.
'''
tokens: [ 'DEBUGGER', 'IDENTIFIER' ]
lintToken: (token, tokenApi) ->
if token[0] is 'DEBUGGER'
return { context: "found '#{token[0]}'" }
if tokenApi.config[@rule.name]?.console
if token[1] is 'console' and tokenApi.peek(1)?[0] is '.'
method = tokenApi.peek(2)
return { context: "found 'console.#{method[1]}'" }
| 40984 |
module.exports = class NoDebugger
rule:
name: 'no_debugger'
level: 'warn'
message: 'Found debugging code'
console: false
description: '''
This rule detects `debugger` and optionally `console` calls
This rule is `warn` by default.
'''
tokens: [ '<KEY>', 'IDENTIFIER' ]
lintToken: (token, tokenApi) ->
if token[0] is 'DEBUGGER'
return { context: "found '#{token[0]}'" }
if tokenApi.config[@rule.name]?.console
if token[1] is 'console' and tokenApi.peek(1)?[0] is '.'
method = tokenApi.peek(2)
return { context: "found 'console.#{method[1]}'" }
| true |
module.exports = class NoDebugger
rule:
name: 'no_debugger'
level: 'warn'
message: 'Found debugging code'
console: false
description: '''
This rule detects `debugger` and optionally `console` calls
This rule is `warn` by default.
'''
tokens: [ 'PI:KEY:<KEY>END_PI', 'IDENTIFIER' ]
lintToken: (token, tokenApi) ->
if token[0] is 'DEBUGGER'
return { context: "found '#{token[0]}'" }
if tokenApi.config[@rule.name]?.console
if token[1] is 'console' and tokenApi.peek(1)?[0] is '.'
method = tokenApi.peek(2)
return { context: "found 'console.#{method[1]}'" }
|
[
{
"context": "ntity is created'\n\t@test.assertEquals km.apiKey, 'abc123', 'API key is set correctly'\n\ncasper.then ->\n\tins",
"end": 520,
"score": 0.9972469806671143,
"start": 514,
"tag": "KEY",
"value": "abc123"
},
{
"context": "valuate ->\n\t\tnew window.AnonKissmetricsClient 'a... | test/casperjs/kissmetrics-anon.coffee | evansolomon/kissmetrics-js | 1 | # The page doesn't actually matter
casper.start 'http://localhost:9000/index.html'
casper.then ->
# Injections are relative to the project root
casper.page.injectJs 'min/kissmetrics.min.js'
# Existance
casper.then ->
KM = @evaluate ->
!! window.AnonKissmetricsClient
@test.assertTruthy KM, 'AnonKissmetricsClient exists'
# Instantiation
casper.then ->
km = @evaluate ->
new window.AnonKissmetricsClient 'abc123'
@test.assertTruthy km.person, 'Identity is created'
@test.assertEquals km.apiKey, 'abc123', 'API key is set correctly'
casper.then ->
instanceOfKM = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km instanceof AnonKissmetricsClient
@test.assertTruthy instanceOfKM, 'km is instance of AnonKissmetricsClient'
# Auto-identifier storage
casper.then ->
ID = @evaluate ->
new window.AnonKissmetricsClient 'abc123'
window.localStorage.getItem 'kissmetricsAnon'
@test.assertTruthy ID, 'ID is stored in localStorage'
casper.then ->
ID = @evaluate ->
new window.AnonKissmetricsClient 'abc123', {storageKey: 'customKey'}
window.localStorage.getItem 'customKey'
@test.assertTruthy ID, 'ID is stored in localStorage with custom storage key'
casper.then ->
data = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
{cookies: document.cookie, person: km.person}
matchString = "kissmetricsAnon=#{data.person}"
@test.assertTruthy data.cookies.match matchString, 'Cookie is saved'
casper.then ->
data = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'cookie'
storageKey: 'somethingCustom'
{cookies: document.cookie, person: km.person}
matchString = "somethingCustom=#{data.person}"
@test.assertTruthy data.cookies.match matchString, 'Cookie is saved with custom storage key'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in cookies'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'cookie'
storageKey: 'somethingCustom'
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'cookie'
storageKey: 'somethingCustom'
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in cookies with custom storage key'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'localStorage'}
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'localStorage'}
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in localStorage'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'localStorage'
storageKey: 'customKey'
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'localStorage'
storageKey: 'customKey'
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in localStorage with custom storage key'
# Record
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123', 'evan'
{person: km.person, query: km.record('event name').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/e?_n=event%20name&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Records event'
# Set
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.set({place: 'home'}).queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/s?place=home&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Sets properties'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.set({place: 'home', foo: 'bar'}).queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/s?place=home&foo=bar&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Sets multiple properties'
# Alias
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.alias('notevan').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/a?_n=notevan&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Alias person'
casper.then ->
km = @evaluate ->
km = new AnonKissmetricsClient 'abc123', 'evan'
km.alias 'notevan'
@test.assertEquals km.person, 'notevan', 'Updates person attribute'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.alias 'username'
km._storage.get()
@test.assertFalsy data, 'Logged out ID is deleted by alias'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.alias 'username', false
km._storage.get()
@test.assertTruthy data, 'Logged out ID is retained by alias with the `false` argument'
# # Client API
casper.then ->
ownInstance = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.record('event name') instanceof AnonKissmetricsClient
@test.assertTruthy ownInstance, 'AnonKissmetricsClient returns its own instance'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.record('event name').record('other event name').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/e?_n=other%20event%20name&_k=ab&_p=#{data.person}"
@test.assertTruthy data.query, 'Runs multiple queries when chained'
casper.then ->
lastQuery = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
delete km.apiKey
km.record('event name').queries.pop()
@test.assertFalsy lastQuery, 'Requires API key'
casper.then ->
lastQuery = @evaluate ->
km = new AnonKissmetricsClient
delete km.person
km.record('event name').queries.pop()
@test.assertFalsy lastQuery, 'Requires Person'
casper.run ->
@test.done()
| 183397 | # The page doesn't actually matter
casper.start 'http://localhost:9000/index.html'
casper.then ->
# Injections are relative to the project root
casper.page.injectJs 'min/kissmetrics.min.js'
# Existance
casper.then ->
KM = @evaluate ->
!! window.AnonKissmetricsClient
@test.assertTruthy KM, 'AnonKissmetricsClient exists'
# Instantiation
casper.then ->
km = @evaluate ->
new window.AnonKissmetricsClient 'abc123'
@test.assertTruthy km.person, 'Identity is created'
@test.assertEquals km.apiKey, '<KEY>', 'API key is set correctly'
casper.then ->
instanceOfKM = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km instanceof AnonKissmetricsClient
@test.assertTruthy instanceOfKM, 'km is instance of AnonKissmetricsClient'
# Auto-identifier storage
casper.then ->
ID = @evaluate ->
new window.AnonKissmetricsClient 'abc123'
window.localStorage.getItem 'kissmetricsAnon'
@test.assertTruthy ID, 'ID is stored in localStorage'
casper.then ->
ID = @evaluate ->
new window.AnonKissmetricsClient 'abc<KEY>23', {storageKey: 'customKey'}
window.localStorage.getItem 'customKey'
@test.assertTruthy ID, 'ID is stored in localStorage with custom storage key'
casper.then ->
data = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
{cookies: document.cookie, person: km.person}
matchString = "kissmetricsAnon=#{data.person}"
@test.assertTruthy data.cookies.match matchString, 'Cookie is saved'
casper.then ->
data = @evaluate ->
km = new window.AnonKissmetricsClient 'abc<KEY>23',
storage: 'cookie'
storageKey: '<KEY>'
{cookies: document.cookie, person: km.person}
matchString = "somethingCustom=#{data.person}"
@test.assertTruthy data.cookies.match matchString, 'Cookie is saved with custom storage key'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in cookies'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'cookie'
storageKey: 'something<KEY>'
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'cookie'
storageKey: '<KEY>'
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in cookies with custom storage key'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'localStorage'}
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'localStorage'}
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in localStorage'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'localStorage'
storageKey: 'customKey'
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'localStorage'
storageKey: 'customKey'
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in localStorage with custom storage key'
# Record
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123', 'evan'
{person: km.person, query: km.record('event name').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/e?_n=event%20name&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Records event'
# Set
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.set({place: 'home'}).queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/s?place=home&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Sets properties'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.set({place: 'home', foo: 'bar'}).queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/s?place=home&foo=bar&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Sets multiple properties'
# Alias
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.alias('notevan').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/a?_n=notevan&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Alias person'
casper.then ->
km = @evaluate ->
km = new AnonKissmetricsClient 'abc123', '<NAME>'
km.alias 'notevan'
@test.assertEquals km.person, 'not<NAME>', 'Updates person attribute'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.alias 'username'
km._storage.get()
@test.assertFalsy data, 'Logged out ID is deleted by alias'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.alias 'username', false
km._storage.get()
@test.assertTruthy data, 'Logged out ID is retained by alias with the `false` argument'
# # Client API
casper.then ->
ownInstance = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.record('event name') instanceof AnonKissmetricsClient
@test.assertTruthy ownInstance, 'AnonKissmetricsClient returns its own instance'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.record('event name').record('other event name').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/e?_n=other%20event%20name&_k=ab&_p=#{data.person}"
@test.assertTruthy data.query, 'Runs multiple queries when chained'
casper.then ->
lastQuery = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
delete km.apiKey
km.record('event name').queries.pop()
@test.assertFalsy lastQuery, 'Requires API key'
casper.then ->
lastQuery = @evaluate ->
km = new AnonKissmetricsClient
delete km.person
km.record('event name').queries.pop()
@test.assertFalsy lastQuery, 'Requires Person'
casper.run ->
@test.done()
| true | # The page doesn't actually matter
casper.start 'http://localhost:9000/index.html'
casper.then ->
# Injections are relative to the project root
casper.page.injectJs 'min/kissmetrics.min.js'
# Existance
casper.then ->
KM = @evaluate ->
!! window.AnonKissmetricsClient
@test.assertTruthy KM, 'AnonKissmetricsClient exists'
# Instantiation
casper.then ->
km = @evaluate ->
new window.AnonKissmetricsClient 'abc123'
@test.assertTruthy km.person, 'Identity is created'
@test.assertEquals km.apiKey, 'PI:KEY:<KEY>END_PI', 'API key is set correctly'
casper.then ->
instanceOfKM = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km instanceof AnonKissmetricsClient
@test.assertTruthy instanceOfKM, 'km is instance of AnonKissmetricsClient'
# Auto-identifier storage
casper.then ->
ID = @evaluate ->
new window.AnonKissmetricsClient 'abc123'
window.localStorage.getItem 'kissmetricsAnon'
@test.assertTruthy ID, 'ID is stored in localStorage'
casper.then ->
ID = @evaluate ->
new window.AnonKissmetricsClient 'abcPI:KEY:<KEY>END_PI23', {storageKey: 'customKey'}
window.localStorage.getItem 'customKey'
@test.assertTruthy ID, 'ID is stored in localStorage with custom storage key'
casper.then ->
data = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
{cookies: document.cookie, person: km.person}
matchString = "kissmetricsAnon=#{data.person}"
@test.assertTruthy data.cookies.match matchString, 'Cookie is saved'
casper.then ->
data = @evaluate ->
km = new window.AnonKissmetricsClient 'abcPI:KEY:<KEY>END_PI23',
storage: 'cookie'
storageKey: 'PI:KEY:<KEY>END_PI'
{cookies: document.cookie, person: km.person}
matchString = "somethingCustom=#{data.person}"
@test.assertTruthy data.cookies.match matchString, 'Cookie is saved with custom storage key'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'cookie'}
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in cookies'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'cookie'
storageKey: 'somethingPI:KEY:<KEY>END_PI'
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'cookie'
storageKey: 'PI:KEY:<KEY>END_PI'
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in cookies with custom storage key'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'localStorage'}
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123', {storage: 'localStorage'}
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in localStorage'
casper.then ->
originalPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'localStorage'
storageKey: 'customKey'
km.person
newPerson = @evaluate ->
km = new window.AnonKissmetricsClient 'abc123',
storage: 'localStorage'
storageKey: 'customKey'
km.person
@test.assertEquals originalPerson, newPerson, 'Person is persistent in localStorage with custom storage key'
# Record
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123', 'evan'
{person: km.person, query: km.record('event name').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/e?_n=event%20name&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Records event'
# Set
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.set({place: 'home'}).queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/s?place=home&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Sets properties'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.set({place: 'home', foo: 'bar'}).queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/s?place=home&foo=bar&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Sets multiple properties'
# Alias
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.alias('notevan').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/a?_n=notevan&_k=abc123&_p=#{data.person}"
@test.assertEquals data.query, exepectedQuery, 'Alias person'
casper.then ->
km = @evaluate ->
km = new AnonKissmetricsClient 'abc123', 'PI:NAME:<NAME>END_PI'
km.alias 'notevan'
@test.assertEquals km.person, 'notPI:NAME:<NAME>END_PI', 'Updates person attribute'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.alias 'username'
km._storage.get()
@test.assertFalsy data, 'Logged out ID is deleted by alias'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.alias 'username', false
km._storage.get()
@test.assertTruthy data, 'Logged out ID is retained by alias with the `false` argument'
# # Client API
casper.then ->
ownInstance = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
km.record('event name') instanceof AnonKissmetricsClient
@test.assertTruthy ownInstance, 'AnonKissmetricsClient returns its own instance'
casper.then ->
data = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
{person: km.person, query: km.record('event name').record('other event name').queries.pop()}
exepectedQuery = "https://trk.kissmetrics.com/e?_n=other%20event%20name&_k=ab&_p=#{data.person}"
@test.assertTruthy data.query, 'Runs multiple queries when chained'
casper.then ->
lastQuery = @evaluate ->
km = new AnonKissmetricsClient 'abc123'
delete km.apiKey
km.record('event name').queries.pop()
@test.assertFalsy lastQuery, 'Requires API key'
casper.then ->
lastQuery = @evaluate ->
km = new AnonKissmetricsClient
delete km.person
km.record('event name').queries.pop()
@test.assertFalsy lastQuery, 'Requires Person'
casper.run ->
@test.done()
|
[
{
"context": "#!/usr/bin/env coffee\n# copyright 2015, r. brian harrison. all rights reserved.\n\n# TODO opt",
"end": 41,
"score": 0.9940812587738037,
"start": 40,
"tag": "NAME",
"value": "r"
},
{
"context": "#!/usr/bin/env coffee\n# copyright 2015, r. brian harrison. all rights re... | web.coffee | idiomatic/twittersurvey | 0 | #!/usr/bin/env coffee
# copyright 2015, r. brian harrison. all rights reserved.
# TODO optimize CSV generation
os = require 'os'
util = require 'util'
koa = require 'koa'
route = require 'koa-route'
#koaStatic = require 'koa-static'
co = require 'co'
redis = require 'redis'
coRedis = require 'co-redis'
wait = require 'co-wait'
csv = require 'fast-csv'
survey = require './twitter'
port = process.env.PORT ? 3002
createRedisClient = ->
return coRedis(redis.createClient(process.env.REDIS_URL))
dictify = (a) ->
# [k, v, k2, v2, ... ] -> {k: v, k2: v, ...}
d = {}
for v, i in a
if i % 2 is 1
d[a[i - 1]] = v
return d
commatize = (n) ->
fractionIndex = (n or 0).toString().lastIndexOf('.')
fraction = ''
if fractionIndex > -1
fraction = n.toString().substr(fractionIndex)
if n >= 1000
commatize(Math.floor(n / 1000)) + ',' + Math.floor(n).toString().substr(-3) + fraction
else
n
start = ->
surveyer = new survey.Surveyer()
app = koa()
app.use route.get '/', (next) ->
stats = yield surveyer.stats()
@body = """
<!DOCTYPE html>
<html>
<head>
<title>Twitter Influencer Survey</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/mohsen1/json-formatter-js/master/dist/style.css" />
<style>
body {font-family: Sans-Serif;}
#{if stats.paused then "body {background-color:#fff9f9;}" else ""}
th, td {text-align: right; padding: 0.5em;}
th:first-child {text-align: left;}
table {border-collapse: collapse;}
table, td, th {border: 1px solid black;}
th.trivia, td.trivia {border: 1px solid #eee; color:#eee;}
th.trivia *, td.trivia * {color:#eee;}
.explain {font-size: x-small; color:#ccc;}
h1 {color:#f00;}
</style>
</head>
<body>
#{if stats.paused then "<h1>paused</h1>" else ""}
<h2>Statistics</h2>
<table>
<tr>
<th></th>
<th>processed</th>
<th>unique discovered</th>
<th>
queue
<div class="explain">Backlog</div>
</th>
<th class="trivia">
discarded
<div class="explain">Memory pressure</div>
</th>
</tr>
<tr>
<th>Users
<div class="explain">
Twitter users
</div>
</th>
<td>#{commatize stats.user.popped or 0}</td>
<td>#{if stats.user.discarded then "≥ " else ""}#{commatize stats.user.pushed or 0}</td>
<td rowspan=2>#{if stats.user.discarded then "≥ " else ""}#{commatize stats.user.queue or 0}</td>
<td class="trivia">#{commatize stats.user.discarded or 0}</td>
</tr>
<tr>
<th>Influencers
<div class="explain">
Twitter users with 5,000 followers or more
</div>
<div>
<a href="/influencers.csv">download all</a> or
<a href="/influencers.csv?offset=0&count=5000">top #{commatize Math.min(5000, stats.influencers)}</a>
<a href="/influencers.csv?offset=0&count=5000&hasemail=1">with email</a>
</div>
</th>
<td colspan=2>#{commatize stats.influencers}</td>
<td class="trivia">0</td>
</tr>
<tr>
<th>Influencer Followers
<div class="explain">
Influencers with followers<br/>
About to (slowly) fetch the first 5,000 followers
</div>
</th>
<td>#{commatize stats.followers.popped or 0}</td>
<td>#{if stats.followers.discarded then "≥ " else ""}#{commatize stats.followers.pushed or 0}</td>
<td>#{if stats.followers.discarded then "≥ " else ""}#{commatize stats.followers.queue or 0}</td>
<td class="trivia">#{commatize stats.followers.discarded or 0}</td>
</tr>
<tr>
<th>Influencer Follower Friends
<div class="explain">
Users that follow others<br/>
About to (slowly) fetch the first 5,000 users they follow
</div>
</th>
<td>#{commatize stats.friends.popped or 0}</td>
<td>#{if stats.friends.discarded then "≥ " else ""}#{commatize stats.friends.pushed or 0}</td>
<td>#{if stats.friends.discarded then "≥ " else ""}#{commatize stats.friends.queue or 0}</td>
<td class="trivia">#{commatize stats.friends.discarded or 0}</td>
</tr>
</table>
<h2>Latest Influencer</h2>
<p>
<a href="https://twitter.com/#{stats.lastInfluencer.screen_name}">#{stats.lastInfluencer.name}</a>
</p>
<script src="https://cdn.rawgit.com/mohsen1/json-formatter-js/master/dist/bundle.js"></script>
<script>
var lastInfluencer = #{JSON.stringify(stats.lastInfluencer)};
var formatter = new JSONFormatter(lastInfluencer);
document.body.appendChild(formatter.render())
</script>
</body>
</html>
"""
app.use route.get '/stats', (next) ->
@body = yield surveyer.stats()
app.use route.get '/influencers.csv', (next) ->
redisClient = createRedisClient()
s = csv.createWriteStream()
@body = s
@type = 'text/csv'
@attachment()
s.write(['screen_name', 'followers_count', 'name', 'description', 'location', 'url', 'email_address'])
{offset, count, hasemail} = @query
influencers = null
if offset? or count?
# lazily avoid this ZSET if downloading all
offset ?= 0
count ?= -1
# TODO redis via Surveyer
influencers = yield redisClient.zrevrangebyscore('influence', '+inf', 5000, 'withscores', 'limit', offset, count)
influencers = dictify(influencers)
# HACK proceed in parallel to sending HTTP headers
co (cb) ->
# HACK x@y.z is valid, but x@gmail and "x at gmail dot com" are not
email_re = /\S+@\S+\.\S+/
# HACK fetch everything and filter here
cursor = '0'
loop
[cursor, influencersChunk] = yield redisClient.hscan('influencers', cursor, 'COUNT', 100)
for screen_name, influencer of dictify(influencersChunk)
{name, followers_count, description, location, url} = JSON.parse(influencer)
continue if influencers? and not influencers[screen_name]
description = description.replace(/\r/g, '\n')
email_address = email_re.exec(description)?[0]
continue if hasemail? and not email_address
s.write([screen_name, followers_count, name, description, location, url, email_address])
break if cursor is '0'
yield wait(10)
s.end()
redisClient.quit()
cb?()
.catch (err) ->
# TODO propagate
console.error err.stack
app.use route.get '/memory', (next) ->
@body = process.memoryUsage()
yield return
app.use route.get '/loadavg', (next) ->
@body = os.loadavg()
yield return
app.listen(port)
if require.main is module
co(start).catch (err) ->
console.error err.stack
module.exports = {start}
| 200987 | #!/usr/bin/env coffee
# copyright 2015, <NAME>. <NAME>. all rights reserved.
# TODO optimize CSV generation
os = require 'os'
util = require 'util'
koa = require 'koa'
route = require 'koa-route'
#koaStatic = require 'koa-static'
co = require 'co'
redis = require 'redis'
coRedis = require 'co-redis'
wait = require 'co-wait'
csv = require 'fast-csv'
survey = require './twitter'
port = process.env.PORT ? 3002
createRedisClient = ->
return coRedis(redis.createClient(process.env.REDIS_URL))
dictify = (a) ->
# [k, v, k2, v2, ... ] -> {k: v, k2: v, ...}
d = {}
for v, i in a
if i % 2 is 1
d[a[i - 1]] = v
return d
commatize = (n) ->
fractionIndex = (n or 0).toString().lastIndexOf('.')
fraction = ''
if fractionIndex > -1
fraction = n.toString().substr(fractionIndex)
if n >= 1000
commatize(Math.floor(n / 1000)) + ',' + Math.floor(n).toString().substr(-3) + fraction
else
n
start = ->
surveyer = new survey.Surveyer()
app = koa()
app.use route.get '/', (next) ->
stats = yield surveyer.stats()
@body = """
<!DOCTYPE html>
<html>
<head>
<title>Twitter Influencer Survey</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/mohsen1/json-formatter-js/master/dist/style.css" />
<style>
body {font-family: Sans-Serif;}
#{if stats.paused then "body {background-color:#fff9f9;}" else ""}
th, td {text-align: right; padding: 0.5em;}
th:first-child {text-align: left;}
table {border-collapse: collapse;}
table, td, th {border: 1px solid black;}
th.trivia, td.trivia {border: 1px solid #eee; color:#eee;}
th.trivia *, td.trivia * {color:#eee;}
.explain {font-size: x-small; color:#ccc;}
h1 {color:#f00;}
</style>
</head>
<body>
#{if stats.paused then "<h1>paused</h1>" else ""}
<h2>Statistics</h2>
<table>
<tr>
<th></th>
<th>processed</th>
<th>unique discovered</th>
<th>
queue
<div class="explain">Backlog</div>
</th>
<th class="trivia">
discarded
<div class="explain">Memory pressure</div>
</th>
</tr>
<tr>
<th>Users
<div class="explain">
Twitter users
</div>
</th>
<td>#{commatize stats.user.popped or 0}</td>
<td>#{if stats.user.discarded then "≥ " else ""}#{commatize stats.user.pushed or 0}</td>
<td rowspan=2>#{if stats.user.discarded then "≥ " else ""}#{commatize stats.user.queue or 0}</td>
<td class="trivia">#{commatize stats.user.discarded or 0}</td>
</tr>
<tr>
<th>Influencers
<div class="explain">
Twitter users with 5,000 followers or more
</div>
<div>
<a href="/influencers.csv">download all</a> or
<a href="/influencers.csv?offset=0&count=5000">top #{commatize Math.min(5000, stats.influencers)}</a>
<a href="/influencers.csv?offset=0&count=5000&hasemail=1">with email</a>
</div>
</th>
<td colspan=2>#{commatize stats.influencers}</td>
<td class="trivia">0</td>
</tr>
<tr>
<th>Influencer Followers
<div class="explain">
Influencers with followers<br/>
About to (slowly) fetch the first 5,000 followers
</div>
</th>
<td>#{commatize stats.followers.popped or 0}</td>
<td>#{if stats.followers.discarded then "≥ " else ""}#{commatize stats.followers.pushed or 0}</td>
<td>#{if stats.followers.discarded then "≥ " else ""}#{commatize stats.followers.queue or 0}</td>
<td class="trivia">#{commatize stats.followers.discarded or 0}</td>
</tr>
<tr>
<th>Influencer Follower Friends
<div class="explain">
Users that follow others<br/>
About to (slowly) fetch the first 5,000 users they follow
</div>
</th>
<td>#{commatize stats.friends.popped or 0}</td>
<td>#{if stats.friends.discarded then "≥ " else ""}#{commatize stats.friends.pushed or 0}</td>
<td>#{if stats.friends.discarded then "≥ " else ""}#{commatize stats.friends.queue or 0}</td>
<td class="trivia">#{commatize stats.friends.discarded or 0}</td>
</tr>
</table>
<h2>Latest Influencer</h2>
<p>
<a href="https://twitter.com/#{stats.lastInfluencer.screen_name}">#{stats.lastInfluencer.name}</a>
</p>
<script src="https://cdn.rawgit.com/mohsen1/json-formatter-js/master/dist/bundle.js"></script>
<script>
var lastInfluencer = #{JSON.stringify(stats.lastInfluencer)};
var formatter = new JSONFormatter(lastInfluencer);
document.body.appendChild(formatter.render())
</script>
</body>
</html>
"""
app.use route.get '/stats', (next) ->
@body = yield surveyer.stats()
app.use route.get '/influencers.csv', (next) ->
redisClient = createRedisClient()
s = csv.createWriteStream()
@body = s
@type = 'text/csv'
@attachment()
s.write(['screen_name', 'followers_count', 'name', 'description', 'location', 'url', 'email_address'])
{offset, count, hasemail} = @query
influencers = null
if offset? or count?
# lazily avoid this ZSET if downloading all
offset ?= 0
count ?= -1
# TODO redis via Surveyer
influencers = yield redisClient.zrevrangebyscore('influence', '+inf', 5000, 'withscores', 'limit', offset, count)
influencers = dictify(influencers)
# HACK proceed in parallel to sending HTTP headers
co (cb) ->
# HACK x@y.z is valid, but x@gmail and "x at gmail dot com" are not
email_re = /\S+@\S+\.\S+/
# HACK fetch everything and filter here
cursor = '0'
loop
[cursor, influencersChunk] = yield redisClient.hscan('influencers', cursor, 'COUNT', 100)
for screen_name, influencer of dictify(influencersChunk)
{name, followers_count, description, location, url} = JSON.parse(influencer)
continue if influencers? and not influencers[screen_name]
description = description.replace(/\r/g, '\n')
email_address = email_re.exec(description)?[0]
continue if hasemail? and not email_address
s.write([screen_name, followers_count, name, description, location, url, email_address])
break if cursor is '0'
yield wait(10)
s.end()
redisClient.quit()
cb?()
.catch (err) ->
# TODO propagate
console.error err.stack
app.use route.get '/memory', (next) ->
@body = process.memoryUsage()
yield return
app.use route.get '/loadavg', (next) ->
@body = os.loadavg()
yield return
app.listen(port)
if require.main is module
co(start).catch (err) ->
console.error err.stack
module.exports = {start}
| true | #!/usr/bin/env coffee
# copyright 2015, PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI. all rights reserved.
# TODO optimize CSV generation
os = require 'os'
util = require 'util'
koa = require 'koa'
route = require 'koa-route'
#koaStatic = require 'koa-static'
co = require 'co'
redis = require 'redis'
coRedis = require 'co-redis'
wait = require 'co-wait'
csv = require 'fast-csv'
survey = require './twitter'
port = process.env.PORT ? 3002
createRedisClient = ->
return coRedis(redis.createClient(process.env.REDIS_URL))
dictify = (a) ->
# [k, v, k2, v2, ... ] -> {k: v, k2: v, ...}
d = {}
for v, i in a
if i % 2 is 1
d[a[i - 1]] = v
return d
commatize = (n) ->
fractionIndex = (n or 0).toString().lastIndexOf('.')
fraction = ''
if fractionIndex > -1
fraction = n.toString().substr(fractionIndex)
if n >= 1000
commatize(Math.floor(n / 1000)) + ',' + Math.floor(n).toString().substr(-3) + fraction
else
n
start = ->
surveyer = new survey.Surveyer()
app = koa()
app.use route.get '/', (next) ->
stats = yield surveyer.stats()
@body = """
<!DOCTYPE html>
<html>
<head>
<title>Twitter Influencer Survey</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/mohsen1/json-formatter-js/master/dist/style.css" />
<style>
body {font-family: Sans-Serif;}
#{if stats.paused then "body {background-color:#fff9f9;}" else ""}
th, td {text-align: right; padding: 0.5em;}
th:first-child {text-align: left;}
table {border-collapse: collapse;}
table, td, th {border: 1px solid black;}
th.trivia, td.trivia {border: 1px solid #eee; color:#eee;}
th.trivia *, td.trivia * {color:#eee;}
.explain {font-size: x-small; color:#ccc;}
h1 {color:#f00;}
</style>
</head>
<body>
#{if stats.paused then "<h1>paused</h1>" else ""}
<h2>Statistics</h2>
<table>
<tr>
<th></th>
<th>processed</th>
<th>unique discovered</th>
<th>
queue
<div class="explain">Backlog</div>
</th>
<th class="trivia">
discarded
<div class="explain">Memory pressure</div>
</th>
</tr>
<tr>
<th>Users
<div class="explain">
Twitter users
</div>
</th>
<td>#{commatize stats.user.popped or 0}</td>
<td>#{if stats.user.discarded then "≥ " else ""}#{commatize stats.user.pushed or 0}</td>
<td rowspan=2>#{if stats.user.discarded then "≥ " else ""}#{commatize stats.user.queue or 0}</td>
<td class="trivia">#{commatize stats.user.discarded or 0}</td>
</tr>
<tr>
<th>Influencers
<div class="explain">
Twitter users with 5,000 followers or more
</div>
<div>
<a href="/influencers.csv">download all</a> or
<a href="/influencers.csv?offset=0&count=5000">top #{commatize Math.min(5000, stats.influencers)}</a>
<a href="/influencers.csv?offset=0&count=5000&hasemail=1">with email</a>
</div>
</th>
<td colspan=2>#{commatize stats.influencers}</td>
<td class="trivia">0</td>
</tr>
<tr>
<th>Influencer Followers
<div class="explain">
Influencers with followers<br/>
About to (slowly) fetch the first 5,000 followers
</div>
</th>
<td>#{commatize stats.followers.popped or 0}</td>
<td>#{if stats.followers.discarded then "≥ " else ""}#{commatize stats.followers.pushed or 0}</td>
<td>#{if stats.followers.discarded then "≥ " else ""}#{commatize stats.followers.queue or 0}</td>
<td class="trivia">#{commatize stats.followers.discarded or 0}</td>
</tr>
<tr>
<th>Influencer Follower Friends
<div class="explain">
Users that follow others<br/>
About to (slowly) fetch the first 5,000 users they follow
</div>
</th>
<td>#{commatize stats.friends.popped or 0}</td>
<td>#{if stats.friends.discarded then "≥ " else ""}#{commatize stats.friends.pushed or 0}</td>
<td>#{if stats.friends.discarded then "≥ " else ""}#{commatize stats.friends.queue or 0}</td>
<td class="trivia">#{commatize stats.friends.discarded or 0}</td>
</tr>
</table>
<h2>Latest Influencer</h2>
<p>
<a href="https://twitter.com/#{stats.lastInfluencer.screen_name}">#{stats.lastInfluencer.name}</a>
</p>
<script src="https://cdn.rawgit.com/mohsen1/json-formatter-js/master/dist/bundle.js"></script>
<script>
var lastInfluencer = #{JSON.stringify(stats.lastInfluencer)};
var formatter = new JSONFormatter(lastInfluencer);
document.body.appendChild(formatter.render())
</script>
</body>
</html>
"""
app.use route.get '/stats', (next) ->
@body = yield surveyer.stats()
app.use route.get '/influencers.csv', (next) ->
redisClient = createRedisClient()
s = csv.createWriteStream()
@body = s
@type = 'text/csv'
@attachment()
s.write(['screen_name', 'followers_count', 'name', 'description', 'location', 'url', 'email_address'])
{offset, count, hasemail} = @query
influencers = null
if offset? or count?
# lazily avoid this ZSET if downloading all
offset ?= 0
count ?= -1
# TODO redis via Surveyer
influencers = yield redisClient.zrevrangebyscore('influence', '+inf', 5000, 'withscores', 'limit', offset, count)
influencers = dictify(influencers)
# HACK proceed in parallel to sending HTTP headers
co (cb) ->
# HACK x@y.z is valid, but x@gmail and "x at gmail dot com" are not
email_re = /\S+@\S+\.\S+/
# HACK fetch everything and filter here
cursor = '0'
loop
[cursor, influencersChunk] = yield redisClient.hscan('influencers', cursor, 'COUNT', 100)
for screen_name, influencer of dictify(influencersChunk)
{name, followers_count, description, location, url} = JSON.parse(influencer)
continue if influencers? and not influencers[screen_name]
description = description.replace(/\r/g, '\n')
email_address = email_re.exec(description)?[0]
continue if hasemail? and not email_address
s.write([screen_name, followers_count, name, description, location, url, email_address])
break if cursor is '0'
yield wait(10)
s.end()
redisClient.quit()
cb?()
.catch (err) ->
# TODO propagate
console.error err.stack
app.use route.get '/memory', (next) ->
@body = process.memoryUsage()
yield return
app.use route.get '/loadavg', (next) ->
@body = os.loadavg()
yield return
app.listen(port)
if require.main is module
co(start).catch (err) ->
console.error err.stack
module.exports = {start}
|
[
{
"context": " parse user info', ->\n expect(parseUserInfo '1234@userName.User.AnimeBytes') .to.deep.equal\n user: '1234@u",
"end": 370,
"score": 0.9436001777648926,
"start": 352,
"tag": "EMAIL",
"value": "1234@userName.User"
},
{
"context": "e.User.AnimeBytes') .to.deep.... | test/parseUserInfo.test.coffee | WeebHoarder/kana | 0 | {expect} = require 'chai'
{
parseUserInfo
ParseUserInfoInvalidInput
ParseUserInfoMissingUser
ParseUserInfoMissingRank
ParseUserInfoMissingHost
ParseUserInfoWrongHost
} = require '../utils/parseUserInfo'
describe 'parseUserInfo utility', ->
describe 'when valid input', ->
it 'should parse user info', ->
expect(parseUserInfo '1234@userName.User.AnimeBytes') .to.deep.equal
user: '1234@userName'
rank: 'User'
it 'should throw on wrong host', ->
expect(-> parseUserInfo '1234@userName.User.SomethingElse')
.to.throw ParseUserInfoWrongHost
describe 'when invalid input', ->
it 'should throw on invalid input', ->
expect(-> parseUserInfo null) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo undefined) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo []) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo {}) .to.throw ParseUserInfoInvalidInput
it 'should throw on missing user', ->
expect(-> parseUserInfo '') .to.throw ParseUserInfoMissingUser
it 'should throw on missing rank', ->
expect(-> parseUserInfo 'user.') .to.throw ParseUserInfoMissingRank
it 'should throw on missing host', ->
expect(-> parseUserInfo 'user.rank.') .to.throw ParseUserInfoMissingHost
| 115447 | {expect} = require 'chai'
{
parseUserInfo
ParseUserInfoInvalidInput
ParseUserInfoMissingUser
ParseUserInfoMissingRank
ParseUserInfoMissingHost
ParseUserInfoWrongHost
} = require '../utils/parseUserInfo'
describe 'parseUserInfo utility', ->
describe 'when valid input', ->
it 'should parse user info', ->
expect(parseUserInfo '<EMAIL>.AnimeBytes') .to.deep.equal
user: '<EMAIL> <PASSWORD>@<EMAIL>'
rank: 'User'
it 'should throw on wrong host', ->
expect(-> parseUserInfo '<EMAIL>.User.SomethingElse')
.to.throw ParseUserInfoWrongHost
describe 'when invalid input', ->
it 'should throw on invalid input', ->
expect(-> parseUserInfo null) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo undefined) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo []) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo {}) .to.throw ParseUserInfoInvalidInput
it 'should throw on missing user', ->
expect(-> parseUserInfo '') .to.throw ParseUserInfoMissingUser
it 'should throw on missing rank', ->
expect(-> parseUserInfo 'user.') .to.throw ParseUserInfoMissingRank
it 'should throw on missing host', ->
expect(-> parseUserInfo 'user.rank.') .to.throw ParseUserInfoMissingHost
| true | {expect} = require 'chai'
{
parseUserInfo
ParseUserInfoInvalidInput
ParseUserInfoMissingUser
ParseUserInfoMissingRank
ParseUserInfoMissingHost
ParseUserInfoWrongHost
} = require '../utils/parseUserInfo'
describe 'parseUserInfo utility', ->
describe 'when valid input', ->
it 'should parse user info', ->
expect(parseUserInfo 'PI:EMAIL:<EMAIL>END_PI.AnimeBytes') .to.deep.equal
user: 'PI:EMAIL:<EMAIL>END_PI PI:PASSWORD:<PASSWORD>END_PI@PI:EMAIL:<EMAIL>END_PI'
rank: 'User'
it 'should throw on wrong host', ->
expect(-> parseUserInfo 'PI:EMAIL:<EMAIL>END_PI.User.SomethingElse')
.to.throw ParseUserInfoWrongHost
describe 'when invalid input', ->
it 'should throw on invalid input', ->
expect(-> parseUserInfo null) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo undefined) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo []) .to.throw ParseUserInfoInvalidInput
expect(-> parseUserInfo {}) .to.throw ParseUserInfoInvalidInput
it 'should throw on missing user', ->
expect(-> parseUserInfo '') .to.throw ParseUserInfoMissingUser
it 'should throw on missing rank', ->
expect(-> parseUserInfo 'user.') .to.throw ParseUserInfoMissingRank
it 'should throw on missing host', ->
expect(-> parseUserInfo 'user.rank.') .to.throw ParseUserInfoMissingHost
|
[
{
"context": "\", ->\n it 'help', ->\n @room.user.say('alice', '@hubot show bangbang commands').then =>\n ",
"end": 461,
"score": 0.6719107031822205,
"start": 456,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " expect(@room.messages).to.eql [\n [... | test/bangbang-test.coffee | lukaspustina/hubot-bangbang | 2 | Helper = require('hubot-test-helper')
chai = require 'chai'
Promise = require('bluebird')
co = require('co')
utils = require('../src/utils')
expect = chai.expect
process.env.EXPRESS_PORT = 18080
command_execution_delay = 20
describe 'bangbang', ->
beforeEach ->
@room = setup_test_env {}
afterEach ->
tear_down_test_env @room
context "generally authorized", ->
context "show help", ->
it 'help', ->
@room.user.say('alice', '@hubot show bangbang commands').then =>
expect(@room.messages).to.eql [
['alice', '@hubot show bangbang commands']
['hubot', "@alice !! date for (.+) - retrieve local date from the specified host\n!! use report for (.+) - retrieve an USE report from the specified host"]
]
context "reload commands", ->
it 'reload', ->
@room.user.say('alice', '@hubot reload bangbang commands').then =>
expect(@room.messages).to.eql [
['alice', '@hubot reload bangbang commands']
['hubot', "@alice Reloaded. Now I recognize 2 commands."]
]
context "run command", ->
context "unrecognized", ->
context "!! anything", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! anything'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! anything']
['hubot', "@alice Oh oh! Did not recognize any command in 'anything'."]
]
context "recognized", ->
context "successful", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! date for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! date for server']
['hubot', "@alice Alright, trying to retrieve local date from the specified host with parameters 'server'."]
['hubot', "@alice Your ticket is '5c89100'."]
['hubot', "@alice Your command with ticket '5c89100' finished successfully."]
['hubot', "@alice Command output for 'echo ssh server date':"]
['hubot', "@alice ssh server date\n"]
]
context "command based authorized", ->
context "run command", ->
context "recognized", ->
context "successful", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! use report for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! use report for server']
['hubot', "@alice Alright, trying to retrieve an USE report from the specified host with parameters 'server'."]
['hubot', "@alice Your ticket is 'd42a892'."]
['hubot', "@alice Your command with ticket 'd42a892' finished successfully."]
['hubot', "@alice Command output for 'echo ssh server usereport.py':"]
['hubot', "@alice ssh server usereport.py\n"]
]
context "command based unauthorized", ->
context "run command", ->
context "recognized", ->
context "Fail if unauthorized", ->
beforeEach ->
co =>
yield @room.user.say 'charlie', '@hubot !! use report for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['charlie', '@hubot !! use report for server']
['hubot', "@charlie Sorry, you're not allowed to do that. You need the 'bangbang' and 'bangbang.use_report' roles."]
]
context "generally unauthorized", ->
context "run command", ->
context "Fail if unauthorized", ->
it '!! anything', ->
@room.user.say('bob', '@hubot !! anything').then =>
expect(@room.messages).to.eql [
['bob', '@hubot !! anything']
['hubot', "@bob Sorry, you're not allowed to do that. You need the 'bangbang' role."]
]
describe 'bangbang error handling', ->
beforeEach ->
@room = setup_test_env {
hubot_bangbang_commands_file: "#{__dirname}/commands_for_error_handling-test.js"
}
afterEach ->
tear_down_test_env @room
context "authorized", ->
context "run command", ->
context "failed, because command failed", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! exit 2'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! exit 2']
['hubot', "@alice Alright, trying to exits with specified code with parameters '2'."]
['hubot', "@alice Your ticket is '00e264e'."]
['hubot', "@alice Your command with ticket '00e264e' finished with error code 2, because of null."]
['hubot', "@alice Command output for 'exit 2':"]
]
context "failed, because command does not exist", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! does not exist for does not matter'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! does not exist for does not matter']
['hubot', "@alice Alright, trying to tries to run a command that does not exists with parameters 'does not matter'."]
['hubot', "@alice Your ticket is 'f5d8d6f'."]
['hubot', "@alice Your command with ticket 'f5d8d6f' finished with error code 127, because of null."]
]
context "failed, because command timedout", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! time out'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! time out']
['hubot', "@alice Alright, trying to tries to time out with parameters ''."]
['hubot', "@alice Your ticket is '9b528ca'."]
['hubot', "@alice Your command with ticket '9b528ca' finished with error code null, because of SIGTERM."]
['hubot', "@alice Command output for 'sleep 60':"]
]
slackMessages = []
describe 'bangbang with Slack', ->
beforeEach ->
@room = setup_test_env {
hubot_bangbang_slack: "yes"
hubot_bangbang_commands_file: "#{__dirname}/commands_for_slack-test.js"
}
slackMessages = []
@room.robot.adapter.customMessage = (msg) -> slackMessages.push msg
afterEach ->
tear_down_test_env @room
context "authorized", ->
context "run command", ->
context "recognized", ->
context "successful with stdout only formated with markdown", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! markdown'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! markdown"]
['hubot', "@alice Alright, trying to echo markdown with parameters ''."]
['hubot', "@alice Your ticket is '6edb6c0'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: [ "text" ]
text: "# Title\n\n## Subtitle\n\n This is markdown\n"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket '6edb6c0' finished successfully."
]
context "successful with stdout only formated with pre", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! pre'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! pre"]
['hubot', "@alice Alright, trying to echo pre with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: [ "text" ]
text: "```\noutput\n\n```"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout only formated with plain", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! plain'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! plain"]
['hubot', "@alice Alright, trying to echo plain with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: []
text: "output\n"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout only formated with ignore", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! ignore'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! ignore"]
['hubot', "@alice Alright, trying to echo ignore with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: []
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout and stderr", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! plain_out_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! plain_out_err"]
['hubot', "@alice Alright, trying to echo plain to stdout and stderr with parameters ''."]
['hubot', "@alice Your ticket is 'e637a83'."]
]
expect(slackMessages).to.eql [
attachments: [
{
color: "good"
mrkdwn_in: []
text: "stdout\n"
title: "stdout"
}, {
color: "good"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
}
]
channel: "room1"
text: "Your command with ticket 'e637a83' finished successfully."
]
context "failed with stderr only", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! fail_out_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! fail_out_err"]
['hubot', "@alice Alright, trying to echo plain to stdout and stderr and exit 2 with parameters ''."]
['hubot', "@alice Your ticket is 'a2e2791'."]
]
expect(slackMessages).to.eql [
attachments: [
{
color: "danger"
mrkdwn_in: []
text: "stdout\n"
title: "stdout"
}, {
color: "danger"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
}
]
channel: "room1"
text: "Your command with ticket 'a2e2791' finished with error code 2, because of null."
]
context "failed with stdout and stderr", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! fail_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! fail_err"]
['hubot', "@alice Alright, trying to echo plain to stderr and exit 2 with parameters ''."]
['hubot', "@alice Your ticket is '787ea34'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "danger"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
]
channel: "room1"
text: "Your command with ticket '787ea34' finished with error code 2, because of null."
]
setup_test_env = (env) ->
process.env.HUBOT_BANGBANG_COMMANDS_FILE = env.hubot_bangbang_commands_file or "#{__dirname}/commands-test.js"
process.env.HUBOT_BANGBANG_LOG_LEVEL = env.hubot_bangbang_debug_level or "error"
process.env.HUBOT_BANGBANG_ROLE = env.hubot_bangbang_role or "bangbang"
process.env.HUBOT_BANGBANG_SLACK = env.hubot_bangbang_slack or "no"
process.env.HUBOT_BANGBANG_TIMEOUT = env.hubot_bangbang_slack_timeout or 1000
unpatched_utils_now = utils.now
utils.now = () -> 1469527900631
helper = new Helper('../src/bangbang.coffee')
room = helper.createRoom()
room.robot.auth = new MockAuth
room.unpatched_utils_now = unpatched_utils_now
room
tear_down_test_env = (room) ->
utils.now = room.unpatched_utils_now
room.destroy()
# Force reload of module under test
delete require.cache[require.resolve('../src/bangbang')]
class MockAuth
hasRole: (user, role) ->
if user.name is 'alice' and role is 'bangbang' then return true
if user.name is 'alice' and role is 'bangbang.use_report' then return true
if user.name is 'charlie' and role is 'bangbang' then return true
return false
| 10487 | Helper = require('hubot-test-helper')
chai = require 'chai'
Promise = require('bluebird')
co = require('co')
utils = require('../src/utils')
expect = chai.expect
process.env.EXPRESS_PORT = 18080
command_execution_delay = 20
describe 'bangbang', ->
beforeEach ->
@room = setup_test_env {}
afterEach ->
tear_down_test_env @room
context "generally authorized", ->
context "show help", ->
it 'help', ->
@room.user.say('alice', '@hubot show bangbang commands').then =>
expect(@room.messages).to.eql [
['alice', '@hubot show bangbang commands']
['hubot', "@alice !! date for (.+) - retrieve local date from the specified host\n!! use report for (.+) - retrieve an USE report from the specified host"]
]
context "reload commands", ->
it 'reload', ->
@room.user.say('alice', '@hubot reload bangbang commands').then =>
expect(@room.messages).to.eql [
['alice', '@hubot reload bangbang commands']
['hubot', "@alice Reloaded. Now I recognize 2 commands."]
]
context "run command", ->
context "unrecognized", ->
context "!! anything", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! anything'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! anything']
['hubot', "@alice Oh oh! Did not recognize any command in 'anything'."]
]
context "recognized", ->
context "successful", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! date for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! date for server']
['hubot', "@alice Alright, trying to retrieve local date from the specified host with parameters 'server'."]
['hubot', "@alice Your ticket is '5c89100'."]
['hubot', "@alice Your command with ticket '5c89100' finished successfully."]
['hubot', "@alice Command output for 'echo ssh server date':"]
['hubot', "@alice ssh server date\n"]
]
context "command based authorized", ->
context "run command", ->
context "recognized", ->
context "successful", ->
beforeEach ->
co =>
yield @room.user.say '<NAME>', '@hubot !! use report for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! use report for server']
['hubot', "@alice <NAME>, trying to retrieve an USE report from the specified host with parameters 'server'."]
['hubot', "@alice Your ticket is 'd42a892'."]
['hubot', "@alice Your command with ticket 'd42a892' finished successfully."]
['hubot', "@alice Command output for 'echo ssh server usereport.py':"]
['hubot', "@alice ssh server usereport.py\n"]
]
context "command based unauthorized", ->
context "run command", ->
context "recognized", ->
context "Fail if unauthorized", ->
beforeEach ->
co =>
yield @room.user.say '<NAME>', '@hubot !! use report for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['<NAME>', '@hubot !! use report for server']
['hubot', "@charlie Sorry, you're not allowed to do that. You need the 'bangbang' and 'bangbang.use_report' roles."]
]
context "generally unauthorized", ->
context "run command", ->
context "Fail if unauthorized", ->
it '!! anything', ->
@room.user.say('<NAME>', '@hubot !! anything').then =>
expect(@room.messages).to.eql [
['bob', '@hubot !! anything']
['hubot', "@bob Sorry, you're not allowed to do that. You need the 'bangbang' role."]
]
describe 'bangbang error handling', ->
beforeEach ->
@room = setup_test_env {
hubot_bangbang_commands_file: "#{__dirname}/commands_for_error_handling-test.js"
}
afterEach ->
tear_down_test_env @room
context "authorized", ->
context "run command", ->
context "failed, because command failed", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! exit 2'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! exit 2']
['hubot', "@alice <NAME>, trying to exits with specified code with parameters '2'."]
['hubot', "@alice Your ticket is '00e264e'."]
['hubot', "@alice Your command with ticket '00e264e' finished with error code 2, because of null."]
['hubot', "@alice Command output for 'exit 2':"]
]
context "failed, because command does not exist", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! does not exist for does not matter'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! does not exist for does not matter']
['hubot', "@alice <NAME>, trying to tries to run a command that does not exists with parameters 'does not matter'."]
['hubot', "@alice Your ticket is 'f5d8d6f'."]
['hubot', "@alice Your command with ticket 'f5d8d6f' finished with error code 127, because of null."]
]
context "failed, because command timedout", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! time out'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! time out']
['hubot', "@alice <NAME>, trying to tries to time out with parameters ''."]
['hubot', "@alice Your ticket is '9b528ca'."]
['hubot', "@alice Your command with ticket '9b528ca' finished with error code null, because of SIGTERM."]
['hubot', "@alice Command output for 'sleep 60':"]
]
slackMessages = []
describe 'bangbang with Slack', ->
beforeEach ->
@room = setup_test_env {
hubot_bangbang_slack: "yes"
hubot_bangbang_commands_file: "#{__dirname}/commands_for_slack-test.js"
}
slackMessages = []
@room.robot.adapter.customMessage = (msg) -> slackMessages.push msg
afterEach ->
tear_down_test_env @room
context "authorized", ->
context "run command", ->
context "recognized", ->
context "successful with stdout only formated with markdown", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! markdown'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! markdown"]
['hubot', "@alice Al<NAME>, trying to echo markdown with parameters ''."]
['hubot', "@alice Your ticket is '6edb6c0'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: [ "text" ]
text: "# Title\n\n## Subtitle\n\n This is markdown\n"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket '6edb6c0' finished successfully."
]
context "successful with stdout only formated with pre", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! pre'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! pre"]
['hubot', "@alice Al<NAME>, trying to echo pre with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: [ "text" ]
text: "```\noutput\n\n```"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout only formated with plain", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! plain'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! plain"]
['hubot', "@alice Alright, trying to echo plain with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: []
text: "output\n"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout only formated with ignore", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! ignore'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! ignore"]
['hubot', "@alice Alright, trying to echo ignore with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: []
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout and stderr", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! plain_out_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! plain_out_err"]
['hubot', "@alice Alright, trying to echo plain to stdout and stderr with parameters ''."]
['hubot', "@alice Your ticket is 'e637a83'."]
]
expect(slackMessages).to.eql [
attachments: [
{
color: "good"
mrkdwn_in: []
text: "stdout\n"
title: "stdout"
}, {
color: "good"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
}
]
channel: "room1"
text: "Your command with ticket 'e637a83' finished successfully."
]
context "failed with stderr only", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! fail_out_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! fail_out_err"]
['hubot', "@alice Alright, trying to echo plain to stdout and stderr and exit 2 with parameters ''."]
['hubot', "@alice Your ticket is 'a2e2791'."]
]
expect(slackMessages).to.eql [
attachments: [
{
color: "danger"
mrkdwn_in: []
text: "stdout\n"
title: "stdout"
}, {
color: "danger"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
}
]
channel: "room1"
text: "Your command with ticket 'a2e2791' finished with error code 2, because of null."
]
context "failed with stdout and stderr", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! fail_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! fail_err"]
['hubot', "@alice Alright, trying to echo plain to stderr and exit 2 with parameters ''."]
['hubot', "@alice Your ticket is '787ea34'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "danger"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
]
channel: "room1"
text: "Your command with ticket '787ea34' finished with error code 2, because of null."
]
setup_test_env = (env) ->
process.env.HUBOT_BANGBANG_COMMANDS_FILE = env.hubot_bangbang_commands_file or "#{__dirname}/commands-test.js"
process.env.HUBOT_BANGBANG_LOG_LEVEL = env.hubot_bangbang_debug_level or "error"
process.env.HUBOT_BANGBANG_ROLE = env.hubot_bangbang_role or "bangbang"
process.env.HUBOT_BANGBANG_SLACK = env.hubot_bangbang_slack or "no"
process.env.HUBOT_BANGBANG_TIMEOUT = env.hubot_bangbang_slack_timeout or 1000
unpatched_utils_now = utils.now
utils.now = () -> 1469527900631
helper = new Helper('../src/bangbang.coffee')
room = helper.createRoom()
room.robot.auth = new MockAuth
room.unpatched_utils_now = unpatched_utils_now
room
tear_down_test_env = (room) ->
utils.now = room.unpatched_utils_now
room.destroy()
# Force reload of module under test
delete require.cache[require.resolve('../src/bangbang')]
class MockAuth
hasRole: (user, role) ->
if user.name is 'alice' and role is 'bangbang' then return true
if user.name is 'alice' and role is 'bangbang.use_report' then return true
if user.name is 'charlie' and role is 'bangbang' then return true
return false
| true | Helper = require('hubot-test-helper')
chai = require 'chai'
Promise = require('bluebird')
co = require('co')
utils = require('../src/utils')
expect = chai.expect
process.env.EXPRESS_PORT = 18080
command_execution_delay = 20
describe 'bangbang', ->
beforeEach ->
@room = setup_test_env {}
afterEach ->
tear_down_test_env @room
context "generally authorized", ->
context "show help", ->
it 'help', ->
@room.user.say('alice', '@hubot show bangbang commands').then =>
expect(@room.messages).to.eql [
['alice', '@hubot show bangbang commands']
['hubot', "@alice !! date for (.+) - retrieve local date from the specified host\n!! use report for (.+) - retrieve an USE report from the specified host"]
]
context "reload commands", ->
it 'reload', ->
@room.user.say('alice', '@hubot reload bangbang commands').then =>
expect(@room.messages).to.eql [
['alice', '@hubot reload bangbang commands']
['hubot', "@alice Reloaded. Now I recognize 2 commands."]
]
context "run command", ->
context "unrecognized", ->
context "!! anything", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! anything'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! anything']
['hubot', "@alice Oh oh! Did not recognize any command in 'anything'."]
]
context "recognized", ->
context "successful", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! date for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! date for server']
['hubot', "@alice Alright, trying to retrieve local date from the specified host with parameters 'server'."]
['hubot', "@alice Your ticket is '5c89100'."]
['hubot', "@alice Your command with ticket '5c89100' finished successfully."]
['hubot', "@alice Command output for 'echo ssh server date':"]
['hubot', "@alice ssh server date\n"]
]
context "command based authorized", ->
context "run command", ->
context "recognized", ->
context "successful", ->
beforeEach ->
co =>
yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot !! use report for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! use report for server']
['hubot', "@alice PI:NAME:<NAME>END_PI, trying to retrieve an USE report from the specified host with parameters 'server'."]
['hubot', "@alice Your ticket is 'd42a892'."]
['hubot', "@alice Your command with ticket 'd42a892' finished successfully."]
['hubot', "@alice Command output for 'echo ssh server usereport.py':"]
['hubot', "@alice ssh server usereport.py\n"]
]
context "command based unauthorized", ->
context "run command", ->
context "recognized", ->
context "Fail if unauthorized", ->
beforeEach ->
co =>
yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot !! use report for server'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['PI:NAME:<NAME>END_PI', '@hubot !! use report for server']
['hubot', "@charlie Sorry, you're not allowed to do that. You need the 'bangbang' and 'bangbang.use_report' roles."]
]
context "generally unauthorized", ->
context "run command", ->
context "Fail if unauthorized", ->
it '!! anything', ->
@room.user.say('PI:NAME:<NAME>END_PI', '@hubot !! anything').then =>
expect(@room.messages).to.eql [
['bob', '@hubot !! anything']
['hubot', "@bob Sorry, you're not allowed to do that. You need the 'bangbang' role."]
]
describe 'bangbang error handling', ->
beforeEach ->
@room = setup_test_env {
hubot_bangbang_commands_file: "#{__dirname}/commands_for_error_handling-test.js"
}
afterEach ->
tear_down_test_env @room
context "authorized", ->
context "run command", ->
context "failed, because command failed", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! exit 2'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! exit 2']
['hubot', "@alice PI:NAME:<NAME>END_PI, trying to exits with specified code with parameters '2'."]
['hubot', "@alice Your ticket is '00e264e'."]
['hubot', "@alice Your command with ticket '00e264e' finished with error code 2, because of null."]
['hubot', "@alice Command output for 'exit 2':"]
]
context "failed, because command does not exist", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! does not exist for does not matter'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! does not exist for does not matter']
['hubot', "@alice PI:NAME:<NAME>END_PI, trying to tries to run a command that does not exists with parameters 'does not matter'."]
['hubot', "@alice Your ticket is 'f5d8d6f'."]
['hubot', "@alice Your command with ticket 'f5d8d6f' finished with error code 127, because of null."]
]
context "failed, because command timedout", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! time out'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', '@hubot !! time out']
['hubot', "@alice PI:NAME:<NAME>END_PI, trying to tries to time out with parameters ''."]
['hubot', "@alice Your ticket is '9b528ca'."]
['hubot', "@alice Your command with ticket '9b528ca' finished with error code null, because of SIGTERM."]
['hubot', "@alice Command output for 'sleep 60':"]
]
slackMessages = []
describe 'bangbang with Slack', ->
beforeEach ->
@room = setup_test_env {
hubot_bangbang_slack: "yes"
hubot_bangbang_commands_file: "#{__dirname}/commands_for_slack-test.js"
}
slackMessages = []
@room.robot.adapter.customMessage = (msg) -> slackMessages.push msg
afterEach ->
tear_down_test_env @room
context "authorized", ->
context "run command", ->
context "recognized", ->
context "successful with stdout only formated with markdown", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! markdown'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! markdown"]
['hubot', "@alice AlPI:NAME:<NAME>END_PI, trying to echo markdown with parameters ''."]
['hubot', "@alice Your ticket is '6edb6c0'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: [ "text" ]
text: "# Title\n\n## Subtitle\n\n This is markdown\n"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket '6edb6c0' finished successfully."
]
context "successful with stdout only formated with pre", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! pre'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! pre"]
['hubot', "@alice AlPI:NAME:<NAME>END_PI, trying to echo pre with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: [ "text" ]
text: "```\noutput\n\n```"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout only formated with plain", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! plain'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! plain"]
['hubot', "@alice Alright, trying to echo plain with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "good"
mrkdwn_in: []
text: "output\n"
title: "stdout"
]
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout only formated with ignore", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! ignore'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! ignore"]
['hubot', "@alice Alright, trying to echo ignore with parameters ''."]
['hubot', "@alice Your ticket is 'da7e3fa'."]
]
expect(slackMessages).to.eql [
attachments: []
channel: "room1"
text: "Your command with ticket 'da7e3fa' finished successfully."
]
context "successful with stdout and stderr", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! plain_out_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! plain_out_err"]
['hubot', "@alice Alright, trying to echo plain to stdout and stderr with parameters ''."]
['hubot', "@alice Your ticket is 'e637a83'."]
]
expect(slackMessages).to.eql [
attachments: [
{
color: "good"
mrkdwn_in: []
text: "stdout\n"
title: "stdout"
}, {
color: "good"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
}
]
channel: "room1"
text: "Your command with ticket 'e637a83' finished successfully."
]
context "failed with stderr only", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! fail_out_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! fail_out_err"]
['hubot', "@alice Alright, trying to echo plain to stdout and stderr and exit 2 with parameters ''."]
['hubot', "@alice Your ticket is 'a2e2791'."]
]
expect(slackMessages).to.eql [
attachments: [
{
color: "danger"
mrkdwn_in: []
text: "stdout\n"
title: "stdout"
}, {
color: "danger"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
}
]
channel: "room1"
text: "Your command with ticket 'a2e2791' finished with error code 2, because of null."
]
context "failed with stdout and stderr", ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot !! fail_err'
yield new Promise.delay command_execution_delay
it 'run', ->
expect(@room.messages).to.eql [
['alice', "@hubot !! fail_err"]
['hubot', "@alice Alright, trying to echo plain to stderr and exit 2 with parameters ''."]
['hubot', "@alice Your ticket is '787ea34'."]
]
expect(slackMessages).to.eql [
attachments: [
color: "danger"
mrkdwn_in: []
text: "stderr\n"
title: "stderr"
]
channel: "room1"
text: "Your command with ticket '787ea34' finished with error code 2, because of null."
]
setup_test_env = (env) ->
process.env.HUBOT_BANGBANG_COMMANDS_FILE = env.hubot_bangbang_commands_file or "#{__dirname}/commands-test.js"
process.env.HUBOT_BANGBANG_LOG_LEVEL = env.hubot_bangbang_debug_level or "error"
process.env.HUBOT_BANGBANG_ROLE = env.hubot_bangbang_role or "bangbang"
process.env.HUBOT_BANGBANG_SLACK = env.hubot_bangbang_slack or "no"
process.env.HUBOT_BANGBANG_TIMEOUT = env.hubot_bangbang_slack_timeout or 1000
unpatched_utils_now = utils.now
utils.now = () -> 1469527900631
helper = new Helper('../src/bangbang.coffee')
room = helper.createRoom()
room.robot.auth = new MockAuth
room.unpatched_utils_now = unpatched_utils_now
room
tear_down_test_env = (room) ->
utils.now = room.unpatched_utils_now
room.destroy()
# Force reload of module under test
delete require.cache[require.resolve('../src/bangbang')]
class MockAuth
hasRole: (user, role) ->
if user.name is 'alice' and role is 'bangbang' then return true
if user.name is 'alice' and role is 'bangbang.use_report' then return true
if user.name is 'charlie' and role is 'bangbang' then return true
return false
|
[
{
"context": "g-a-grammar/\n\nscopeName: 'source.fountain'\nname: 'Fountain'\ntype: 'tree-sitter'\nparser: 'tree-sitter-fountai",
"end": 191,
"score": 0.9995436668395996,
"start": 183,
"tag": "NAME",
"value": "Fountain"
}
] | grammars/tree-sitter-fountain.cson | UserNobody14/language-fountain | 0 | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
scopeName: 'source.fountain'
name: 'Fountain'
type: 'tree-sitter'
parser: 'tree-sitter-fountain'
fileTypes: ['fountain', 'ftn']
folds: [
{type: 'scene'},
{type: 'section1'},
{type: 'section2'},
{type: 'section3'},
{type: 'section4'},
{type: 'section5'},
{type: 'section6'},
{type: 'boneyard'}
]
scopes:
#Match dialogue action and centered action.
#Dialog
'dialogue > character' : 'string.other.dialogue.character.fountain'
'dialogue > parenthetical' : 'string.other.dialogue.parenthetical.fountain'
'dialogue > lyric' : 'lyric'
#TODO: make all grammatical forcing characters highlighted separately.
#(using regex obviously.) start with section headings.
#Emphasis Text
'action, centered_action > normal_txt' : 'markup.normal.action'
'action, centered_action > italic_txt' : 'markup.italic.action'
'action, centered_action > bold_txt' : 'markup.bold.action'
'action, centered_action > bold_and_italic_txt' : 'markup.bold.italic.action'
'action, centered_action > underlined_txt' : 'markup.underlined.action'
'spoken > normal_txt' : 'markup.normal.spoken.dialogue.fountain'
'spoken > italic_txt' : 'markup.italic.spoken.dialogue.fountain'
'spoken > bold_txt' : 'markup.bold.spoken.dialogue.fountain'
'spoken > bold_and_italic_txt' : 'markup.bold.italic.spoken.dialogue.fountain'
'spoken > underlined_txt' : 'markup.underlined.spoken.dialogue.fountain'
#Match Sections and scene headings
'section1' : 'section.level1.fountain'
'section2' : 'section.level2.fountain'
'section3' : 'section.level3.fountain'
'section4' : 'section.level4.fountain'
'section5' : 'section.level5.fountain'
'section6' : 'section.level6.fountain'
'sec_heading1' : 'secHeading.level1.heading1'
'sec_heading2' : 'secHeading.level2.heading2'
'sec_heading3' : 'secHeading.level3.heading3'
'sec_heading4' : 'secHeading.level4.heading4'
'sec_heading5' : 'secHeading.level5.heading5'
'sec_heading6' : 'secHeading.level6.heading6'
#Match Scenes
'scene_heading' : 'fountain.scene.heading'
#Match Misc
'note' : 'comment.note.fountain'
'synopsis' : 'comment.synopsis.fountain'
'boneyard' : 'comment.block.fountain'
'page_break' : 'fountain.page.break'
'transition' : 'fountain.transition'
#Match title page and keys.
'title_page' : 'fountain.title'
'title_page > k_v_pair' : 'fountain.keyandvalue'
'k_v_pair > key' : 'fountain.key'
'k_v_pair > value' : 'fountain.value'
#////////////////////////////////////////////
#tried naming them after normal css items to improve reliability?
# lookup github markup?
#'action, centered_action, spoken > normal_txt' : 'string.quoted'
| 172951 | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
scopeName: 'source.fountain'
name: '<NAME>'
type: 'tree-sitter'
parser: 'tree-sitter-fountain'
fileTypes: ['fountain', 'ftn']
folds: [
{type: 'scene'},
{type: 'section1'},
{type: 'section2'},
{type: 'section3'},
{type: 'section4'},
{type: 'section5'},
{type: 'section6'},
{type: 'boneyard'}
]
scopes:
#Match dialogue action and centered action.
#Dialog
'dialogue > character' : 'string.other.dialogue.character.fountain'
'dialogue > parenthetical' : 'string.other.dialogue.parenthetical.fountain'
'dialogue > lyric' : 'lyric'
#TODO: make all grammatical forcing characters highlighted separately.
#(using regex obviously.) start with section headings.
#Emphasis Text
'action, centered_action > normal_txt' : 'markup.normal.action'
'action, centered_action > italic_txt' : 'markup.italic.action'
'action, centered_action > bold_txt' : 'markup.bold.action'
'action, centered_action > bold_and_italic_txt' : 'markup.bold.italic.action'
'action, centered_action > underlined_txt' : 'markup.underlined.action'
'spoken > normal_txt' : 'markup.normal.spoken.dialogue.fountain'
'spoken > italic_txt' : 'markup.italic.spoken.dialogue.fountain'
'spoken > bold_txt' : 'markup.bold.spoken.dialogue.fountain'
'spoken > bold_and_italic_txt' : 'markup.bold.italic.spoken.dialogue.fountain'
'spoken > underlined_txt' : 'markup.underlined.spoken.dialogue.fountain'
#Match Sections and scene headings
'section1' : 'section.level1.fountain'
'section2' : 'section.level2.fountain'
'section3' : 'section.level3.fountain'
'section4' : 'section.level4.fountain'
'section5' : 'section.level5.fountain'
'section6' : 'section.level6.fountain'
'sec_heading1' : 'secHeading.level1.heading1'
'sec_heading2' : 'secHeading.level2.heading2'
'sec_heading3' : 'secHeading.level3.heading3'
'sec_heading4' : 'secHeading.level4.heading4'
'sec_heading5' : 'secHeading.level5.heading5'
'sec_heading6' : 'secHeading.level6.heading6'
#Match Scenes
'scene_heading' : 'fountain.scene.heading'
#Match Misc
'note' : 'comment.note.fountain'
'synopsis' : 'comment.synopsis.fountain'
'boneyard' : 'comment.block.fountain'
'page_break' : 'fountain.page.break'
'transition' : 'fountain.transition'
#Match title page and keys.
'title_page' : 'fountain.title'
'title_page > k_v_pair' : 'fountain.keyandvalue'
'k_v_pair > key' : 'fountain.key'
'k_v_pair > value' : 'fountain.value'
#////////////////////////////////////////////
#tried naming them after normal css items to improve reliability?
# lookup github markup?
#'action, centered_action, spoken > normal_txt' : 'string.quoted'
| true | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
scopeName: 'source.fountain'
name: 'PI:NAME:<NAME>END_PI'
type: 'tree-sitter'
parser: 'tree-sitter-fountain'
fileTypes: ['fountain', 'ftn']
folds: [
{type: 'scene'},
{type: 'section1'},
{type: 'section2'},
{type: 'section3'},
{type: 'section4'},
{type: 'section5'},
{type: 'section6'},
{type: 'boneyard'}
]
scopes:
#Match dialogue action and centered action.
#Dialog
'dialogue > character' : 'string.other.dialogue.character.fountain'
'dialogue > parenthetical' : 'string.other.dialogue.parenthetical.fountain'
'dialogue > lyric' : 'lyric'
#TODO: make all grammatical forcing characters highlighted separately.
#(using regex obviously.) start with section headings.
#Emphasis Text
'action, centered_action > normal_txt' : 'markup.normal.action'
'action, centered_action > italic_txt' : 'markup.italic.action'
'action, centered_action > bold_txt' : 'markup.bold.action'
'action, centered_action > bold_and_italic_txt' : 'markup.bold.italic.action'
'action, centered_action > underlined_txt' : 'markup.underlined.action'
'spoken > normal_txt' : 'markup.normal.spoken.dialogue.fountain'
'spoken > italic_txt' : 'markup.italic.spoken.dialogue.fountain'
'spoken > bold_txt' : 'markup.bold.spoken.dialogue.fountain'
'spoken > bold_and_italic_txt' : 'markup.bold.italic.spoken.dialogue.fountain'
'spoken > underlined_txt' : 'markup.underlined.spoken.dialogue.fountain'
#Match Sections and scene headings
'section1' : 'section.level1.fountain'
'section2' : 'section.level2.fountain'
'section3' : 'section.level3.fountain'
'section4' : 'section.level4.fountain'
'section5' : 'section.level5.fountain'
'section6' : 'section.level6.fountain'
'sec_heading1' : 'secHeading.level1.heading1'
'sec_heading2' : 'secHeading.level2.heading2'
'sec_heading3' : 'secHeading.level3.heading3'
'sec_heading4' : 'secHeading.level4.heading4'
'sec_heading5' : 'secHeading.level5.heading5'
'sec_heading6' : 'secHeading.level6.heading6'
#Match Scenes
'scene_heading' : 'fountain.scene.heading'
#Match Misc
'note' : 'comment.note.fountain'
'synopsis' : 'comment.synopsis.fountain'
'boneyard' : 'comment.block.fountain'
'page_break' : 'fountain.page.break'
'transition' : 'fountain.transition'
#Match title page and keys.
'title_page' : 'fountain.title'
'title_page > k_v_pair' : 'fountain.keyandvalue'
'k_v_pair > key' : 'fountain.key'
'k_v_pair > value' : 'fountain.value'
#////////////////////////////////////////////
#tried naming them after normal css items to improve reliability?
# lookup github markup?
#'action, centered_action, spoken > normal_txt' : 'string.quoted'
|
[
{
"context": "leoverview Operator linebreak rule tests\n# @author Benoît Zugmeyer\n###\n'use strict'\n\n#------------------------------",
"end": 76,
"score": 0.9998427033424377,
"start": 61,
"tag": "NAME",
"value": "Benoît Zugmeyer"
}
] | src/tests/rules/operator-linebreak.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Operator linebreak rule tests
# @author Benoît Zugmeyer
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
util = require 'util'
rule = require '../../rules/operator-linebreak'
path = require 'path'
{RuleTester} = require 'eslint'
# BAD_LN_BRK_MSG = "Bad line breaking before and after '%s'."
# BEFORE_MSG = "'%s' should be placed at the beginning of the line."
# AFTER_MSG = "'%s' should be placed at the end of the line."
NONE_MSG = "There should be no line break before or after '%s'."
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'operator-linebreak', rule,
valid: [
'1 + 1'
'1 + 1 + 1'
'1 +\n1'
'1 + (1 +\n1)'
'f(1 +\n1)'
'1 || 1'
'1 || \n1'
'1 ? 1'
'1 ? \n1'
'a += 1'
'a'
'o = \nsomething'
'o = \nsomething'
"'a\\\n' +\n 'c'"
"'a' +\n 'b\\\n'"
'(a\n) + b'
'''
answer =
if everything
42
else
foo
'''
,
code: '''
answer = if everything
42
else
foo
'''
options: ['none']
,
code: 'a += 1', options: ['before']
,
code: '1 + 1', options: ['none']
,
code: '1 + 1 + 1', options: ['none']
,
code: '1 || 1', options: ['none']
,
code: 'a += 1', options: ['none']
,
code: 'a', options: ['none']
,
code: '\n1 + 1', options: ['none']
,
code: '1 + 1\n', options: ['none']
]
invalid: [
# code: '1 \n || 1'
# output: '1 || \n 1'
# errors: [
# message: util.format AFTER_MSG, '||'
# type: 'LogicalExpression'
# line: 2
# column: 4
# ]
# ,
# code: '1 || \n 1'
# output: '1 \n || 1'
# options: ['before']
# errors: [
# message: util.format BEFORE_MSG, '||'
# type: 'LogicalExpression'
# line: 1
# column: 5
# ]
# ,
code: '1 +\n1'
# output: '1 +1'
options: ['none']
errors: [
message: util.format NONE_MSG, '+'
type: 'BinaryExpression'
line: 1
column: 4
]
,
code: 'f(1 +\n1)'
# output: 'f(1 +1)'
options: ['none']
errors: [
message: util.format NONE_MSG, '+'
type: 'BinaryExpression'
line: 1
column: 6
]
,
code: '1 || \n 1'
# output: '1 || 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '||'
type: 'LogicalExpression'
line: 1
column: 5
]
,
code: '1 or \n 1'
# output: '1 || 1'
options: ['none']
errors: [
message: util.format NONE_MSG, 'or'
type: 'LogicalExpression'
line: 1
column: 5
]
,
# ,
# code: '1 \n || 1'
# # output: '1 || 1'
# options: ['none']
# errors: [
# message: util.format NONE_MSG, '||'
# type: 'LogicalExpression'
# line: 2
# column: 4
# ]
code: 'a += \n1'
# output: 'a += 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '+='
type: 'AssignmentExpression'
line: 1
column: 5
]
,
code: 'a = \n1'
# output: 'a = 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '='
type: 'AssignmentExpression'
line: 1
column: 4
]
,
code: 'foo +=\n42\nbar -=\n12'
# output: 'foo +=42\nbar -=\n12\n+ 5'
options: ['after', {overrides: '+=': 'none'}]
errors: [
message: util.format NONE_MSG, '+='
type: 'AssignmentExpression'
line: 1
column: 7
]
# ,
# code: 'foo #comment\n&& bar'
# # output: 'foo && #comment\nbar'
# errors: [
# message: util.format AFTER_MSG, '&&'
# type: 'LogicalExpression'
# line: 2
# column: 3
# ]
# ,
# code: 'foo #comment\nand bar'
# # output: 'foo && #comment\nbar'
# errors: [
# message: util.format AFTER_MSG, 'and'
# type: 'LogicalExpression'
# line: 2
# column: 3
# ]
]
| 82571 | ###*
# @fileoverview Operator linebreak rule tests
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
util = require 'util'
rule = require '../../rules/operator-linebreak'
path = require 'path'
{RuleTester} = require 'eslint'
# BAD_LN_BRK_MSG = "Bad line breaking before and after '%s'."
# BEFORE_MSG = "'%s' should be placed at the beginning of the line."
# AFTER_MSG = "'%s' should be placed at the end of the line."
NONE_MSG = "There should be no line break before or after '%s'."
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'operator-linebreak', rule,
valid: [
'1 + 1'
'1 + 1 + 1'
'1 +\n1'
'1 + (1 +\n1)'
'f(1 +\n1)'
'1 || 1'
'1 || \n1'
'1 ? 1'
'1 ? \n1'
'a += 1'
'a'
'o = \nsomething'
'o = \nsomething'
"'a\\\n' +\n 'c'"
"'a' +\n 'b\\\n'"
'(a\n) + b'
'''
answer =
if everything
42
else
foo
'''
,
code: '''
answer = if everything
42
else
foo
'''
options: ['none']
,
code: 'a += 1', options: ['before']
,
code: '1 + 1', options: ['none']
,
code: '1 + 1 + 1', options: ['none']
,
code: '1 || 1', options: ['none']
,
code: 'a += 1', options: ['none']
,
code: 'a', options: ['none']
,
code: '\n1 + 1', options: ['none']
,
code: '1 + 1\n', options: ['none']
]
invalid: [
# code: '1 \n || 1'
# output: '1 || \n 1'
# errors: [
# message: util.format AFTER_MSG, '||'
# type: 'LogicalExpression'
# line: 2
# column: 4
# ]
# ,
# code: '1 || \n 1'
# output: '1 \n || 1'
# options: ['before']
# errors: [
# message: util.format BEFORE_MSG, '||'
# type: 'LogicalExpression'
# line: 1
# column: 5
# ]
# ,
code: '1 +\n1'
# output: '1 +1'
options: ['none']
errors: [
message: util.format NONE_MSG, '+'
type: 'BinaryExpression'
line: 1
column: 4
]
,
code: 'f(1 +\n1)'
# output: 'f(1 +1)'
options: ['none']
errors: [
message: util.format NONE_MSG, '+'
type: 'BinaryExpression'
line: 1
column: 6
]
,
code: '1 || \n 1'
# output: '1 || 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '||'
type: 'LogicalExpression'
line: 1
column: 5
]
,
code: '1 or \n 1'
# output: '1 || 1'
options: ['none']
errors: [
message: util.format NONE_MSG, 'or'
type: 'LogicalExpression'
line: 1
column: 5
]
,
# ,
# code: '1 \n || 1'
# # output: '1 || 1'
# options: ['none']
# errors: [
# message: util.format NONE_MSG, '||'
# type: 'LogicalExpression'
# line: 2
# column: 4
# ]
code: 'a += \n1'
# output: 'a += 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '+='
type: 'AssignmentExpression'
line: 1
column: 5
]
,
code: 'a = \n1'
# output: 'a = 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '='
type: 'AssignmentExpression'
line: 1
column: 4
]
,
code: 'foo +=\n42\nbar -=\n12'
# output: 'foo +=42\nbar -=\n12\n+ 5'
options: ['after', {overrides: '+=': 'none'}]
errors: [
message: util.format NONE_MSG, '+='
type: 'AssignmentExpression'
line: 1
column: 7
]
# ,
# code: 'foo #comment\n&& bar'
# # output: 'foo && #comment\nbar'
# errors: [
# message: util.format AFTER_MSG, '&&'
# type: 'LogicalExpression'
# line: 2
# column: 3
# ]
# ,
# code: 'foo #comment\nand bar'
# # output: 'foo && #comment\nbar'
# errors: [
# message: util.format AFTER_MSG, 'and'
# type: 'LogicalExpression'
# line: 2
# column: 3
# ]
]
| true | ###*
# @fileoverview Operator linebreak rule tests
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
util = require 'util'
rule = require '../../rules/operator-linebreak'
path = require 'path'
{RuleTester} = require 'eslint'
# BAD_LN_BRK_MSG = "Bad line breaking before and after '%s'."
# BEFORE_MSG = "'%s' should be placed at the beginning of the line."
# AFTER_MSG = "'%s' should be placed at the end of the line."
NONE_MSG = "There should be no line break before or after '%s'."
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'operator-linebreak', rule,
valid: [
'1 + 1'
'1 + 1 + 1'
'1 +\n1'
'1 + (1 +\n1)'
'f(1 +\n1)'
'1 || 1'
'1 || \n1'
'1 ? 1'
'1 ? \n1'
'a += 1'
'a'
'o = \nsomething'
'o = \nsomething'
"'a\\\n' +\n 'c'"
"'a' +\n 'b\\\n'"
'(a\n) + b'
'''
answer =
if everything
42
else
foo
'''
,
code: '''
answer = if everything
42
else
foo
'''
options: ['none']
,
code: 'a += 1', options: ['before']
,
code: '1 + 1', options: ['none']
,
code: '1 + 1 + 1', options: ['none']
,
code: '1 || 1', options: ['none']
,
code: 'a += 1', options: ['none']
,
code: 'a', options: ['none']
,
code: '\n1 + 1', options: ['none']
,
code: '1 + 1\n', options: ['none']
]
invalid: [
# code: '1 \n || 1'
# output: '1 || \n 1'
# errors: [
# message: util.format AFTER_MSG, '||'
# type: 'LogicalExpression'
# line: 2
# column: 4
# ]
# ,
# code: '1 || \n 1'
# output: '1 \n || 1'
# options: ['before']
# errors: [
# message: util.format BEFORE_MSG, '||'
# type: 'LogicalExpression'
# line: 1
# column: 5
# ]
# ,
code: '1 +\n1'
# output: '1 +1'
options: ['none']
errors: [
message: util.format NONE_MSG, '+'
type: 'BinaryExpression'
line: 1
column: 4
]
,
code: 'f(1 +\n1)'
# output: 'f(1 +1)'
options: ['none']
errors: [
message: util.format NONE_MSG, '+'
type: 'BinaryExpression'
line: 1
column: 6
]
,
code: '1 || \n 1'
# output: '1 || 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '||'
type: 'LogicalExpression'
line: 1
column: 5
]
,
code: '1 or \n 1'
# output: '1 || 1'
options: ['none']
errors: [
message: util.format NONE_MSG, 'or'
type: 'LogicalExpression'
line: 1
column: 5
]
,
# ,
# code: '1 \n || 1'
# # output: '1 || 1'
# options: ['none']
# errors: [
# message: util.format NONE_MSG, '||'
# type: 'LogicalExpression'
# line: 2
# column: 4
# ]
code: 'a += \n1'
# output: 'a += 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '+='
type: 'AssignmentExpression'
line: 1
column: 5
]
,
code: 'a = \n1'
# output: 'a = 1'
options: ['none']
errors: [
message: util.format NONE_MSG, '='
type: 'AssignmentExpression'
line: 1
column: 4
]
,
code: 'foo +=\n42\nbar -=\n12'
# output: 'foo +=42\nbar -=\n12\n+ 5'
options: ['after', {overrides: '+=': 'none'}]
errors: [
message: util.format NONE_MSG, '+='
type: 'AssignmentExpression'
line: 1
column: 7
]
# ,
# code: 'foo #comment\n&& bar'
# # output: 'foo && #comment\nbar'
# errors: [
# message: util.format AFTER_MSG, '&&'
# type: 'LogicalExpression'
# line: 2
# column: 3
# ]
# ,
# code: 'foo #comment\nand bar'
# # output: 'foo && #comment\nbar'
# errors: [
# message: util.format AFTER_MSG, 'and'
# type: 'LogicalExpression'
# line: 2
# column: 3
# ]
]
|
[
{
"context": "# kent beck did this short test suite in making making coffee",
"end": 11,
"score": 0.9875175356864929,
"start": 2,
"tag": "NAME",
"value": "kent beck"
}
] | src/unit.coffee | temmihoo/raspiware | 0 | # kent beck did this short test suite in making making coffeescript
class unit
runCount: 0
failCount: 0
assert: (flag) ->
throw new Error if not flag
@runAll: (tests) ->
result = new unit
result.runTest test for test in tests
result
@run: (test) ->
unit.runAll [test]
runTest: (test) ->
this.runCount++
try
test()
catch
this.failCount++
# self-tests
thrown = false
result = new unit
try
unit.assert false
catch
thrown = true
throw new Error if not thrown
result = unit.run ->
result.assert result.runCount is 1
result.assert result.failCount is 0
result = unit.run -> throw new Error
result.assert result.runCount is 1
result.assert result.failCount is 1
noop = ->
result = unit.runAll [noop, noop]
result.assert result.runCount is 2
result.assert result.failCount is 0
oops = -> throw new Error
result = unit.runAll [oops, noop]
result.assert result.runCount is 2
result.assert result.failCount is 1
result = unit.runAll [->]
result.assert result.runCount is 1
result.assert result.failCount is 0
module.exports = unit
console.log 'unit.coffee says Success !!!'
| 129032 | # <NAME> did this short test suite in making making coffeescript
class unit
runCount: 0
failCount: 0
assert: (flag) ->
throw new Error if not flag
@runAll: (tests) ->
result = new unit
result.runTest test for test in tests
result
@run: (test) ->
unit.runAll [test]
runTest: (test) ->
this.runCount++
try
test()
catch
this.failCount++
# self-tests
thrown = false
result = new unit
try
unit.assert false
catch
thrown = true
throw new Error if not thrown
result = unit.run ->
result.assert result.runCount is 1
result.assert result.failCount is 0
result = unit.run -> throw new Error
result.assert result.runCount is 1
result.assert result.failCount is 1
noop = ->
result = unit.runAll [noop, noop]
result.assert result.runCount is 2
result.assert result.failCount is 0
oops = -> throw new Error
result = unit.runAll [oops, noop]
result.assert result.runCount is 2
result.assert result.failCount is 1
result = unit.runAll [->]
result.assert result.runCount is 1
result.assert result.failCount is 0
module.exports = unit
console.log 'unit.coffee says Success !!!'
| true | # PI:NAME:<NAME>END_PI did this short test suite in making making coffeescript
class unit
runCount: 0
failCount: 0
assert: (flag) ->
throw new Error if not flag
@runAll: (tests) ->
result = new unit
result.runTest test for test in tests
result
@run: (test) ->
unit.runAll [test]
runTest: (test) ->
this.runCount++
try
test()
catch
this.failCount++
# self-tests
thrown = false
result = new unit
try
unit.assert false
catch
thrown = true
throw new Error if not thrown
result = unit.run ->
result.assert result.runCount is 1
result.assert result.failCount is 0
result = unit.run -> throw new Error
result.assert result.runCount is 1
result.assert result.failCount is 1
noop = ->
result = unit.runAll [noop, noop]
result.assert result.runCount is 2
result.assert result.failCount is 0
oops = -> throw new Error
result = unit.runAll [oops, noop]
result.assert result.runCount is 2
result.assert result.failCount is 1
result = unit.runAll [->]
result.assert result.runCount is 1
result.assert result.failCount is 0
module.exports = unit
console.log 'unit.coffee says Success !!!'
|
[
{
"context": "s TeSSLaLinter\n constructor: ->\n @name = \"Example\"\n @scope = \"file\"\n @lintsOnChange = no\n",
"end": 316,
"score": 0.5607514381408691,
"start": 309,
"tag": "NAME",
"value": "Example"
}
] | lib/linter/tessla-linter.coffee | malteschmitz/tessla-atom2 | 0 | fs = require("fs-extra")
os = require("os")
path = require("path")
childProcess = require("child_process")
{TESSLA_CONTAINER_NAME} = require("../utils/constants")
{isSet} = require("../utils/utils")
Logger = require("../utils/logger")
module.exports=
class TeSSLaLinter
constructor: ->
@name = "Example"
@scope = "file"
@lintsOnChange = no
@grammarScopes = ["tessla"]
@lint = @onLint
onLint: (textEditor) =>
return new Promise (resolve, reject) =>
if not isSet(textEditor) or not isSet(textEditor.getPath())
return
args = ["exec", TESSLA_CONTAINER_NAME, "tessla", "#{textEditor.getTitle()}", "--verify-only"]
command = "docker #{args.join " "}"
Logger.log("Linter.onLint()", command)
editorPath = textEditor.getPath()
verifier = childProcess.spawn("docker", args)
errors = []
warnings = []
verifier.stdout.on "data", (data) ->
Logger.log("Linter.onLint()", "verifier stdout: " + data.toString())
verifier.stderr.on "data", (data) ->
Logger.log("Linter.onLint()", "verifier stderr: " + data.toString())
for line in data.toString().split("\n")
lineIsError = line.substr(0, 5) is "Error"
lineIsWarning = line.substr(0, 7) is "Warning"
errors.push(line) if line isnt "" and lineIsError
warnings.push(line) if line isnt "" and lineIsWarning
verifier.on "close", () ->
# get an array of items
items = []
# regex
regex = /(Error|Warning)\s*:\s*(\w[\w\.]*)\s*\(([\d]+)+\s*,\s*([\d]+)\s*-\s*([\d]+)\s*,\s*([\d]+)\)\s*:([\w\s]*)/gm
# parse error messages
for error in errors
while matches = regex.exec(error)
items.push(
severity: "error"
location:
file: editorPath
position: [[matches[3] - 1, matches[4] - 1], [matches[5] - 1, matches[6] - 1]]
excerpt: matches[7]
description: ""
)
# parse warning messages
for warning in warnings
while matches = regex.exec(warning)
items.push(
severity: "warning"
location:
file: editorPath
position: [[matches[3] - 1, matches[4] - 1], [matches[5] - 1, matches[6] - 1]]
excerpt: matches[7]
description: ""
)
# Do something sync
resolve(items)
| 50513 | fs = require("fs-extra")
os = require("os")
path = require("path")
childProcess = require("child_process")
{TESSLA_CONTAINER_NAME} = require("../utils/constants")
{isSet} = require("../utils/utils")
Logger = require("../utils/logger")
module.exports=
class TeSSLaLinter
constructor: ->
@name = "<NAME>"
@scope = "file"
@lintsOnChange = no
@grammarScopes = ["tessla"]
@lint = @onLint
onLint: (textEditor) =>
return new Promise (resolve, reject) =>
if not isSet(textEditor) or not isSet(textEditor.getPath())
return
args = ["exec", TESSLA_CONTAINER_NAME, "tessla", "#{textEditor.getTitle()}", "--verify-only"]
command = "docker #{args.join " "}"
Logger.log("Linter.onLint()", command)
editorPath = textEditor.getPath()
verifier = childProcess.spawn("docker", args)
errors = []
warnings = []
verifier.stdout.on "data", (data) ->
Logger.log("Linter.onLint()", "verifier stdout: " + data.toString())
verifier.stderr.on "data", (data) ->
Logger.log("Linter.onLint()", "verifier stderr: " + data.toString())
for line in data.toString().split("\n")
lineIsError = line.substr(0, 5) is "Error"
lineIsWarning = line.substr(0, 7) is "Warning"
errors.push(line) if line isnt "" and lineIsError
warnings.push(line) if line isnt "" and lineIsWarning
verifier.on "close", () ->
# get an array of items
items = []
# regex
regex = /(Error|Warning)\s*:\s*(\w[\w\.]*)\s*\(([\d]+)+\s*,\s*([\d]+)\s*-\s*([\d]+)\s*,\s*([\d]+)\)\s*:([\w\s]*)/gm
# parse error messages
for error in errors
while matches = regex.exec(error)
items.push(
severity: "error"
location:
file: editorPath
position: [[matches[3] - 1, matches[4] - 1], [matches[5] - 1, matches[6] - 1]]
excerpt: matches[7]
description: ""
)
# parse warning messages
for warning in warnings
while matches = regex.exec(warning)
items.push(
severity: "warning"
location:
file: editorPath
position: [[matches[3] - 1, matches[4] - 1], [matches[5] - 1, matches[6] - 1]]
excerpt: matches[7]
description: ""
)
# Do something sync
resolve(items)
| true | fs = require("fs-extra")
os = require("os")
path = require("path")
childProcess = require("child_process")
{TESSLA_CONTAINER_NAME} = require("../utils/constants")
{isSet} = require("../utils/utils")
Logger = require("../utils/logger")
module.exports=
class TeSSLaLinter
constructor: ->
@name = "PI:NAME:<NAME>END_PI"
@scope = "file"
@lintsOnChange = no
@grammarScopes = ["tessla"]
@lint = @onLint
onLint: (textEditor) =>
return new Promise (resolve, reject) =>
if not isSet(textEditor) or not isSet(textEditor.getPath())
return
args = ["exec", TESSLA_CONTAINER_NAME, "tessla", "#{textEditor.getTitle()}", "--verify-only"]
command = "docker #{args.join " "}"
Logger.log("Linter.onLint()", command)
editorPath = textEditor.getPath()
verifier = childProcess.spawn("docker", args)
errors = []
warnings = []
verifier.stdout.on "data", (data) ->
Logger.log("Linter.onLint()", "verifier stdout: " + data.toString())
verifier.stderr.on "data", (data) ->
Logger.log("Linter.onLint()", "verifier stderr: " + data.toString())
for line in data.toString().split("\n")
lineIsError = line.substr(0, 5) is "Error"
lineIsWarning = line.substr(0, 7) is "Warning"
errors.push(line) if line isnt "" and lineIsError
warnings.push(line) if line isnt "" and lineIsWarning
verifier.on "close", () ->
# get an array of items
items = []
# regex
regex = /(Error|Warning)\s*:\s*(\w[\w\.]*)\s*\(([\d]+)+\s*,\s*([\d]+)\s*-\s*([\d]+)\s*,\s*([\d]+)\)\s*:([\w\s]*)/gm
# parse error messages
for error in errors
while matches = regex.exec(error)
items.push(
severity: "error"
location:
file: editorPath
position: [[matches[3] - 1, matches[4] - 1], [matches[5] - 1, matches[6] - 1]]
excerpt: matches[7]
description: ""
)
# parse warning messages
for warning in warnings
while matches = regex.exec(warning)
items.push(
severity: "warning"
location:
file: editorPath
position: [[matches[3] - 1, matches[4] - 1], [matches[5] - 1, matches[6] - 1]]
excerpt: matches[7]
description: ""
)
# Do something sync
resolve(items)
|
[
{
"context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof",
"end": 23,
"score": 0.9998847842216492,
"start": 13,
"tag": "NAME",
"value": "Mat Groves"
},
{
"context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/c... | src/Coffixi/core/Point.coffee | namuol/Coffixi | 1 | ###*
@author Mat Groves http://matgroves.com/ @Doormat23
###
define 'Coffixi/core/Point', ->
###*
The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
@class Point
@constructor
@param x {Number} position of the point
@param y {Number} position of the point
###
class Point
constructor: (x, y) ->
###*
@property x
@type Number
@default 0
###
@x = x or 0
###*
@property y
@type Number
@default 0
###
@y = y or 0
###*
Creates a clone of this point
@method clone
@return {Point} a copy of the point
###
clone: ->
new Point(@x, @y)
return Point | 208819 | ###*
@author <NAME> http://matgroves.com/ @Doormat23
###
define 'Coffixi/core/Point', ->
###*
The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
@class Point
@constructor
@param x {Number} position of the point
@param y {Number} position of the point
###
class Point
constructor: (x, y) ->
###*
@property x
@type Number
@default 0
###
@x = x or 0
###*
@property y
@type Number
@default 0
###
@y = y or 0
###*
Creates a clone of this point
@method clone
@return {Point} a copy of the point
###
clone: ->
new Point(@x, @y)
return Point | true | ###*
@author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23
###
define 'Coffixi/core/Point', ->
###*
The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
@class Point
@constructor
@param x {Number} position of the point
@param y {Number} position of the point
###
class Point
constructor: (x, y) ->
###*
@property x
@type Number
@default 0
###
@x = x or 0
###*
@property y
@type Number
@default 0
###
@y = y or 0
###*
Creates a clone of this point
@method clone
@return {Point} a copy of the point
###
clone: ->
new Point(@x, @y)
return Point |
[
{
"context": "けてるので10回復する', ->\n user = new rpg.Actor(name:'user')\n target = new rpg.Actor(name:'target')\n ",
"end": 3380,
"score": 0.9797114729881287,
"start": 3376,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ので9回復して全快する', ->\n user = new rpg.Actor(name:'... | src/test/common/ItemUsableCounterTest.coffee | fukuyama/tmlib-rpg | 0 |
require('chai').should()
require('../../main/common/utils.coffee')
require('../../main/common/constants.coffee')
require('../../main/common/Battler.coffee')
require('../../main/common/Actor.coffee')
require('../../main/common/State.coffee')
require('../../main/common/Item.coffee')
require('../../main/common/ItemContainer.coffee')
require('../../main/common/UsableCounter.coffee')
require('../../main/common/Effect.coffee')
require('../../test/common/System.coffee')
{
SCOPE
USABLE
} = rpg.constants
TEST_STATES = {
'State1': new rpg.State({name:'State1'})
'State2': new rpg.State({name:'State2'})
}
describe 'rpg.UsableCounter', ->
item = null
log = null
rpg.system.temp = rpg.system.temp ? {}
rpg.system.db = rpg.system.db ? {}
describe '基本属性', ->
it 'アイテムの初期化', ->
item = new rpg.Item()
it '名前がある', ->
(item.name is null).should.equal false
item.name.should.equal ''
it '名前を付ける', ->
item.name = 'Name00'
(item.name is null).should.equal false
item.name.should.equal 'Name00'
it '価格がある', ->
(item.price is null).should.equal false
item.price.should.equal 1
it '価格を設定', ->
item.price = 100
item.price.should.equal 100
describe '使った回数で使えなくなるアイテム', ->
describe '1回使用するとなくなるアイテム', ->
it '作成', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '2回使用するとなくなるアイテム', ->
it '作成', ->
item = new rpg.Item(
lost:{max:2}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する1回目', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロストしない', ->
item.isLost().should.equal false
it 'アイテムを使用する2回目', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
it 'アイテムを使用する3回目。使用できない', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal false
describe '使用終了したアイテムを復活させる', ->
it '作成', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
it '復活させるとロストしない', ->
item.reuse()
item.isLost().should.equal false
describe '回復アイテムを使う(足りない場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '11ダメージを受けてるので10回復する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 11
target.hp.should.equal target.maxhp - 11
r = item.use user, target
r.should.equal true
target.hp.should.equal target.maxhp - 1
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(あふれる場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '9ダメージを受けてるので9回復して全快する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 9
target.hp.should.equal target.maxhp - 9
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 9
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(ぴったりの場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
name: '10up'
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '10ダメージを受けてるので10回復して全快する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.item.name.should.equal '10up'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 10
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(ダメージなしの場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1} # type: 'ok_count' (default)
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'ダメージが無い場合は、アイテムは使用されない', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
log = {}
r = item.use user, target, log
r.should.equal false
target.hp.should.equal target.maxhp
it '結果はなし', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 0
it 'アイテムはロストしない', ->
item.isLost().should.equal false
it 'HPを10回復する1度使えるアイテム(回復しなくてもロスト)', ->
item = new rpg.Item(
lost:{type:'count',max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'ダメージが無い場合は、アイテムは効果が無い', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
log = {}
r = item.use user, target, log
r.should.equal false
target.hp.should.equal target.maxhp
it '結果はなし', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 0
it 'アイテムはロストする', ->
item.isLost().should.equal true
describe 'MP回復アイテムを使う(足りない場合)', ->
it 'MPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{mp: 10}
]
)
item.isLost().should.equal false
it '11ダメージを受けてるので10回復する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.mp.should.equal target.maxmp
target.mp -= 11
target.mp.should.equal target.maxmp - 11
r = item.use user, target
r.should.equal true
target.mp.should.equal target.maxmp - 1
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe 'アイテムのスコープ', ->
describe 'デフォルトは味方単体', ->
it '初期化', ->
item = new rpg.Item()
it '確認', ->
item.scope.type.should.equal SCOPE.TYPE.FRIEND
item.scope.range.should.equal SCOPE.RANGE.ONE
describe '誰にでも使えるけど単体', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違う人を回復させる', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'b')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '複数の人を回復させようとすると使えない', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'b')
target.hp -= 10
targets.push target
r = item.use user, targets
r.should.equal false
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 10
describe '味方にしか使えない単体アイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違う人には使えない', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'b')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
r = item.use user, target
r.should.equal false
target.hp.should.equal target.maxhp - 10
it 'チームが同じ人には使える', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'a')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
r = item.use user, target
r.should.equal true
target.hp.should.equal target.maxhp
describe '誰にでも複数人に使えるアイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違っても複数の人を回復できる', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp
targets[1].hp.should.equal target.maxhp - 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 2
log.targets[0].name.should.equal 'target1'
log.targets[0].hp.should.equal 10
log.targets[1].name.should.equal 'target2'
log.targets[1].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
describe '味方の複数人に使えるアイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '対象に仲間が一人もいない場合は失敗する', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'b')
target.hp -= 11
targets.push target
r = item.use user, targets
r.should.equal false
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 11
it '対象に仲間が居る場合は敵が含まれていても使用される', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
target = new rpg.Actor(name:'target3',team:'b')
target.hp -= 9
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 1
targets[2].hp.should.equal target.maxhp - 9
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target2'
log.targets[0].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '全員味方なので全員が回復する', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'a')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
target = new rpg.Actor(name:'target3',team:'a')
target.hp -= 9
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp
targets[1].hp.should.equal target.maxhp - 1
targets[2].hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 3
log.targets[0].name.should.equal 'target1'
log.targets[0].hp.should.equal 10
log.targets[1].name.should.equal 'target2'
log.targets[1].hp.should.equal 10
log.targets[2].name.should.equal 'target3'
log.targets[2].hp.should.equal 9
it 'アイテムはロスト', ->
item.isLost().should.equal true
describe 'ステート変化', ->
describe 'ステート付加アイテム', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
item.isLost().should.equal false
it '使うとステートが追加される', ->
rpg.system.db.state = (name) -> TEST_STATES[name]
target = new rpg.Actor(name:'target1',team:'a')
target.states.length.should.equal 0
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'add'
log.targets[0].state.name.should.equal 'State1'
describe 'ステート解除アイテム', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'remove',name:'State1'}}
]
)
item.isLost().should.equal false
it '使うとステートが削除される(名前で指定)', ->
target = new rpg.Actor(name:'target1',team:'a')
target.addState(new rpg.State(name:'State1'))
target.states.length.should.equal 1
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 0
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'remove'
log.targets[0].state.name.should.equal 'State1'
describe 'ステート解除アイテム(複数のステートから1つ解除)', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'remove',name:'State2'}}
]
)
item.isLost().should.equal false
it '使うとステートが削除される(名前で指定)', ->
target = new rpg.Actor(name:'target1',team:'a')
target.addState(new rpg.State(name:'State1'))
target.states.length.should.equal 1
target.addState(new rpg.State(name:'State2'))
target.states.length.should.equal 2
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'remove'
log.targets[0].state.name.should.equal 'State2'
| 183153 |
require('chai').should()
require('../../main/common/utils.coffee')
require('../../main/common/constants.coffee')
require('../../main/common/Battler.coffee')
require('../../main/common/Actor.coffee')
require('../../main/common/State.coffee')
require('../../main/common/Item.coffee')
require('../../main/common/ItemContainer.coffee')
require('../../main/common/UsableCounter.coffee')
require('../../main/common/Effect.coffee')
require('../../test/common/System.coffee')
{
SCOPE
USABLE
} = rpg.constants
TEST_STATES = {
'State1': new rpg.State({name:'State1'})
'State2': new rpg.State({name:'State2'})
}
describe 'rpg.UsableCounter', ->
item = null
log = null
rpg.system.temp = rpg.system.temp ? {}
rpg.system.db = rpg.system.db ? {}
describe '基本属性', ->
it 'アイテムの初期化', ->
item = new rpg.Item()
it '名前がある', ->
(item.name is null).should.equal false
item.name.should.equal ''
it '名前を付ける', ->
item.name = 'Name00'
(item.name is null).should.equal false
item.name.should.equal 'Name00'
it '価格がある', ->
(item.price is null).should.equal false
item.price.should.equal 1
it '価格を設定', ->
item.price = 100
item.price.should.equal 100
describe '使った回数で使えなくなるアイテム', ->
describe '1回使用するとなくなるアイテム', ->
it '作成', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '2回使用するとなくなるアイテム', ->
it '作成', ->
item = new rpg.Item(
lost:{max:2}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する1回目', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロストしない', ->
item.isLost().should.equal false
it 'アイテムを使用する2回目', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
it 'アイテムを使用する3回目。使用できない', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal false
describe '使用終了したアイテムを復活させる', ->
it '作成', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
it '復活させるとロストしない', ->
item.reuse()
item.isLost().should.equal false
describe '回復アイテムを使う(足りない場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '11ダメージを受けてるので10回復する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 11
target.hp.should.equal target.maxhp - 11
r = item.use user, target
r.should.equal true
target.hp.should.equal target.maxhp - 1
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(あふれる場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '9ダメージを受けてるので9回復して全快する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 9
target.hp.should.equal target.maxhp - 9
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 9
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(ぴったりの場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
name: '<NAME>0up'
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '10ダメージを受けてるので10回復して全快する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.item.name.should.equal '10up'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 10
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(ダメージなしの場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1} # type: 'ok_count' (default)
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'ダメージが無い場合は、アイテムは使用されない', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
log = {}
r = item.use user, target, log
r.should.equal false
target.hp.should.equal target.maxhp
it '結果はなし', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 0
it 'アイテムはロストしない', ->
item.isLost().should.equal false
it 'HPを10回復する1度使えるアイテム(回復しなくてもロスト)', ->
item = new rpg.Item(
lost:{type:'count',max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'ダメージが無い場合は、アイテムは効果が無い', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
log = {}
r = item.use user, target, log
r.should.equal false
target.hp.should.equal target.maxhp
it '結果はなし', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 0
it 'アイテムはロストする', ->
item.isLost().should.equal true
describe 'MP回復アイテムを使う(足りない場合)', ->
it 'MPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{mp: 10}
]
)
item.isLost().should.equal false
it '11ダメージを受けてるので10回復する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.mp.should.equal target.maxmp
target.mp -= 11
target.mp.should.equal target.maxmp - 11
r = item.use user, target
r.should.equal true
target.mp.should.equal target.maxmp - 1
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe 'アイテムのスコープ', ->
describe 'デフォルトは味方単体', ->
it '初期化', ->
item = new rpg.Item()
it '確認', ->
item.scope.type.should.equal SCOPE.TYPE.FRIEND
item.scope.range.should.equal SCOPE.RANGE.ONE
describe '誰にでも使えるけど単体', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違う人を回復させる', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'b')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '複数の人を回復させようとすると使えない', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'b')
target.hp -= 10
targets.push target
r = item.use user, targets
r.should.equal false
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 10
describe '味方にしか使えない単体アイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違う人には使えない', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'b')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
r = item.use user, target
r.should.equal false
target.hp.should.equal target.maxhp - 10
it 'チームが同じ人には使える', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'a')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
r = item.use user, target
r.should.equal true
target.hp.should.equal target.maxhp
describe '誰にでも複数人に使えるアイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違っても複数の人を回復できる', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp
targets[1].hp.should.equal target.maxhp - 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 2
log.targets[0].name.should.equal 'target1'
log.targets[0].hp.should.equal 10
log.targets[1].name.should.equal 'target2'
log.targets[1].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
describe '味方の複数人に使えるアイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '対象に仲間が一人もいない場合は失敗する', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'b')
target.hp -= 11
targets.push target
r = item.use user, targets
r.should.equal false
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 11
it '対象に仲間が居る場合は敵が含まれていても使用される', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
target = new rpg.Actor(name:'target3',team:'b')
target.hp -= 9
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 1
targets[2].hp.should.equal target.maxhp - 9
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target2'
log.targets[0].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '全員味方なので全員が回復する', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'a')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
target = new rpg.Actor(name:'target3',team:'a')
target.hp -= 9
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp
targets[1].hp.should.equal target.maxhp - 1
targets[2].hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 3
log.targets[0].name.should.equal 'target1'
log.targets[0].hp.should.equal 10
log.targets[1].name.should.equal 'target2'
log.targets[1].hp.should.equal 10
log.targets[2].name.should.equal 'target3'
log.targets[2].hp.should.equal 9
it 'アイテムはロスト', ->
item.isLost().should.equal true
describe 'ステート変化', ->
describe 'ステート付加アイテム', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
item.isLost().should.equal false
it '使うとステートが追加される', ->
rpg.system.db.state = (name) -> TEST_STATES[name]
target = new rpg.Actor(name:'target1',team:'a')
target.states.length.should.equal 0
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'add'
log.targets[0].state.name.should.equal 'State1'
describe 'ステート解除アイテム', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'remove',name:'State1'}}
]
)
item.isLost().should.equal false
it '使うとステートが削除される(名前で指定)', ->
target = new rpg.Actor(name:'target1',team:'a')
target.addState(new rpg.State(name:'State1'))
target.states.length.should.equal 1
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 0
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'remove'
log.targets[0].state.name.should.equal 'State1'
describe 'ステート解除アイテム(複数のステートから1つ解除)', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'remove',name:'State2'}}
]
)
item.isLost().should.equal false
it '使うとステートが削除される(名前で指定)', ->
target = new rpg.Actor(name:'target1',team:'a')
target.addState(new rpg.State(name:'State1'))
target.states.length.should.equal 1
target.addState(new rpg.State(name:'State2'))
target.states.length.should.equal 2
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'remove'
log.targets[0].state.name.should.equal 'State2'
| true |
require('chai').should()
require('../../main/common/utils.coffee')
require('../../main/common/constants.coffee')
require('../../main/common/Battler.coffee')
require('../../main/common/Actor.coffee')
require('../../main/common/State.coffee')
require('../../main/common/Item.coffee')
require('../../main/common/ItemContainer.coffee')
require('../../main/common/UsableCounter.coffee')
require('../../main/common/Effect.coffee')
require('../../test/common/System.coffee')
{
SCOPE
USABLE
} = rpg.constants
TEST_STATES = {
'State1': new rpg.State({name:'State1'})
'State2': new rpg.State({name:'State2'})
}
describe 'rpg.UsableCounter', ->
item = null
log = null
rpg.system.temp = rpg.system.temp ? {}
rpg.system.db = rpg.system.db ? {}
describe '基本属性', ->
it 'アイテムの初期化', ->
item = new rpg.Item()
it '名前がある', ->
(item.name is null).should.equal false
item.name.should.equal ''
it '名前を付ける', ->
item.name = 'Name00'
(item.name is null).should.equal false
item.name.should.equal 'Name00'
it '価格がある', ->
(item.price is null).should.equal false
item.price.should.equal 1
it '価格を設定', ->
item.price = 100
item.price.should.equal 100
describe '使った回数で使えなくなるアイテム', ->
describe '1回使用するとなくなるアイテム', ->
it '作成', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '2回使用するとなくなるアイテム', ->
it '作成', ->
item = new rpg.Item(
lost:{max:2}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する1回目', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロストしない', ->
item.isLost().should.equal false
it 'アイテムを使用する2回目', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
it 'アイテムを使用する3回目。使用できない', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal false
describe '使用終了したアイテムを復活させる', ->
it '作成', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
)
item.effectApply = () -> true
item.isLost().should.equal false
it 'アイテムを使用する', ->
user = new rpg.Actor()
target = new rpg.Actor()
r = item.use user, target
r.should.equal true
it 'アイテムがロスト', ->
item.isLost().should.equal true
it '復活させるとロストしない', ->
item.reuse()
item.isLost().should.equal false
describe '回復アイテムを使う(足りない場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '11ダメージを受けてるので10回復する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 11
target.hp.should.equal target.maxhp - 11
r = item.use user, target
r.should.equal true
target.hp.should.equal target.maxhp - 1
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(あふれる場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '9ダメージを受けてるので9回復して全快する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 9
target.hp.should.equal target.maxhp - 9
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 9
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(ぴったりの場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
name: 'PI:NAME:<NAME>END_PI0up'
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '10ダメージを受けてるので10回復して全快する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.item.name.should.equal '10up'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 10
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe '回復アイテムを使う(ダメージなしの場合)', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1} # type: 'ok_count' (default)
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'ダメージが無い場合は、アイテムは使用されない', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
log = {}
r = item.use user, target, log
r.should.equal false
target.hp.should.equal target.maxhp
it '結果はなし', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 0
it 'アイテムはロストしない', ->
item.isLost().should.equal false
it 'HPを10回復する1度使えるアイテム(回復しなくてもロスト)', ->
item = new rpg.Item(
lost:{type:'count',max:1}
usable: USABLE.ALL
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'ダメージが無い場合は、アイテムは効果が無い', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.hp.should.equal target.maxhp
log = {}
r = item.use user, target, log
r.should.equal false
target.hp.should.equal target.maxhp
it '結果はなし', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 0
it 'アイテムはロストする', ->
item.isLost().should.equal true
describe 'MP回復アイテムを使う(足りない場合)', ->
it 'MPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
target:
effects:[
{mp: 10}
]
)
item.isLost().should.equal false
it '11ダメージを受けてるので10回復する', ->
user = new rpg.Actor(name:'user')
target = new rpg.Actor(name:'target')
target.mp.should.equal target.maxmp
target.mp -= 11
target.mp.should.equal target.maxmp - 11
r = item.use user, target
r.should.equal true
target.mp.should.equal target.maxmp - 1
it 'アイテムがロスト', ->
item.isLost().should.equal true
describe 'アイテムのスコープ', ->
describe 'デフォルトは味方単体', ->
it '初期化', ->
item = new rpg.Item()
it '確認', ->
item.scope.type.should.equal SCOPE.TYPE.FRIEND
item.scope.range.should.equal SCOPE.RANGE.ONE
describe '誰にでも使えるけど単体', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違う人を回復させる', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'b')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
log = {}
r = item.use user, target, log
r.should.equal true
target.hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target'
log.targets[0].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '複数の人を回復させようとすると使えない', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'b')
target.hp -= 10
targets.push target
r = item.use user, targets
r.should.equal false
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 10
describe '味方にしか使えない単体アイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違う人には使えない', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'b')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
r = item.use user, target
r.should.equal false
target.hp.should.equal target.maxhp - 10
it 'チームが同じ人には使える', ->
user = new rpg.Actor(name:'user',team:'a')
target = new rpg.Actor(name:'target',team:'a')
target.hp.should.equal target.maxhp
target.hp -= 10
target.hp.should.equal target.maxhp - 10
r = item.use user, target
r.should.equal true
target.hp.should.equal target.maxhp
describe '誰にでも複数人に使えるアイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.ALL
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it 'チームが違っても複数の人を回復できる', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp
targets[1].hp.should.equal target.maxhp - 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 2
log.targets[0].name.should.equal 'target1'
log.targets[0].hp.should.equal 10
log.targets[1].name.should.equal 'target2'
log.targets[1].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
describe '味方の複数人に使えるアイテム', ->
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '対象に仲間が一人もいない場合は失敗する', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'b')
target.hp -= 11
targets.push target
r = item.use user, targets
r.should.equal false
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 11
it '対象に仲間が居る場合は敵が含まれていても使用される', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'b')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
target = new rpg.Actor(name:'target3',team:'b')
target.hp -= 9
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp - 10
targets[1].hp.should.equal target.maxhp - 1
targets[2].hp.should.equal target.maxhp - 9
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target2'
log.targets[0].hp.should.equal 10
it 'アイテムはロスト', ->
item.isLost().should.equal true
it 'HPを10回復する1度使えるアイテム', ->
item = new rpg.Item(
lost:{max:1}
usable: USABLE.ALL
scope:{
type: SCOPE.TYPE.FRIEND
range: SCOPE.RANGE.MULTI
}
target:
effects:[
{hp: 10}
]
)
item.isLost().should.equal false
it '全員味方なので全員が回復する', ->
user = new rpg.Actor(name:'user',team:'a')
targets = []
target = new rpg.Actor(name:'target1',team:'a')
target.hp -= 10
targets.push target
target = new rpg.Actor(name:'target2',team:'a')
target.hp -= 11
targets.push target
target = new rpg.Actor(name:'target3',team:'a')
target.hp -= 9
targets.push target
log = {}
r = item.use user, targets, log
r.should.equal true
targets[0].hp.should.equal target.maxhp
targets[1].hp.should.equal target.maxhp - 1
targets[2].hp.should.equal target.maxhp
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 3
log.targets[0].name.should.equal 'target1'
log.targets[0].hp.should.equal 10
log.targets[1].name.should.equal 'target2'
log.targets[1].hp.should.equal 10
log.targets[2].name.should.equal 'target3'
log.targets[2].hp.should.equal 9
it 'アイテムはロスト', ->
item.isLost().should.equal true
describe 'ステート変化', ->
describe 'ステート付加アイテム', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
item.isLost().should.equal false
it '使うとステートが追加される', ->
rpg.system.db.state = (name) -> TEST_STATES[name]
target = new rpg.Actor(name:'target1',team:'a')
target.states.length.should.equal 0
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'add'
log.targets[0].state.name.should.equal 'State1'
describe 'ステート解除アイテム', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'remove',name:'State1'}}
]
)
item.isLost().should.equal false
it '使うとステートが削除される(名前で指定)', ->
target = new rpg.Actor(name:'target1',team:'a')
target.addState(new rpg.State(name:'State1'))
target.states.length.should.equal 1
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 0
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'remove'
log.targets[0].state.name.should.equal 'State1'
describe 'ステート解除アイテム(複数のステートから1つ解除)', ->
it '作成', ->
item = new rpg.Item(
usable: USABLE.ALL
target:
effects:[
{state: {type:'remove',name:'State2'}}
]
)
item.isLost().should.equal false
it '使うとステートが削除される(名前で指定)', ->
target = new rpg.Actor(name:'target1',team:'a')
target.addState(new rpg.State(name:'State1'))
target.states.length.should.equal 1
target.addState(new rpg.State(name:'State2'))
target.states.length.should.equal 2
user = new rpg.Actor(name:'user',team:'a')
log = {}
r = item.use user, target, log
r.should.equal true
target.states.length.should.equal 1
it '結果確認', ->
log.user.name.should.equal 'user'
log.targets.length.should.equal 1
log.targets[0].name.should.equal 'target1'
log.targets[0].state.type.should.equal 'remove'
log.targets[0].state.name.should.equal 'State2'
|
[
{
"context": "SOFTWARE.\n\nangular-google-maps\nhttps://github.com/nlaplante/angular-google-maps\n\n@authors Bruno Queiroz, crea",
"end": 1154,
"score": 0.6389955282211304,
"start": 1145,
"tag": "USERNAME",
"value": "nlaplante"
},
{
"context": "github.com/nlaplante/angular-google-map... | bower_components/angular-google-maps-init/src/coffee/directives/label.coffee | aditioan/naturapass | 1 | ###
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
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.
angular-google-maps
https://github.com/nlaplante/angular-google-maps
@authors Bruno Queiroz, creativelikeadog@gmail.com
###
###
Marker label directive
This directive is used to create a marker label on an existing map.
{attribute content required} content of the label
{attribute anchor required} string that contains the x and y point position of the label
{attribute class optional} class to DOM object
{attribute style optional} style for the label
###
###
Basic Directive api for a label. Basic in the sense that this directive contains 1:1 on scope and model.
Thus there will be one html element per marker within the directive.
###
angular.module("google-maps")
.directive "markerLabel", ["$timeout", "ILabel", "MarkerLabelChildModel", "GmapUtil", "nggmap-PropertyAction"
($timeout, ILabel, MarkerLabelChildModel, GmapUtil, PropertyAction) ->
class Label extends ILabel
constructor: ($timeout) ->
super($timeout)
self = @
@require = '^marker'
@template = '<span class="angular-google-maps-marker-label" ng-transclude></span>'
@$log.info(@)
link: (scope, element, attrs, ctrl) =>
markerScope = ctrl.getScope()
if markerScope
markerScope.deferred.promise.then =>
@init markerScope, scope
init: (markerScope, scope)=>
label = null
createLabel = ->
unless label
label = new MarkerLabelChildModel markerScope.gMarker, scope, markerScope.map
isFirstSet = true
markerScope.$watch 'gMarker', (newVal, oldVal) ->
if markerScope.gMarker?
contentAction = new PropertyAction (newVal) ->
createLabel()
if scope.labelContent
label?.setOption 'labelContent', scope.labelContent
, isFirstSet
anchorAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelAnchor', scope.labelAnchor
, isFirstSet
classAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelClass', scope.labelClass
, isFirstSet
styleAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelStyle', scope.labelStyle
, isFirstSet
scope.$watch 'labelContent', contentAction.sic
scope.$watch 'labelAnchor', anchorAction.sic
scope.$watch 'labelClass', classAction.sic
scope.$watch 'labelStyle', styleAction.sic
isFirstSet = false
scope.$on '$destroy', ->
label?.destroy()
new Label($timeout)
] | 141922 | ###
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
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.
angular-google-maps
https://github.com/nlaplante/angular-google-maps
@authors <NAME>, <EMAIL>
###
###
Marker label directive
This directive is used to create a marker label on an existing map.
{attribute content required} content of the label
{attribute anchor required} string that contains the x and y point position of the label
{attribute class optional} class to DOM object
{attribute style optional} style for the label
###
###
Basic Directive api for a label. Basic in the sense that this directive contains 1:1 on scope and model.
Thus there will be one html element per marker within the directive.
###
angular.module("google-maps")
.directive "markerLabel", ["$timeout", "ILabel", "MarkerLabelChildModel", "GmapUtil", "nggmap-PropertyAction"
($timeout, ILabel, MarkerLabelChildModel, GmapUtil, PropertyAction) ->
class Label extends ILabel
constructor: ($timeout) ->
super($timeout)
self = @
@require = '^marker'
@template = '<span class="angular-google-maps-marker-label" ng-transclude></span>'
@$log.info(@)
link: (scope, element, attrs, ctrl) =>
markerScope = ctrl.getScope()
if markerScope
markerScope.deferred.promise.then =>
@init markerScope, scope
init: (markerScope, scope)=>
label = null
createLabel = ->
unless label
label = new MarkerLabelChildModel markerScope.gMarker, scope, markerScope.map
isFirstSet = true
markerScope.$watch 'gMarker', (newVal, oldVal) ->
if markerScope.gMarker?
contentAction = new PropertyAction (newVal) ->
createLabel()
if scope.labelContent
label?.setOption 'labelContent', scope.labelContent
, isFirstSet
anchorAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelAnchor', scope.labelAnchor
, isFirstSet
classAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelClass', scope.labelClass
, isFirstSet
styleAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelStyle', scope.labelStyle
, isFirstSet
scope.$watch 'labelContent', contentAction.sic
scope.$watch 'labelAnchor', anchorAction.sic
scope.$watch 'labelClass', classAction.sic
scope.$watch 'labelStyle', styleAction.sic
isFirstSet = false
scope.$on '$destroy', ->
label?.destroy()
new Label($timeout)
] | true | ###
!
The MIT License
Copyright (c) 2010-2013 Google, Inc. http://angularjs.org
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.
angular-google-maps
https://github.com/nlaplante/angular-google-maps
@authors PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI
###
###
Marker label directive
This directive is used to create a marker label on an existing map.
{attribute content required} content of the label
{attribute anchor required} string that contains the x and y point position of the label
{attribute class optional} class to DOM object
{attribute style optional} style for the label
###
###
Basic Directive api for a label. Basic in the sense that this directive contains 1:1 on scope and model.
Thus there will be one html element per marker within the directive.
###
angular.module("google-maps")
.directive "markerLabel", ["$timeout", "ILabel", "MarkerLabelChildModel", "GmapUtil", "nggmap-PropertyAction"
($timeout, ILabel, MarkerLabelChildModel, GmapUtil, PropertyAction) ->
class Label extends ILabel
constructor: ($timeout) ->
super($timeout)
self = @
@require = '^marker'
@template = '<span class="angular-google-maps-marker-label" ng-transclude></span>'
@$log.info(@)
link: (scope, element, attrs, ctrl) =>
markerScope = ctrl.getScope()
if markerScope
markerScope.deferred.promise.then =>
@init markerScope, scope
init: (markerScope, scope)=>
label = null
createLabel = ->
unless label
label = new MarkerLabelChildModel markerScope.gMarker, scope, markerScope.map
isFirstSet = true
markerScope.$watch 'gMarker', (newVal, oldVal) ->
if markerScope.gMarker?
contentAction = new PropertyAction (newVal) ->
createLabel()
if scope.labelContent
label?.setOption 'labelContent', scope.labelContent
, isFirstSet
anchorAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelAnchor', scope.labelAnchor
, isFirstSet
classAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelClass', scope.labelClass
, isFirstSet
styleAction = new PropertyAction (newVal) ->
createLabel()
label?.setOption 'labelStyle', scope.labelStyle
, isFirstSet
scope.$watch 'labelContent', contentAction.sic
scope.$watch 'labelAnchor', anchorAction.sic
scope.$watch 'labelClass', classAction.sic
scope.$watch 'labelStyle', styleAction.sic
isFirstSet = false
scope.$on '$destroy', ->
label?.destroy()
new Label($timeout)
] |
[
{
"context": "tion = {}\nconfiguration[nerfed + \"_authToken\"] = \"not-bad-meaning-bad-but-bad-meaning-wombat\"\nclient = common.freshClient(configuration)\ncache",
"end": 239,
"score": 0.9988623261451721,
"start": 197,
"tag": "PASSWORD",
"value": "not-bad-meaning-bad-but-bad-meaning-wombat... | deps/npm/node_modules/npm-registry-client/test/deprecate.coffee | lxe/io.coffee | 0 | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "_authToken"] = "not-bad-meaning-bad-but-bad-meaning-wombat"
client = common.freshClient(configuration)
cache = require("./fixtures/underscore/cache.json")
VERSION = "1.3.2"
MESSAGE = "uhhh"
tap.test "deprecate a package", (t) ->
server.expect "GET", "/underscore?write=true", (req, res) ->
t.equal req.method, "GET"
res.json cache
return
server.expect "PUT", "/underscore", (req, res) ->
t.equal req.method, "PUT"
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
updated = JSON.parse(b)
undeprecated = [
"1.0.3"
"1.0.4"
"1.1.0"
"1.1.1"
"1.1.2"
"1.1.3"
"1.1.4"
"1.1.5"
"1.1.6"
"1.1.7"
"1.2.0"
"1.2.1"
"1.2.2"
"1.2.3"
"1.2.4"
"1.3.0"
"1.3.1"
"1.3.3"
]
i = 0
while i < undeprecated.length
current = undeprecated[i]
t.notEqual updated.versions[current].deprecated, MESSAGE, current + " not deprecated"
i++
t.equal updated.versions[VERSION].deprecated, MESSAGE, VERSION + " deprecated"
res.statusCode = 201
res.json deprecated: true
return
return
client.deprecate common.registry + "/underscore", VERSION, MESSAGE, (er, data) ->
t.ifError er
t.ok data.deprecated, "was deprecated"
t.end()
return
return
| 100197 | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "_authToken"] = "<PASSWORD>"
client = common.freshClient(configuration)
cache = require("./fixtures/underscore/cache.json")
VERSION = "1.3.2"
MESSAGE = "uhhh"
tap.test "deprecate a package", (t) ->
server.expect "GET", "/underscore?write=true", (req, res) ->
t.equal req.method, "GET"
res.json cache
return
server.expect "PUT", "/underscore", (req, res) ->
t.equal req.method, "PUT"
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
updated = JSON.parse(b)
undeprecated = [
"1.0.3"
"1.0.4"
"1.1.0"
"1.1.1"
"1.1.2"
"1.1.3"
"1.1.4"
"1.1.5"
"1.1.6"
"1.1.7"
"1.2.0"
"1.2.1"
"1.2.2"
"1.2.3"
"1.2.4"
"1.3.0"
"1.3.1"
"1.3.3"
]
i = 0
while i < undeprecated.length
current = undeprecated[i]
t.notEqual updated.versions[current].deprecated, MESSAGE, current + " not deprecated"
i++
t.equal updated.versions[VERSION].deprecated, MESSAGE, VERSION + " deprecated"
res.statusCode = 201
res.json deprecated: true
return
return
client.deprecate common.registry + "/underscore", VERSION, MESSAGE, (er, data) ->
t.ifError er
t.ok data.deprecated, "was deprecated"
t.end()
return
return
| true | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "_authToken"] = "PI:PASSWORD:<PASSWORD>END_PI"
client = common.freshClient(configuration)
cache = require("./fixtures/underscore/cache.json")
VERSION = "1.3.2"
MESSAGE = "uhhh"
tap.test "deprecate a package", (t) ->
server.expect "GET", "/underscore?write=true", (req, res) ->
t.equal req.method, "GET"
res.json cache
return
server.expect "PUT", "/underscore", (req, res) ->
t.equal req.method, "PUT"
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
updated = JSON.parse(b)
undeprecated = [
"1.0.3"
"1.0.4"
"1.1.0"
"1.1.1"
"1.1.2"
"1.1.3"
"1.1.4"
"1.1.5"
"1.1.6"
"1.1.7"
"1.2.0"
"1.2.1"
"1.2.2"
"1.2.3"
"1.2.4"
"1.3.0"
"1.3.1"
"1.3.3"
]
i = 0
while i < undeprecated.length
current = undeprecated[i]
t.notEqual updated.versions[current].deprecated, MESSAGE, current + " not deprecated"
i++
t.equal updated.versions[VERSION].deprecated, MESSAGE, VERSION + " deprecated"
res.statusCode = 201
res.json deprecated: true
return
return
client.deprecate common.registry + "/underscore", VERSION, MESSAGE, (er, data) ->
t.ifError er
t.ok data.deprecated, "was deprecated"
t.end()
return
return
|
[
{
"context": "getDefaultProjectLogo: (slug, id) ->\n key = \"#{slug}-#{id}\"\n idx = murmurhash3_32_gc(key, 42) %% @.log",
"end": 1560,
"score": 0.9987450242042542,
"start": 1545,
"tag": "KEY",
"value": "\"#{slug}-#{id}\""
}
] | app/modules/services/project-logo.service.coffee | threefoldtech/Threefold-Circles-front | 0 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: services/project-logo.service.coffee
###
class ProjectLogoService
constructor: () ->
IMAGES = [
"/#{window._version}/images/project-logos/project-logo-01.png"
"/#{window._version}/images/project-logos/project-logo-02.png"
"/#{window._version}/images/project-logos/project-logo-03.png"
"/#{window._version}/images/project-logos/project-logo-04.png"
"/#{window._version}/images/project-logos/project-logo-05.png"
]
COLORS = [
"rgba( 153, 214, 220, 1 )"
"rgba( 213, 156, 156, 1 )"
"rgba( 214, 161, 212, 1 )"
"rgba( 164, 162, 219, 1 )"
"rgba( 152, 224, 168, 1 )"
]
@.logos = _.cartesianProduct(IMAGES, COLORS)
getDefaultProjectLogo: (slug, id) ->
key = "#{slug}-#{id}"
idx = murmurhash3_32_gc(key, 42) %% @.logos.length
logo = @.logos[idx]
return { src: logo[0], color: logo[1] }
angular.module("taigaCommon").service("tgProjectLogoService", ProjectLogoService)
| 140241 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: services/project-logo.service.coffee
###
class ProjectLogoService
constructor: () ->
IMAGES = [
"/#{window._version}/images/project-logos/project-logo-01.png"
"/#{window._version}/images/project-logos/project-logo-02.png"
"/#{window._version}/images/project-logos/project-logo-03.png"
"/#{window._version}/images/project-logos/project-logo-04.png"
"/#{window._version}/images/project-logos/project-logo-05.png"
]
COLORS = [
"rgba( 153, 214, 220, 1 )"
"rgba( 213, 156, 156, 1 )"
"rgba( 214, 161, 212, 1 )"
"rgba( 164, 162, 219, 1 )"
"rgba( 152, 224, 168, 1 )"
]
@.logos = _.cartesianProduct(IMAGES, COLORS)
getDefaultProjectLogo: (slug, id) ->
key = <KEY>
idx = murmurhash3_32_gc(key, 42) %% @.logos.length
logo = @.logos[idx]
return { src: logo[0], color: logo[1] }
angular.module("taigaCommon").service("tgProjectLogoService", ProjectLogoService)
| true | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: services/project-logo.service.coffee
###
class ProjectLogoService
constructor: () ->
IMAGES = [
"/#{window._version}/images/project-logos/project-logo-01.png"
"/#{window._version}/images/project-logos/project-logo-02.png"
"/#{window._version}/images/project-logos/project-logo-03.png"
"/#{window._version}/images/project-logos/project-logo-04.png"
"/#{window._version}/images/project-logos/project-logo-05.png"
]
COLORS = [
"rgba( 153, 214, 220, 1 )"
"rgba( 213, 156, 156, 1 )"
"rgba( 214, 161, 212, 1 )"
"rgba( 164, 162, 219, 1 )"
"rgba( 152, 224, 168, 1 )"
]
@.logos = _.cartesianProduct(IMAGES, COLORS)
getDefaultProjectLogo: (slug, id) ->
key = PI:KEY:<KEY>END_PI
idx = murmurhash3_32_gc(key, 42) %% @.logos.length
logo = @.logos[idx]
return { src: logo[0], color: logo[1] }
angular.module("taigaCommon").service("tgProjectLogoService", ProjectLogoService)
|
[
{
"context": "iq) ->\n (expect iq.attr \"to\").toEqual \"User@service.example.com\"\n (expect iq.attr \"type\").toEqual \"set",
"end": 2431,
"score": 0.9985781311988831,
"start": 2407,
"tag": "EMAIL",
"value": "User@service.example.com"
},
{
"context": "toEqual ... | joap/spec/strophe.joap.spec.coffee | calendar42/strophejs-plugins | 0 | fs = require('fs')
jsdom = require('jsdom')
jquery = fs.readFileSync("./lib/jquery.js").toString()
strophe = fs.readFileSync("./lib/strophe.js").toString()
rpc = fs.readFileSync("./lib/strophe.rpc.js").toString()
joap = fs.readFileSync("./strophe.joap.js").toString()
describe "strophe.joap loading", ->
it "loads the strophe library", ->
window = null
Strophe = null
$ = null
$iq = null
mockConnection = ->
c = new Strophe.Connection()
c.authenticated = true
c.jid = 'n@d/r2'
c._processRequest = ->
c._changeConnectStatus Strophe.Status.CONNECTED
c
str = (builder) ->
if builder.tree
return Strophe.serialize(builder.tree())
Strophe.serialize(builder)
spyon = (obj, method, cb) ->
spyOn(obj, method).andCallFake (res)->
cb.call @, ($ str res)
receive = (c,req) ->
c._dataRecv(createRequest(req))
expect(c.send).toHaveBeenCalled()
createRequest = (iq) ->
iq = iq.tree() if typeof iq.tree is "function"
req = new Strophe.Request(iq, ->)
req.getResponse = ->
env = new Strophe.Builder('env', {type: 'mock'}).tree()
env.appendChild(iq)
env
req
jsdom.env
html: 'http://news.ycombinator.com/'
src: [ jquery, strophe, rpc, joap ]
done: (errors, w) ->
Strophe = w.Strophe
$ = w.jQuery
$iq = w.$iq
window = w
waitsFor -> !!window
runs ->
(expect window.Strophe).toBeDefined()
(expect window.$).toBeDefined()
(expect window.jQuery).toBeDefined()
describe "strophe.joap plugin", ->
beforeEach ->
@c = mockConnection()
@successHandler = jasmine.createSpy "successHandler"
@errorHandler = jasmine.createSpy "errorHandler"
it "provides connection.joap", ->
(expect window.Strophe).toBeDefined()
(expect typeof @c.joap).toEqual "object"
it "has a method for creating a new connection to an object server", ->
server = @c.joap.getObjectServer "service.example.com"
(expect server).toBeDefined()
describe "object server", ->
server = null
beforeEach ->
server = @c.joap.getObjectServer "service.example.com"
it "can create an instance", ->
spyon @c, "send", (iq) ->
(expect iq.attr "to").toEqual "User@service.example.com"
(expect iq.attr "type").toEqual "set"
child = $ iq.children()[0]
(expect child.attr "xmlns").toEqual "jabber:iq:joap"
(expect child[0].tagName).toEqual "ADD"
(expect child.children().length).toEqual 2
foo = $ child.children()[0]
pass = $ child.children()[1]
(expect foo[0].tagName).toEqual "ATTRIBUTE"
(expect pass[0].tagName).toEqual "ATTRIBUTE"
(expect foo.children().length).toEqual 2
(expect foo.children()[0].tagName).toEqual "NAME"
(expect foo.children()[1].tagName).toEqual "VALUE"
(expect ($ "string", foo).text()).toEqual "foo"
(expect pass.children().length).toEqual 2
(expect child.children().length).toEqual 2
(expect ($ "i4", pass).text()).toEqual "2"
server.add "User", {name: "foo", pass: 2}, (iq, err, address) ->
it "can parse an error message", ->
spyon @c, "send", (req) =>
res = $iq({type:'error', id: req.attr 'id'})
.c("add").c("error", code:403).t("My error message")
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect err.message).toEqual "My error message"
(expect err.code).toEqual 403
it "can parse an 'service-unavailable' error", ->
spyon @c, "send", (req) =>
res = $iq({type:'error', id: req.attr 'id'})
.c("add").c("error", code:503)
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect err.code).toEqual 503
(expect err.message).toEqual "JOAP server is unavailable"
it "can parse an error message", ->
it "can parse the new instance id", ->
spyon @c, "send", (req) =>
res = $iq({type:'result', id: req.attr 'id'})
.c("add").c("newAddress").t("User@example.org/markus")
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect instanceId).toEqual "User@example.org/markus"
it "can edit an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "User@service.example.com/myId"
(expect iq.attr "type").toEqual "set"
(expect ($ "edit",iq).attr "xmlns").toEqual "jabber:iq:joap"
($ "attribute",iq).each ->
(expect ($ @).children().length).toEqual 2
res = $iq({type:'result', id: iq.attr 'id'}).c("edit")
@c._dataRecv createRequest(res)
server.edit "User", "myId",{ name:"x", age: 33 },(iq, err) ->
(expect typeof iq).toEqual "object"
(expect err).toBeFalsy()
it "can read an instance", ->
spyon @c, "sendIQ", (iq) ->
(expect iq.attr "to").toEqual "User@service.example.com/myId"
(expect iq.attr "type").toEqual "get"
(expect ($ "read",iq).attr "xmlns").toEqual "jabber:iq:joap"
server.read "User", "myId", (iq, err, obj) ->
it "can parse the read attributes", ->
spyon @c, "send", (req) =>
res = $iq({type:'result', id: req.attr 'id'})
.c("read")
.c("attribute")
.c("name").t("prop").up()
.c("value").c("int").t(5).up().up()
.c("attribute")
.c("name").t("obj").up()
.c("value").c("struct")
.c("member")
.c("name").t("foo").up()
.c("value").c("string").t("bar").up().up().up().up().up()
.c("attribute")
.c("name").t("arr").up()
.c("value")
.c("array")
.c("data")
.c("value").c("boolean").t(1).up().up()
.c("value").c("double").t("-0.5")
@c._dataRecv createRequest(res)
server.read "User", "id",(iq, err, obj) ->
(expect obj.prop).toEqual 5
(expect obj.obj.foo).toEqual "bar"
(expect obj.arr).toEqual [ true, -0.5 ]
it "can delete an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "User@service.example.com/myId"
(expect iq.attr "type").toEqual "set"
(expect ($ "delete",iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("delete")
@c._dataRecv createRequest(res)
server.delete "User", "myId", (iq, err) ->
(expect typeof iq).toEqual "object"
(expect err).toBeFalsy()
it "can search instances", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "User@service.example.com"
(expect iq.attr "type").toEqual "get"
(expect ($ "search",iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("search")
.c("item").t("Class@service.example.com/id0").up()
.c("item").t("Class@service.example.com/id2").up()
@c._dataRecv createRequest(res)
server.search "User", (iq, err, result) ->
(expect typeof iq).toEqual "object"
(expect result[0]).toEqual "Class@service.example.com/id0"
(expect result[1]).toEqual "Class@service.example.com/id2"
it "can send a describe request a class", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "Class@service.example.com"
(expect iq.attr "type").toEqual "get"
(expect ($ "describe", iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("describe")
.c("desc", "xml:lang":"en-US").t("Class description").up()
.c("attributeDescription", { writeable:false, required:true })
.c("name").t("myAttribute").up()
.c("type").t("int").up()
.c("desc", "xml:lang":"en-US").t("Foo").up()
.c("desc", "xml:lang":"de-DE").t("Alles mögliche").up().up()
.c("methodDescription", { allocation:"class"})
.c("name").t("methodname").up()
.c("returnType").t("boolean").up()
.c("desc", "xml:lang":"en-US").t("myAttribute").up().up()
.c("superclass").t("SuperClass@service.example.com").up()
.c("timestamp").t("2003-01-07T20:08:13Z").up()
@c._dataRecv createRequest(res)
server.describe "Class", (iq, err, result) ->
(expect typeof iq).toEqual "object"
(expect typeof result).toEqual "object"
(expect result.desc["en-US"]).toEqual "Class description"
(expect result.attributes.myAttribute.type).toEqual "int"
(expect result.attributes.myAttribute.desc["en-US"]).toEqual "Foo"
(expect result.superclass).toEqual "SuperClass@service.example.com"
it "can send a describe request to the server", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "service.example.com"
server.describe (iq, err, result) ->
it "can send a describe requests to an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "Class@service.example.com/id"
server.describe "Class", "id", (iq, err, result) ->
| 9804 | fs = require('fs')
jsdom = require('jsdom')
jquery = fs.readFileSync("./lib/jquery.js").toString()
strophe = fs.readFileSync("./lib/strophe.js").toString()
rpc = fs.readFileSync("./lib/strophe.rpc.js").toString()
joap = fs.readFileSync("./strophe.joap.js").toString()
describe "strophe.joap loading", ->
it "loads the strophe library", ->
window = null
Strophe = null
$ = null
$iq = null
mockConnection = ->
c = new Strophe.Connection()
c.authenticated = true
c.jid = 'n@d/r2'
c._processRequest = ->
c._changeConnectStatus Strophe.Status.CONNECTED
c
str = (builder) ->
if builder.tree
return Strophe.serialize(builder.tree())
Strophe.serialize(builder)
spyon = (obj, method, cb) ->
spyOn(obj, method).andCallFake (res)->
cb.call @, ($ str res)
receive = (c,req) ->
c._dataRecv(createRequest(req))
expect(c.send).toHaveBeenCalled()
createRequest = (iq) ->
iq = iq.tree() if typeof iq.tree is "function"
req = new Strophe.Request(iq, ->)
req.getResponse = ->
env = new Strophe.Builder('env', {type: 'mock'}).tree()
env.appendChild(iq)
env
req
jsdom.env
html: 'http://news.ycombinator.com/'
src: [ jquery, strophe, rpc, joap ]
done: (errors, w) ->
Strophe = w.Strophe
$ = w.jQuery
$iq = w.$iq
window = w
waitsFor -> !!window
runs ->
(expect window.Strophe).toBeDefined()
(expect window.$).toBeDefined()
(expect window.jQuery).toBeDefined()
describe "strophe.joap plugin", ->
beforeEach ->
@c = mockConnection()
@successHandler = jasmine.createSpy "successHandler"
@errorHandler = jasmine.createSpy "errorHandler"
it "provides connection.joap", ->
(expect window.Strophe).toBeDefined()
(expect typeof @c.joap).toEqual "object"
it "has a method for creating a new connection to an object server", ->
server = @c.joap.getObjectServer "service.example.com"
(expect server).toBeDefined()
describe "object server", ->
server = null
beforeEach ->
server = @c.joap.getObjectServer "service.example.com"
it "can create an instance", ->
spyon @c, "send", (iq) ->
(expect iq.attr "to").toEqual "<EMAIL>"
(expect iq.attr "type").toEqual "set"
child = $ iq.children()[0]
(expect child.attr "xmlns").toEqual "jabber:iq:joap"
(expect child[0].tagName).toEqual "ADD"
(expect child.children().length).toEqual 2
foo = $ child.children()[0]
pass = $ child.children()[1]
(expect foo[0].tagName).toEqual "ATTRIBUTE"
(expect pass[0].tagName).toEqual "ATTRIBUTE"
(expect foo.children().length).toEqual 2
(expect foo.children()[0].tagName).toEqual "NAME"
(expect foo.children()[1].tagName).toEqual "VALUE"
(expect ($ "string", foo).text()).toEqual "foo"
(expect pass.children().length).toEqual 2
(expect child.children().length).toEqual 2
(expect ($ "i4", pass).text()).toEqual "2"
server.add "User", {name: "foo", pass: 2}, (iq, err, address) ->
it "can parse an error message", ->
spyon @c, "send", (req) =>
res = $iq({type:'error', id: req.attr 'id'})
.c("add").c("error", code:403).t("My error message")
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect err.message).toEqual "My error message"
(expect err.code).toEqual 403
it "can parse an 'service-unavailable' error", ->
spyon @c, "send", (req) =>
res = $iq({type:'error', id: req.attr 'id'})
.c("add").c("error", code:503)
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect err.code).toEqual 503
(expect err.message).toEqual "JOAP server is unavailable"
it "can parse an error message", ->
it "can parse the new instance id", ->
spyon @c, "send", (req) =>
res = $iq({type:'result', id: req.attr 'id'})
.c("add").c("newAddress").t("<EMAIL>/markus")
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect instanceId).toEqual "<EMAIL>/markus"
it "can edit an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "<EMAIL>/myId"
(expect iq.attr "type").toEqual "set"
(expect ($ "edit",iq).attr "xmlns").toEqual "jabber:iq:joap"
($ "attribute",iq).each ->
(expect ($ @).children().length).toEqual 2
res = $iq({type:'result', id: iq.attr 'id'}).c("edit")
@c._dataRecv createRequest(res)
server.edit "User", "myId",{ name:"x", age: 33 },(iq, err) ->
(expect typeof iq).toEqual "object"
(expect err).toBeFalsy()
it "can read an instance", ->
spyon @c, "sendIQ", (iq) ->
(expect iq.attr "to").toEqual "<EMAIL>/myId"
(expect iq.attr "type").toEqual "get"
(expect ($ "read",iq).attr "xmlns").toEqual "jabber:iq:joap"
server.read "User", "myId", (iq, err, obj) ->
it "can parse the read attributes", ->
spyon @c, "send", (req) =>
res = $iq({type:'result', id: req.attr 'id'})
.c("read")
.c("attribute")
.c("name").t("prop").up()
.c("value").c("int").t(5).up().up()
.c("attribute")
.c("name").t("obj").up()
.c("value").c("struct")
.c("member")
.c("name").t("foo").up()
.c("value").c("string").t("bar").up().up().up().up().up()
.c("attribute")
.c("name").t("arr").up()
.c("value")
.c("array")
.c("data")
.c("value").c("boolean").t(1).up().up()
.c("value").c("double").t("-0.5")
@c._dataRecv createRequest(res)
server.read "User", "id",(iq, err, obj) ->
(expect obj.prop).toEqual 5
(expect obj.obj.foo).toEqual "bar"
(expect obj.arr).toEqual [ true, -0.5 ]
it "can delete an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "<EMAIL>/myId"
(expect iq.attr "type").toEqual "set"
(expect ($ "delete",iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("delete")
@c._dataRecv createRequest(res)
server.delete "User", "myId", (iq, err) ->
(expect typeof iq).toEqual "object"
(expect err).toBeFalsy()
it "can search instances", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "<EMAIL>"
(expect iq.attr "type").toEqual "get"
(expect ($ "search",iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("search")
.c("item").t("<EMAIL>/id0").up()
.c("item").t("<EMAIL>/id2").up()
@c._dataRecv createRequest(res)
server.search "User", (iq, err, result) ->
(expect typeof iq).toEqual "object"
(expect result[0]).toEqual "<EMAIL>/id0"
(expect result[1]).toEqual "<EMAIL>/id2"
it "can send a describe request a class", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "<EMAIL>"
(expect iq.attr "type").toEqual "get"
(expect ($ "describe", iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("describe")
.c("desc", "xml:lang":"en-US").t("Class description").up()
.c("attributeDescription", { writeable:false, required:true })
.c("name").t("myAttribute").up()
.c("type").t("int").up()
.c("desc", "xml:lang":"en-US").t("Foo").up()
.c("desc", "xml:lang":"de-DE").t("Alles mögliche").up().up()
.c("methodDescription", { allocation:"class"})
.c("name").t("methodname").up()
.c("returnType").t("boolean").up()
.c("desc", "xml:lang":"en-US").t("myAttribute").up().up()
.c("superclass").t("<EMAIL>").up()
.c("timestamp").t("2003-01-07T20:08:13Z").up()
@c._dataRecv createRequest(res)
server.describe "Class", (iq, err, result) ->
(expect typeof iq).toEqual "object"
(expect typeof result).toEqual "object"
(expect result.desc["en-US"]).toEqual "Class description"
(expect result.attributes.myAttribute.type).toEqual "int"
(expect result.attributes.myAttribute.desc["en-US"]).toEqual "Foo"
(expect result.superclass).toEqual "<EMAIL>"
it "can send a describe request to the server", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "service.example.com"
server.describe (iq, err, result) ->
it "can send a describe requests to an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "<EMAIL>/id"
server.describe "Class", "id", (iq, err, result) ->
| true | fs = require('fs')
jsdom = require('jsdom')
jquery = fs.readFileSync("./lib/jquery.js").toString()
strophe = fs.readFileSync("./lib/strophe.js").toString()
rpc = fs.readFileSync("./lib/strophe.rpc.js").toString()
joap = fs.readFileSync("./strophe.joap.js").toString()
describe "strophe.joap loading", ->
it "loads the strophe library", ->
window = null
Strophe = null
$ = null
$iq = null
mockConnection = ->
c = new Strophe.Connection()
c.authenticated = true
c.jid = 'n@d/r2'
c._processRequest = ->
c._changeConnectStatus Strophe.Status.CONNECTED
c
str = (builder) ->
if builder.tree
return Strophe.serialize(builder.tree())
Strophe.serialize(builder)
spyon = (obj, method, cb) ->
spyOn(obj, method).andCallFake (res)->
cb.call @, ($ str res)
receive = (c,req) ->
c._dataRecv(createRequest(req))
expect(c.send).toHaveBeenCalled()
createRequest = (iq) ->
iq = iq.tree() if typeof iq.tree is "function"
req = new Strophe.Request(iq, ->)
req.getResponse = ->
env = new Strophe.Builder('env', {type: 'mock'}).tree()
env.appendChild(iq)
env
req
jsdom.env
html: 'http://news.ycombinator.com/'
src: [ jquery, strophe, rpc, joap ]
done: (errors, w) ->
Strophe = w.Strophe
$ = w.jQuery
$iq = w.$iq
window = w
waitsFor -> !!window
runs ->
(expect window.Strophe).toBeDefined()
(expect window.$).toBeDefined()
(expect window.jQuery).toBeDefined()
describe "strophe.joap plugin", ->
beforeEach ->
@c = mockConnection()
@successHandler = jasmine.createSpy "successHandler"
@errorHandler = jasmine.createSpy "errorHandler"
it "provides connection.joap", ->
(expect window.Strophe).toBeDefined()
(expect typeof @c.joap).toEqual "object"
it "has a method for creating a new connection to an object server", ->
server = @c.joap.getObjectServer "service.example.com"
(expect server).toBeDefined()
describe "object server", ->
server = null
beforeEach ->
server = @c.joap.getObjectServer "service.example.com"
it "can create an instance", ->
spyon @c, "send", (iq) ->
(expect iq.attr "to").toEqual "PI:EMAIL:<EMAIL>END_PI"
(expect iq.attr "type").toEqual "set"
child = $ iq.children()[0]
(expect child.attr "xmlns").toEqual "jabber:iq:joap"
(expect child[0].tagName).toEqual "ADD"
(expect child.children().length).toEqual 2
foo = $ child.children()[0]
pass = $ child.children()[1]
(expect foo[0].tagName).toEqual "ATTRIBUTE"
(expect pass[0].tagName).toEqual "ATTRIBUTE"
(expect foo.children().length).toEqual 2
(expect foo.children()[0].tagName).toEqual "NAME"
(expect foo.children()[1].tagName).toEqual "VALUE"
(expect ($ "string", foo).text()).toEqual "foo"
(expect pass.children().length).toEqual 2
(expect child.children().length).toEqual 2
(expect ($ "i4", pass).text()).toEqual "2"
server.add "User", {name: "foo", pass: 2}, (iq, err, address) ->
it "can parse an error message", ->
spyon @c, "send", (req) =>
res = $iq({type:'error', id: req.attr 'id'})
.c("add").c("error", code:403).t("My error message")
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect err.message).toEqual "My error message"
(expect err.code).toEqual 403
it "can parse an 'service-unavailable' error", ->
spyon @c, "send", (req) =>
res = $iq({type:'error', id: req.attr 'id'})
.c("add").c("error", code:503)
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect err.code).toEqual 503
(expect err.message).toEqual "JOAP server is unavailable"
it "can parse an error message", ->
it "can parse the new instance id", ->
spyon @c, "send", (req) =>
res = $iq({type:'result', id: req.attr 'id'})
.c("add").c("newAddress").t("PI:EMAIL:<EMAIL>END_PI/markus")
@c._dataRecv createRequest(res)
server.add "User", {name: "foo", pass: 2}, (iq, err, instanceId) ->
(expect instanceId).toEqual "PI:EMAIL:<EMAIL>END_PI/markus"
it "can edit an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "PI:EMAIL:<EMAIL>END_PI/myId"
(expect iq.attr "type").toEqual "set"
(expect ($ "edit",iq).attr "xmlns").toEqual "jabber:iq:joap"
($ "attribute",iq).each ->
(expect ($ @).children().length).toEqual 2
res = $iq({type:'result', id: iq.attr 'id'}).c("edit")
@c._dataRecv createRequest(res)
server.edit "User", "myId",{ name:"x", age: 33 },(iq, err) ->
(expect typeof iq).toEqual "object"
(expect err).toBeFalsy()
it "can read an instance", ->
spyon @c, "sendIQ", (iq) ->
(expect iq.attr "to").toEqual "PI:EMAIL:<EMAIL>END_PI/myId"
(expect iq.attr "type").toEqual "get"
(expect ($ "read",iq).attr "xmlns").toEqual "jabber:iq:joap"
server.read "User", "myId", (iq, err, obj) ->
it "can parse the read attributes", ->
spyon @c, "send", (req) =>
res = $iq({type:'result', id: req.attr 'id'})
.c("read")
.c("attribute")
.c("name").t("prop").up()
.c("value").c("int").t(5).up().up()
.c("attribute")
.c("name").t("obj").up()
.c("value").c("struct")
.c("member")
.c("name").t("foo").up()
.c("value").c("string").t("bar").up().up().up().up().up()
.c("attribute")
.c("name").t("arr").up()
.c("value")
.c("array")
.c("data")
.c("value").c("boolean").t(1).up().up()
.c("value").c("double").t("-0.5")
@c._dataRecv createRequest(res)
server.read "User", "id",(iq, err, obj) ->
(expect obj.prop).toEqual 5
(expect obj.obj.foo).toEqual "bar"
(expect obj.arr).toEqual [ true, -0.5 ]
it "can delete an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "PI:EMAIL:<EMAIL>END_PI/myId"
(expect iq.attr "type").toEqual "set"
(expect ($ "delete",iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("delete")
@c._dataRecv createRequest(res)
server.delete "User", "myId", (iq, err) ->
(expect typeof iq).toEqual "object"
(expect err).toBeFalsy()
it "can search instances", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "PI:EMAIL:<EMAIL>END_PI"
(expect iq.attr "type").toEqual "get"
(expect ($ "search",iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("search")
.c("item").t("PI:EMAIL:<EMAIL>END_PI/id0").up()
.c("item").t("PI:EMAIL:<EMAIL>END_PI/id2").up()
@c._dataRecv createRequest(res)
server.search "User", (iq, err, result) ->
(expect typeof iq).toEqual "object"
(expect result[0]).toEqual "PI:EMAIL:<EMAIL>END_PI/id0"
(expect result[1]).toEqual "PI:EMAIL:<EMAIL>END_PI/id2"
it "can send a describe request a class", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "PI:EMAIL:<EMAIL>END_PI"
(expect iq.attr "type").toEqual "get"
(expect ($ "describe", iq).attr "xmlns").toEqual "jabber:iq:joap"
res = $iq({type:'result', id: iq.attr 'id'}).c("describe")
.c("desc", "xml:lang":"en-US").t("Class description").up()
.c("attributeDescription", { writeable:false, required:true })
.c("name").t("myAttribute").up()
.c("type").t("int").up()
.c("desc", "xml:lang":"en-US").t("Foo").up()
.c("desc", "xml:lang":"de-DE").t("Alles mögliche").up().up()
.c("methodDescription", { allocation:"class"})
.c("name").t("methodname").up()
.c("returnType").t("boolean").up()
.c("desc", "xml:lang":"en-US").t("myAttribute").up().up()
.c("superclass").t("PI:EMAIL:<EMAIL>END_PI").up()
.c("timestamp").t("2003-01-07T20:08:13Z").up()
@c._dataRecv createRequest(res)
server.describe "Class", (iq, err, result) ->
(expect typeof iq).toEqual "object"
(expect typeof result).toEqual "object"
(expect result.desc["en-US"]).toEqual "Class description"
(expect result.attributes.myAttribute.type).toEqual "int"
(expect result.attributes.myAttribute.desc["en-US"]).toEqual "Foo"
(expect result.superclass).toEqual "PI:EMAIL:<EMAIL>END_PI"
it "can send a describe request to the server", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "service.example.com"
server.describe (iq, err, result) ->
it "can send a describe requests to an instance", ->
spyon @c, "send", (iq) =>
(expect iq.attr "to").toEqual "PI:EMAIL:<EMAIL>END_PI/id"
server.describe "Class", "id", (iq, err, result) ->
|
[
{
"context": "->\n beforeEach ->\n @getCurrentUser.resolve(@user)\n\n it \"displays user name\", ->\n cy\n ",
"end": 1491,
"score": 0.9974946975708008,
"start": 1486,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "a\").should ($a) ->\n expect($a).t... | packages/desktop-gui/cypress/integration/nav_spec.coffee | Everworks/cypress | 3 | describe "Navigation", ->
beforeEach ->
cy.fixture("user").as("user")
cy.visitIndex().then (win) ->
{ start, @ipc } = win.App
cy.stub(@ipc, "getOptions").resolves({})
cy.stub(@ipc, "updaterCheck").resolves(false)
cy.stub(@ipc, "getProjects").resolves([])
cy.stub(@ipc, "getProjectStatuses").resolves([])
cy.stub(@ipc, "logOut").resolves({})
cy.stub(@ipc, "pingApiServer").resolves()
cy.stub(@ipc, "externalOpen")
@getCurrentUser = @util.deferred()
cy.stub(@ipc, "getCurrentUser").returns(@getCurrentUser.promise)
start()
it "displays and opens link to docs on click", ->
cy.get("nav").find(".fa-graduation-cap").click().then ->
expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io")
it "displays and opens link to support on click", ->
cy.get("nav").find(".fa-question-circle").click().then ->
expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/support")
it "shows loading spinner where user or 'Log in' will be", ->
cy.get(".main-nav li:last .fa-spinner")
context "without a current user", ->
beforeEach ->
@getCurrentUser.resolve({})
it "displays login button", ->
cy.shouldBeLoggedOut()
it "displays login modal when clicking login button", ->
cy.contains("Log In").click()
cy.contains(".btn", "Log In with GitHub")
context "with a current user", ->
beforeEach ->
@getCurrentUser.resolve(@user)
it "displays user name", ->
cy
.get("nav a").should ($a) ->
expect($a).to.contain(@user.name)
it "shows dropdown on click of user name", ->
cy.contains("Jane Lane").click()
cy.contains("Log Out").should("be.visible")
describe "logging out", ->
beforeEach ->
cy.logOut()
it "triggers logout on click of logout", ->
expect(@ipc.logOut).to.be.called
it "displays login button", ->
cy.shouldBeLoggedOut()
describe "when log out errors", ->
beforeEach ->
@ipc.logOut.rejects({ name: "", message: "ECONNREFUSED\n0.0.0.0:1234"})
cy.logOut()
it "shows global error", ->
cy.get(".global-error").should("be.visible")
it "displays error message", ->
cy.get(".global-error p").eq(0).invoke("text").should("include", "An unexpected error occurred while logging out")
cy.get(".global-error p").eq(1).invoke("html").should("include", "ECONNREFUSED<br>0.0.0.0:1234")
it "dismisses warning after clicking X", ->
cy.get(".global-error .close").click()
cy.get(".global-error").should("not.exist")
context "when current user has no name", ->
beforeEach ->
@user.name = null
@getCurrentUser.resolve(@user)
it "displays email instead of name", ->
cy
.get("nav a").should ($a) ->
expect($a).to.contain(@user.email)
| 112066 | describe "Navigation", ->
beforeEach ->
cy.fixture("user").as("user")
cy.visitIndex().then (win) ->
{ start, @ipc } = win.App
cy.stub(@ipc, "getOptions").resolves({})
cy.stub(@ipc, "updaterCheck").resolves(false)
cy.stub(@ipc, "getProjects").resolves([])
cy.stub(@ipc, "getProjectStatuses").resolves([])
cy.stub(@ipc, "logOut").resolves({})
cy.stub(@ipc, "pingApiServer").resolves()
cy.stub(@ipc, "externalOpen")
@getCurrentUser = @util.deferred()
cy.stub(@ipc, "getCurrentUser").returns(@getCurrentUser.promise)
start()
it "displays and opens link to docs on click", ->
cy.get("nav").find(".fa-graduation-cap").click().then ->
expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io")
it "displays and opens link to support on click", ->
cy.get("nav").find(".fa-question-circle").click().then ->
expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/support")
it "shows loading spinner where user or 'Log in' will be", ->
cy.get(".main-nav li:last .fa-spinner")
context "without a current user", ->
beforeEach ->
@getCurrentUser.resolve({})
it "displays login button", ->
cy.shouldBeLoggedOut()
it "displays login modal when clicking login button", ->
cy.contains("Log In").click()
cy.contains(".btn", "Log In with GitHub")
context "with a current user", ->
beforeEach ->
@getCurrentUser.resolve(@user)
it "displays user name", ->
cy
.get("nav a").should ($a) ->
expect($a).to.contain(@user.name)
it "shows dropdown on click of user name", ->
cy.contains("<NAME>").click()
cy.contains("Log Out").should("be.visible")
describe "logging out", ->
beforeEach ->
cy.logOut()
it "triggers logout on click of logout", ->
expect(@ipc.logOut).to.be.called
it "displays login button", ->
cy.shouldBeLoggedOut()
describe "when log out errors", ->
beforeEach ->
@ipc.logOut.rejects({ name: "", message: "ECONNREFUSED\n0.0.0.0:1234"})
cy.logOut()
it "shows global error", ->
cy.get(".global-error").should("be.visible")
it "displays error message", ->
cy.get(".global-error p").eq(0).invoke("text").should("include", "An unexpected error occurred while logging out")
cy.get(".global-error p").eq(1).invoke("html").should("include", "ECONNREFUSED<br>0.0.0.0:1234")
it "dismisses warning after clicking X", ->
cy.get(".global-error .close").click()
cy.get(".global-error").should("not.exist")
context "when current user has no name", ->
beforeEach ->
@user.name = null
@getCurrentUser.resolve(@user)
it "displays email instead of name", ->
cy
.get("nav a").should ($a) ->
expect($a).to.contain(@user.email)
| true | describe "Navigation", ->
beforeEach ->
cy.fixture("user").as("user")
cy.visitIndex().then (win) ->
{ start, @ipc } = win.App
cy.stub(@ipc, "getOptions").resolves({})
cy.stub(@ipc, "updaterCheck").resolves(false)
cy.stub(@ipc, "getProjects").resolves([])
cy.stub(@ipc, "getProjectStatuses").resolves([])
cy.stub(@ipc, "logOut").resolves({})
cy.stub(@ipc, "pingApiServer").resolves()
cy.stub(@ipc, "externalOpen")
@getCurrentUser = @util.deferred()
cy.stub(@ipc, "getCurrentUser").returns(@getCurrentUser.promise)
start()
it "displays and opens link to docs on click", ->
cy.get("nav").find(".fa-graduation-cap").click().then ->
expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io")
it "displays and opens link to support on click", ->
cy.get("nav").find(".fa-question-circle").click().then ->
expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/support")
it "shows loading spinner where user or 'Log in' will be", ->
cy.get(".main-nav li:last .fa-spinner")
context "without a current user", ->
beforeEach ->
@getCurrentUser.resolve({})
it "displays login button", ->
cy.shouldBeLoggedOut()
it "displays login modal when clicking login button", ->
cy.contains("Log In").click()
cy.contains(".btn", "Log In with GitHub")
context "with a current user", ->
beforeEach ->
@getCurrentUser.resolve(@user)
it "displays user name", ->
cy
.get("nav a").should ($a) ->
expect($a).to.contain(@user.name)
it "shows dropdown on click of user name", ->
cy.contains("PI:NAME:<NAME>END_PI").click()
cy.contains("Log Out").should("be.visible")
describe "logging out", ->
beforeEach ->
cy.logOut()
it "triggers logout on click of logout", ->
expect(@ipc.logOut).to.be.called
it "displays login button", ->
cy.shouldBeLoggedOut()
describe "when log out errors", ->
beforeEach ->
@ipc.logOut.rejects({ name: "", message: "ECONNREFUSED\n0.0.0.0:1234"})
cy.logOut()
it "shows global error", ->
cy.get(".global-error").should("be.visible")
it "displays error message", ->
cy.get(".global-error p").eq(0).invoke("text").should("include", "An unexpected error occurred while logging out")
cy.get(".global-error p").eq(1).invoke("html").should("include", "ECONNREFUSED<br>0.0.0.0:1234")
it "dismisses warning after clicking X", ->
cy.get(".global-error .close").click()
cy.get(".global-error").should("not.exist")
context "when current user has no name", ->
beforeEach ->
@user.name = null
@getCurrentUser.resolve(@user)
it "displays email instead of name", ->
cy
.get("nav a").should ($a) ->
expect($a).to.contain(@user.email)
|
[
{
"context": "ersion %> - @license: <%= pkg.license %>; @author: Jean Christophe Roy; @site: <%= pkg.homepage %> */\\n'\n browser",
"end": 643,
"score": 0.9998769164085388,
"start": 624,
"tag": "NAME",
"value": "Jean Christophe Roy"
},
{
"context": "ersion %> - @license: <%= p... | Gruntfile.coffee | oraricha/fuzz-aldrin-plus | 216 | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
clean: ['lib','dist']
coffee:
glob_to_multiple:
expand: true
cwd: 'src'
src: ['*.coffee']
dest: 'lib'
ext: '.js'
coffeelint:
options:
no_empty_param_list:
level: 'error'
max_line_length:
level: 'ignore'
src: ['src/*.coffee']
test: ['spec/*.coffee']
gruntfile: ['Gruntfile.coffee']
browserify:
options:
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - @license: <%= pkg.license %>; @author: Jean Christophe Roy; @site: <%= pkg.homepage %> */\n'
browserifyOptions:
standalone: 'fuzzaldrin'
dist:
src: 'lib/fuzzaldrin.js'
dest: 'dist-browser/fuzzaldrin-plus.js'
uglify:
options:
compress: true
preserveComments: false
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - @license: <%= pkg.license %>; @author: Jean Christophe Roy; @site: <%= pkg.homepage %> */\n'
dist:
src: 'dist-browser/fuzzaldrin-plus.js',
dest: 'dist-browser/fuzzaldrin-plus.min.js'
shell:
test:
command: 'node node_modules/jasmine-focused/bin/jasmine-focused --coffee --captureExceptions spec'
options:
stdout: true
stderr: true
failOnError: true
mkdir:
command: 'mkdir dist'
options:
stdout: true
stderr: true
nugetpack:
options:
properties:'versiondir=<%= pkg.version %>'
verbosity: 'detailed'
dist:
src: 'fuzzaldrin-plus.nuspec'
dest: 'dist/'
options:
version: '<%= pkg.version %>'
nugetpush:
dist:
src: 'dist/*.nupkg'
options:
apiKey: '<specify API key before executing nugetpush task>'
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-shell')
grunt.loadNpmTasks('grunt-coffeelint')
grunt.loadNpmTasks('grunt-browserify')
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-contrib-clean')
grunt.loadNpmTasks('grunt-nuget')
grunt.loadNpmTasks('grunt-bower-task')
grunt.registerTask('lint', ['coffeelint'])
grunt.registerTask('test', ['default', 'shell:test'])
grunt.registerTask('prepublish', ['clean', 'test', 'distribute'])
grunt.registerTask('default', ['coffee', 'lint'])
grunt.registerTask('distribute', ['default', 'browserify', 'uglify'])
grunt.registerTask('packnuget', ['shell:mkdir', 'nugetpack'])
grunt.registerTask('publishnuget', ['packnuget', 'nugetpush'])
| 199150 | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
clean: ['lib','dist']
coffee:
glob_to_multiple:
expand: true
cwd: 'src'
src: ['*.coffee']
dest: 'lib'
ext: '.js'
coffeelint:
options:
no_empty_param_list:
level: 'error'
max_line_length:
level: 'ignore'
src: ['src/*.coffee']
test: ['spec/*.coffee']
gruntfile: ['Gruntfile.coffee']
browserify:
options:
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - @license: <%= pkg.license %>; @author: <NAME>; @site: <%= pkg.homepage %> */\n'
browserifyOptions:
standalone: 'fuzzaldrin'
dist:
src: 'lib/fuzzaldrin.js'
dest: 'dist-browser/fuzzaldrin-plus.js'
uglify:
options:
compress: true
preserveComments: false
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - @license: <%= pkg.license %>; @author: <NAME>; @site: <%= pkg.homepage %> */\n'
dist:
src: 'dist-browser/fuzzaldrin-plus.js',
dest: 'dist-browser/fuzzaldrin-plus.min.js'
shell:
test:
command: 'node node_modules/jasmine-focused/bin/jasmine-focused --coffee --captureExceptions spec'
options:
stdout: true
stderr: true
failOnError: true
mkdir:
command: 'mkdir dist'
options:
stdout: true
stderr: true
nugetpack:
options:
properties:'versiondir=<%= pkg.version %>'
verbosity: 'detailed'
dist:
src: 'fuzzaldrin-plus.nuspec'
dest: 'dist/'
options:
version: '<%= pkg.version %>'
nugetpush:
dist:
src: 'dist/*.nupkg'
options:
apiKey: '<specify API key before executing nugetpush task>'
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-shell')
grunt.loadNpmTasks('grunt-coffeelint')
grunt.loadNpmTasks('grunt-browserify')
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-contrib-clean')
grunt.loadNpmTasks('grunt-nuget')
grunt.loadNpmTasks('grunt-bower-task')
grunt.registerTask('lint', ['coffeelint'])
grunt.registerTask('test', ['default', 'shell:test'])
grunt.registerTask('prepublish', ['clean', 'test', 'distribute'])
grunt.registerTask('default', ['coffee', 'lint'])
grunt.registerTask('distribute', ['default', 'browserify', 'uglify'])
grunt.registerTask('packnuget', ['shell:mkdir', 'nugetpack'])
grunt.registerTask('publishnuget', ['packnuget', 'nugetpush'])
| true | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
clean: ['lib','dist']
coffee:
glob_to_multiple:
expand: true
cwd: 'src'
src: ['*.coffee']
dest: 'lib'
ext: '.js'
coffeelint:
options:
no_empty_param_list:
level: 'error'
max_line_length:
level: 'ignore'
src: ['src/*.coffee']
test: ['spec/*.coffee']
gruntfile: ['Gruntfile.coffee']
browserify:
options:
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - @license: <%= pkg.license %>; @author: PI:NAME:<NAME>END_PI; @site: <%= pkg.homepage %> */\n'
browserifyOptions:
standalone: 'fuzzaldrin'
dist:
src: 'lib/fuzzaldrin.js'
dest: 'dist-browser/fuzzaldrin-plus.js'
uglify:
options:
compress: true
preserveComments: false
banner: '/* <%= pkg.name %> - v<%= pkg.version %> - @license: <%= pkg.license %>; @author: PI:NAME:<NAME>END_PI; @site: <%= pkg.homepage %> */\n'
dist:
src: 'dist-browser/fuzzaldrin-plus.js',
dest: 'dist-browser/fuzzaldrin-plus.min.js'
shell:
test:
command: 'node node_modules/jasmine-focused/bin/jasmine-focused --coffee --captureExceptions spec'
options:
stdout: true
stderr: true
failOnError: true
mkdir:
command: 'mkdir dist'
options:
stdout: true
stderr: true
nugetpack:
options:
properties:'versiondir=<%= pkg.version %>'
verbosity: 'detailed'
dist:
src: 'fuzzaldrin-plus.nuspec'
dest: 'dist/'
options:
version: '<%= pkg.version %>'
nugetpush:
dist:
src: 'dist/*.nupkg'
options:
apiKey: '<specify API key before executing nugetpush task>'
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-shell')
grunt.loadNpmTasks('grunt-coffeelint')
grunt.loadNpmTasks('grunt-browserify')
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-contrib-clean')
grunt.loadNpmTasks('grunt-nuget')
grunt.loadNpmTasks('grunt-bower-task')
grunt.registerTask('lint', ['coffeelint'])
grunt.registerTask('test', ['default', 'shell:test'])
grunt.registerTask('prepublish', ['clean', 'test', 'distribute'])
grunt.registerTask('default', ['coffee', 'lint'])
grunt.registerTask('distribute', ['default', 'browserify', 'uglify'])
grunt.registerTask('packnuget', ['shell:mkdir', 'nugetpack'])
grunt.registerTask('publishnuget', ['packnuget', 'nugetpush'])
|
[
{
"context": "# Copyright (c) 2008-2013 Michael Dvorkin and contributors.\n#\n# Fat Free CRM is freely dist",
"end": 41,
"score": 0.9998588562011719,
"start": 26,
"tag": "NAME",
"value": "Michael Dvorkin"
}
] | app/assets/javascripts/crm_comments.js.coffee | ramses-lopez/re-crm | 0 | # Copyright (c) 2008-2013 Michael Dvorkin and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# When comments are added to an entity, disable the add button
# and add a spinner to indicate request is processing
(($j) ->
addSpinnerToComments = ->
$j('div.new_comment').each ->
container = $j(this)
unless container.hasClass('withSpinner')
container.find('form').on 'submit', ->
container.find('form [type=submit]').attr("disabled", "disabled")
container.find('.spinner').show()
container.addClass("withSpinner")
toggleComment = (container) ->
baseId = container.attr('id').replace('_comment_new', '')
post = container.find('#' + baseId + '_post')
ask = container.find('#' + baseId + '_ask')
comment = container.find('#' + baseId + '_comment_comment')
post.toggle()
ask.toggle()
if comment.is(":visible")
container.find('form [type=submit]').removeAttr("disabled")
container.find('.spinner').hide()
comment.focus()
addOpenCloseToComments = ->
$j('div.new_comment').each ->
container = $j(this)
unless container.hasClass('withOpenClose')
baseId = container.attr('id').replace('_comment_new', '')
post = container.find('#' + baseId + '_post')
ask = container.find('#' + baseId + '_ask')
container.find('.cancel').on 'click', (event) ->
toggleComment(container)
false
new_comment = container.find('#' + baseId + '_post_new_note')
new_comment.on 'click', ->
toggleComment(container)
crm.textarea_user_autocomplete(baseId + '_comment_comment')
container.addClass("withOpenClose")
# Apply when document is loaded
$j(document).ready ->
addSpinnerToComments()
addOpenCloseToComments()
# Apply when jquery event (e.g. search) occurs
$j(document).ajaxComplete ->
addSpinnerToComments()
addOpenCloseToComments()
# Apply when protoype event (e.g. cancel edit) occurs
Ajax.Responders.register({
onComplete: ->
addSpinnerToComments()
addOpenCloseToComments()
})
)(jQuery)
| 159969 | # Copyright (c) 2008-2013 <NAME> and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# When comments are added to an entity, disable the add button
# and add a spinner to indicate request is processing
(($j) ->
addSpinnerToComments = ->
$j('div.new_comment').each ->
container = $j(this)
unless container.hasClass('withSpinner')
container.find('form').on 'submit', ->
container.find('form [type=submit]').attr("disabled", "disabled")
container.find('.spinner').show()
container.addClass("withSpinner")
toggleComment = (container) ->
baseId = container.attr('id').replace('_comment_new', '')
post = container.find('#' + baseId + '_post')
ask = container.find('#' + baseId + '_ask')
comment = container.find('#' + baseId + '_comment_comment')
post.toggle()
ask.toggle()
if comment.is(":visible")
container.find('form [type=submit]').removeAttr("disabled")
container.find('.spinner').hide()
comment.focus()
addOpenCloseToComments = ->
$j('div.new_comment').each ->
container = $j(this)
unless container.hasClass('withOpenClose')
baseId = container.attr('id').replace('_comment_new', '')
post = container.find('#' + baseId + '_post')
ask = container.find('#' + baseId + '_ask')
container.find('.cancel').on 'click', (event) ->
toggleComment(container)
false
new_comment = container.find('#' + baseId + '_post_new_note')
new_comment.on 'click', ->
toggleComment(container)
crm.textarea_user_autocomplete(baseId + '_comment_comment')
container.addClass("withOpenClose")
# Apply when document is loaded
$j(document).ready ->
addSpinnerToComments()
addOpenCloseToComments()
# Apply when jquery event (e.g. search) occurs
$j(document).ajaxComplete ->
addSpinnerToComments()
addOpenCloseToComments()
# Apply when protoype event (e.g. cancel edit) occurs
Ajax.Responders.register({
onComplete: ->
addSpinnerToComments()
addOpenCloseToComments()
})
)(jQuery)
| true | # Copyright (c) 2008-2013 PI:NAME:<NAME>END_PI and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
# When comments are added to an entity, disable the add button
# and add a spinner to indicate request is processing
(($j) ->
addSpinnerToComments = ->
$j('div.new_comment').each ->
container = $j(this)
unless container.hasClass('withSpinner')
container.find('form').on 'submit', ->
container.find('form [type=submit]').attr("disabled", "disabled")
container.find('.spinner').show()
container.addClass("withSpinner")
toggleComment = (container) ->
baseId = container.attr('id').replace('_comment_new', '')
post = container.find('#' + baseId + '_post')
ask = container.find('#' + baseId + '_ask')
comment = container.find('#' + baseId + '_comment_comment')
post.toggle()
ask.toggle()
if comment.is(":visible")
container.find('form [type=submit]').removeAttr("disabled")
container.find('.spinner').hide()
comment.focus()
addOpenCloseToComments = ->
$j('div.new_comment').each ->
container = $j(this)
unless container.hasClass('withOpenClose')
baseId = container.attr('id').replace('_comment_new', '')
post = container.find('#' + baseId + '_post')
ask = container.find('#' + baseId + '_ask')
container.find('.cancel').on 'click', (event) ->
toggleComment(container)
false
new_comment = container.find('#' + baseId + '_post_new_note')
new_comment.on 'click', ->
toggleComment(container)
crm.textarea_user_autocomplete(baseId + '_comment_comment')
container.addClass("withOpenClose")
# Apply when document is loaded
$j(document).ready ->
addSpinnerToComments()
addOpenCloseToComments()
# Apply when jquery event (e.g. search) occurs
$j(document).ajaxComplete ->
addSpinnerToComments()
addOpenCloseToComments()
# Apply when protoype event (e.g. cancel edit) occurs
Ajax.Responders.register({
onComplete: ->
addSpinnerToComments()
addOpenCloseToComments()
})
)(jQuery)
|
[
{
"context": "\n atom.config.set 'wercker-status.Token', '123'\n atom.config.set 'wercker-status.Username",
"end": 143,
"score": 0.96938157081604,
"start": 140,
"tag": "PASSWORD",
"value": "123"
},
{
"context": " atom.config.set 'wercker-status.Username', 'bozo'\n ... | spec/config-spec.coffee | mdno/wercker-status | 3 | config = require '../lib/config'
describe 'Configuration lib', ->
it 'get_config', ->
atom.config.set 'wercker-status.Token', '123'
atom.config.set 'wercker-status.Username', 'bozo'
atom.config.set 'wercker-status.Password', 'onetwothree'
atom.config.set 'wercker-status.Interval_Minutes', 1
configloaded = config.get_config()
expect(configloaded.user).toBe('bozo')
expect(configloaded.pass).toBe('onetwothree')
expect(configloaded.interval).toBe(60000)
expect(configloaded.token).toBe('123')
it 'reset_config', ->
atom.config.set 'wercker-status.Token', '123'
atom.config.set 'wercker-status.Username', 'bozo'
atom.config.set 'wercker-status.Password', 'onetwothree'
atom.config.set 'wercker-status.Interval_Minutes', 1
config.reset_config()
configloaded = config.get_config()
expect(configloaded.user).toBe('')
expect(configloaded.pass).toBe('')
expect(configloaded.interval).toBe(120000)
expect(configloaded.token).toBe(undefined)
| 103321 | config = require '../lib/config'
describe 'Configuration lib', ->
it 'get_config', ->
atom.config.set 'wercker-status.Token', '<PASSWORD>'
atom.config.set 'wercker-status.Username', 'bozo'
atom.config.set 'wercker-status.Password', '<PASSWORD>'
atom.config.set 'wercker-status.Interval_Minutes', 1
configloaded = config.get_config()
expect(configloaded.user).toBe('bozo')
expect(configloaded.pass).toBe('<PASSWORD>')
expect(configloaded.interval).toBe(60000)
expect(configloaded.token).toBe('1<PASSWORD>')
it 'reset_config', ->
atom.config.set 'wercker-status.Token', '<PASSWORD>'
atom.config.set 'wercker-status.Username', 'bozo'
atom.config.set 'wercker-status.Password', '<PASSWORD>'
atom.config.set 'wercker-status.Interval_Minutes', 1
config.reset_config()
configloaded = config.get_config()
expect(configloaded.user).toBe('')
expect(configloaded.pass).toBe('')
expect(configloaded.interval).toBe(120000)
expect(configloaded.token).toBe(undefined)
| true | config = require '../lib/config'
describe 'Configuration lib', ->
it 'get_config', ->
atom.config.set 'wercker-status.Token', 'PI:PASSWORD:<PASSWORD>END_PI'
atom.config.set 'wercker-status.Username', 'bozo'
atom.config.set 'wercker-status.Password', 'PI:PASSWORD:<PASSWORD>END_PI'
atom.config.set 'wercker-status.Interval_Minutes', 1
configloaded = config.get_config()
expect(configloaded.user).toBe('bozo')
expect(configloaded.pass).toBe('PI:PASSWORD:<PASSWORD>END_PI')
expect(configloaded.interval).toBe(60000)
expect(configloaded.token).toBe('1PI:PASSWORD:<PASSWORD>END_PI')
it 'reset_config', ->
atom.config.set 'wercker-status.Token', 'PI:PASSWORD:<PASSWORD>END_PI'
atom.config.set 'wercker-status.Username', 'bozo'
atom.config.set 'wercker-status.Password', 'PI:PASSWORD:<PASSWORD>END_PI'
atom.config.set 'wercker-status.Interval_Minutes', 1
config.reset_config()
configloaded = config.get_config()
expect(configloaded.user).toBe('')
expect(configloaded.pass).toBe('')
expect(configloaded.interval).toBe(120000)
expect(configloaded.token).toBe(undefined)
|
[
{
"context": "yFirstExtension.crx'\n\nprivateKey = fs.readFileSync '/tmp/ecf3b8df877d4bea04e01393adebc369'\n\ncrx.setPrivateKey privateKey, (err) ->\n if err",
"end": 232,
"score": 0.9984447956085205,
"start": 194,
"tag": "KEY",
"value": "'/tmp/ecf3b8df877d4bea04e01393adebc369"
}
] | test/unpack.coffee | U/crx | 1 | fs = require 'fs'
ChromeExtension = require '../'
crx = new ChromeExtension
crxPath: '/tmp/5d58b482687e2c2b060fc19f877425b0'
# crxPath: 'myFirstExtension.crx'
privateKey = fs.readFileSync '/tmp/ecf3b8df877d4bea04e01393adebc369'
crx.setPrivateKey privateKey, (err) ->
if err
return console.log 'NOT compatible!!!'
if !err
console.log 'Private key compatible!!!'
crx.unpack () ->
#check crx.manifest, crx.path, crx.rootDirectory
# check whether the app ID can be calculated from the "key" in the manifest.
m = crx.manifest
crx.manifest.name = 'Levy'
crx.pack (err, crxFilename) =>
console.log 'Written Filename:', crxFilename
# debugger
# debugger
#crx.readExtensionId (err, extensionId) ->
# m = crx.manifest
# debugger
#crx.unpack () ->
# #check crx.manifest, crx.path, crx.rootDirectory
# # check whether the app ID can be calculated from the "key" in the manifest.
# m = crx.manifest
# crx.manifest.name = 'Levy'
# crx.pack (err, crxFilename) =>
# console.log 'Written Filename:', crxFilename
# debugger
# debugger
| 7079 | fs = require 'fs'
ChromeExtension = require '../'
crx = new ChromeExtension
crxPath: '/tmp/5d58b482687e2c2b060fc19f877425b0'
# crxPath: 'myFirstExtension.crx'
privateKey = fs.readFileSync <KEY>'
crx.setPrivateKey privateKey, (err) ->
if err
return console.log 'NOT compatible!!!'
if !err
console.log 'Private key compatible!!!'
crx.unpack () ->
#check crx.manifest, crx.path, crx.rootDirectory
# check whether the app ID can be calculated from the "key" in the manifest.
m = crx.manifest
crx.manifest.name = 'Levy'
crx.pack (err, crxFilename) =>
console.log 'Written Filename:', crxFilename
# debugger
# debugger
#crx.readExtensionId (err, extensionId) ->
# m = crx.manifest
# debugger
#crx.unpack () ->
# #check crx.manifest, crx.path, crx.rootDirectory
# # check whether the app ID can be calculated from the "key" in the manifest.
# m = crx.manifest
# crx.manifest.name = 'Levy'
# crx.pack (err, crxFilename) =>
# console.log 'Written Filename:', crxFilename
# debugger
# debugger
| true | fs = require 'fs'
ChromeExtension = require '../'
crx = new ChromeExtension
crxPath: '/tmp/5d58b482687e2c2b060fc19f877425b0'
# crxPath: 'myFirstExtension.crx'
privateKey = fs.readFileSync PI:KEY:<KEY>END_PI'
crx.setPrivateKey privateKey, (err) ->
if err
return console.log 'NOT compatible!!!'
if !err
console.log 'Private key compatible!!!'
crx.unpack () ->
#check crx.manifest, crx.path, crx.rootDirectory
# check whether the app ID can be calculated from the "key" in the manifest.
m = crx.manifest
crx.manifest.name = 'Levy'
crx.pack (err, crxFilename) =>
console.log 'Written Filename:', crxFilename
# debugger
# debugger
#crx.readExtensionId (err, extensionId) ->
# m = crx.manifest
# debugger
#crx.unpack () ->
# #check crx.manifest, crx.path, crx.rootDirectory
# # check whether the app ID can be calculated from the "key" in the manifest.
# m = crx.manifest
# crx.manifest.name = 'Levy'
# crx.pack (err, crxFilename) =>
# console.log 'Written Filename:', crxFilename
# debugger
# debugger
|
[
{
"context": " {}\n total_bytes_read: {}\n\nfile_size_keys = [\n \"total_bytes_sent\"\n \"total_bytes_read\"\n]\n\nformatFileSize = (nb) ->\n",
"end": 332,
"score": 0.9024758338928223,
"start": 315,
"tag": "KEY",
"value": "total_bytes_sent\""
},
{
"context": "d: {}\n\nfile_size_ke... | controllers/analytics/public/analytics.coffee | moul/tapas-icecast-analytics | 3 | options = {}
cols =
listeners: "Listeners"
slow_listeners: "Slow listeners"
total_bytes_read: "Total bytes read"
total_bytes_sent: "Total bytes sent"
title: "Title"
bitrate: "Bitrate"
total =
listeners: {}
slow_listeners: {}
total_bytes_sent: {}
total_bytes_read: {}
file_size_keys = [
"total_bytes_sent"
"total_bytes_read"
]
formatFileSize = (nb) ->
NumberHelpers.number_to_human_size nb,
precision: 5
updateServer = (server) ->
for id, mount of server
if options.mounts?.length && mount.server_name not in options.mounts
continue
mount_uuid = "#{mount.id}#{mount.server_name}"
#console.log mount
tr = $("tr[data-rid=\"#{mount_uuid}\"]")
tds = tr.find('td')
i = 0
for key, value of cols
if key of total
total[key][mount_uuid] = parseInt mount[key]
td = $(tds[i++])
if !mount[key]? or mount[key] == '0'
td.addClass 'nullvalue'
else
td.removeClass 'nullvalue'
oldValue = td.html()
if mount[key]? and oldValue != mount[key]
mount[key] = formatFileSize mount[key] if key in file_size_keys
td.html mount[key]
td.fadeTo(100, 1).fadeTo(700, 0.3)
tds = $('tfoot').find('td')
i = 0
for key, value of cols
td = $(tds[i++])
if key of total
tot = 0
for mount_uuid, amount of total[key]
tot += amount
if key in file_size_keys
tot = formatFileSize tot
td.html tot
createTable = (tree) ->
table = $('#stats')
table.empty()
for group, servers of tree
for id, mounts of servers
thead = $('<thead/>')
tr = $('<tr/>')
tr.append $('<th/>').html id
for key, value of cols
tr.append $('<th/>').html value
thead.append tr
table.append thead
tbody = $('<tbody/>')
for mount_name, mount of mounts
if options.mounts?.length && mount.server_name not in options.mounts
continue
#console.log mount
tr = $('<tr/>').attr('data-rid', "#{mount.id}#{mount.server_name}")
tr.append $('<th/>').html mount_name
for key, value of cols
tr.append $('<td/>').html('')
tbody.append tr
table.append tbody
updateServer mounts
tfoot = $('<tfoot/>')
tr = $('<tr />')
tr.append $('<th/>').html 'Total'
for key, value of cols
tr.append $('<td/>').html('')
tfoot.append tr
table.append tfoot
$(document).ready ->
options.mounts = $('meta[name="mounts"]').attr('content').split(/,/) || false
options.mounts = false if options.mounts.length == 1 and options.mounts[0] is ""
socket = do io.connect
socket.on 'connect', ->
socket.emit 'getTree', createTable
socket.on 'updateServer', updateServer
| 62809 | options = {}
cols =
listeners: "Listeners"
slow_listeners: "Slow listeners"
total_bytes_read: "Total bytes read"
total_bytes_sent: "Total bytes sent"
title: "Title"
bitrate: "Bitrate"
total =
listeners: {}
slow_listeners: {}
total_bytes_sent: {}
total_bytes_read: {}
file_size_keys = [
"<KEY>
"<KEY>
]
formatFileSize = (nb) ->
NumberHelpers.number_to_human_size nb,
precision: 5
updateServer = (server) ->
for id, mount of server
if options.mounts?.length && mount.server_name not in options.mounts
continue
mount_uuid = "#{mount.id}#{mount.server_name}"
#console.log mount
tr = $("tr[data-rid=\"#{mount_uuid}\"]")
tds = tr.find('td')
i = 0
for key, value of cols
if key of total
total[key][mount_uuid] = parseInt mount[key]
td = $(tds[i++])
if !mount[key]? or mount[key] == '0'
td.addClass 'nullvalue'
else
td.removeClass 'nullvalue'
oldValue = td.html()
if mount[key]? and oldValue != mount[key]
mount[key] = formatFileSize mount[key] if key in file_size_keys
td.html mount[key]
td.fadeTo(100, 1).fadeTo(700, 0.3)
tds = $('tfoot').find('td')
i = 0
for key, value of cols
td = $(tds[i++])
if key of total
tot = 0
for mount_uuid, amount of total[key]
tot += amount
if key in file_size_keys
tot = formatFileSize tot
td.html tot
createTable = (tree) ->
table = $('#stats')
table.empty()
for group, servers of tree
for id, mounts of servers
thead = $('<thead/>')
tr = $('<tr/>')
tr.append $('<th/>').html id
for key, value of cols
tr.append $('<th/>').html value
thead.append tr
table.append thead
tbody = $('<tbody/>')
for mount_name, mount of mounts
if options.mounts?.length && mount.server_name not in options.mounts
continue
#console.log mount
tr = $('<tr/>').attr('data-rid', "#{mount.id}#{mount.server_name}")
tr.append $('<th/>').html mount_name
for key, value of cols
tr.append $('<td/>').html('')
tbody.append tr
table.append tbody
updateServer mounts
tfoot = $('<tfoot/>')
tr = $('<tr />')
tr.append $('<th/>').html 'Total'
for key, value of cols
tr.append $('<td/>').html('')
tfoot.append tr
table.append tfoot
$(document).ready ->
options.mounts = $('meta[name="mounts"]').attr('content').split(/,/) || false
options.mounts = false if options.mounts.length == 1 and options.mounts[0] is ""
socket = do io.connect
socket.on 'connect', ->
socket.emit 'getTree', createTable
socket.on 'updateServer', updateServer
| true | options = {}
cols =
listeners: "Listeners"
slow_listeners: "Slow listeners"
total_bytes_read: "Total bytes read"
total_bytes_sent: "Total bytes sent"
title: "Title"
bitrate: "Bitrate"
total =
listeners: {}
slow_listeners: {}
total_bytes_sent: {}
total_bytes_read: {}
file_size_keys = [
"PI:KEY:<KEY>END_PI
"PI:KEY:<KEY>END_PI
]
formatFileSize = (nb) ->
NumberHelpers.number_to_human_size nb,
precision: 5
updateServer = (server) ->
for id, mount of server
if options.mounts?.length && mount.server_name not in options.mounts
continue
mount_uuid = "#{mount.id}#{mount.server_name}"
#console.log mount
tr = $("tr[data-rid=\"#{mount_uuid}\"]")
tds = tr.find('td')
i = 0
for key, value of cols
if key of total
total[key][mount_uuid] = parseInt mount[key]
td = $(tds[i++])
if !mount[key]? or mount[key] == '0'
td.addClass 'nullvalue'
else
td.removeClass 'nullvalue'
oldValue = td.html()
if mount[key]? and oldValue != mount[key]
mount[key] = formatFileSize mount[key] if key in file_size_keys
td.html mount[key]
td.fadeTo(100, 1).fadeTo(700, 0.3)
tds = $('tfoot').find('td')
i = 0
for key, value of cols
td = $(tds[i++])
if key of total
tot = 0
for mount_uuid, amount of total[key]
tot += amount
if key in file_size_keys
tot = formatFileSize tot
td.html tot
createTable = (tree) ->
table = $('#stats')
table.empty()
for group, servers of tree
for id, mounts of servers
thead = $('<thead/>')
tr = $('<tr/>')
tr.append $('<th/>').html id
for key, value of cols
tr.append $('<th/>').html value
thead.append tr
table.append thead
tbody = $('<tbody/>')
for mount_name, mount of mounts
if options.mounts?.length && mount.server_name not in options.mounts
continue
#console.log mount
tr = $('<tr/>').attr('data-rid', "#{mount.id}#{mount.server_name}")
tr.append $('<th/>').html mount_name
for key, value of cols
tr.append $('<td/>').html('')
tbody.append tr
table.append tbody
updateServer mounts
tfoot = $('<tfoot/>')
tr = $('<tr />')
tr.append $('<th/>').html 'Total'
for key, value of cols
tr.append $('<td/>').html('')
tfoot.append tr
table.append tfoot
$(document).ready ->
options.mounts = $('meta[name="mounts"]').attr('content').split(/,/) || false
options.mounts = false if options.mounts.length == 1 and options.mounts[0] is ""
socket = do io.connect
socket.on 'connect', ->
socket.emit 'getTree', createTable
socket.on 'updateServer', updateServer
|
[
{
"context": "ds:\n# hubot fez <your sentences>\n#\n# Author:\n# Bastien de Luca <dev@de-luca.io>\n\nalpha = ['a','b','c','d','e','f",
"end": 235,
"score": 0.9998623728752136,
"start": 220,
"tag": "NAME",
"value": "Bastien de Luca"
},
{
"context": "<your sentences>\n#\n# Author:\... | src/fez.coffee | de-luca/hubot-fez | 0 | # Description:
# Translate your sentences in "FEZIAN"
# This is for Slack using the Slack-FEZ-Emoji
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot fez <your sentences>
#
# Author:
# Bastien de Luca <dev@de-luca.io>
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
module.exports = (robot) ->
robot.respond /fez (.*)/i, (msg) ->
raw = msg.match[1].toLowerCase()
fez = ""
for i in [0..raw.length-1]
unless raw[i] == " "
if raw[i] in alpha
fez += ":fez-#{raw[i]}: "
else
fez += " "
msg.send fez
| 64796 | # Description:
# Translate your sentences in "FEZIAN"
# This is for Slack using the Slack-FEZ-Emoji
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot fez <your sentences>
#
# Author:
# <NAME> <<EMAIL>>
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
module.exports = (robot) ->
robot.respond /fez (.*)/i, (msg) ->
raw = msg.match[1].toLowerCase()
fez = ""
for i in [0..raw.length-1]
unless raw[i] == " "
if raw[i] in alpha
fez += ":fez-#{raw[i]}: "
else
fez += " "
msg.send fez
| true | # Description:
# Translate your sentences in "FEZIAN"
# This is for Slack using the Slack-FEZ-Emoji
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot fez <your sentences>
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
module.exports = (robot) ->
robot.respond /fez (.*)/i, (msg) ->
raw = msg.match[1].toLowerCase()
fez = ""
for i in [0..raw.length-1]
unless raw[i] == " "
if raw[i] in alpha
fez += ":fez-#{raw[i]}: "
else
fez += " "
msg.send fez
|
[
{
"context": "atal\n# Bootstrap ClojureScript React Native apps\n# Dan Motzenbecker\n# http://oxism.com\n# MIT License\n\nfs = requi",
"end": 70,
"score": 0.9998632669448853,
"start": 54,
"tag": "NAME",
"value": "Dan Motzenbecker"
}
] | natal.coffee | dmotz/natal | 456 | # Natal
# Bootstrap ClojureScript React Native apps
# Dan Motzenbecker
# http://oxism.com
# MIT License
fs = require 'fs'
net = require 'net'
http = require 'http'
crypto = require 'crypto'
child = require 'child_process'
cli = require 'commander'
chalk = require 'chalk'
semver = require 'semver'
{Tail} = require 'tail'
pkgJson = require __dirname + '/package.json'
globalVerbose = false
verboseFlag = '-v, --verbose'
verboseText = 'verbose output'
nodeVersion = pkgJson.engines.node
resources = __dirname + '/resources/'
validNameRx = /^[A-Z][0-9A-Z]*$/i
camelRx = /([a-z])([A-Z])/g
projNameRx = /\$PROJECT_NAME\$/g
projNameHyphRx = /\$PROJECT_NAME_HYPHENATED\$/g
rnVersion = '0.19.0'
rnPackagerPort = 8081
podMinVersion = '0.38.2'
rnCliMinVersion = '0.1.10'
process.title = 'natal'
reactInterfaces =
om: 'org.omcljs/om "0.9.0"'
'om-next': 'org.omcljs/om "1.0.0-alpha28"'
interfaceNames = Object.keys reactInterfaces
defaultInterface = 'om'
sampleCommands =
om: '(swap! app-state assoc :text "Hello Native World")'
'om-next': '(swap! app-state assoc :app/msg "Hello Native World")'
log = (s, color = 'green') ->
console.log chalk[color] s
logErr = (err, color = 'red') ->
console.error chalk[color] err
process.exit 1
verboseDec = (fn) ->
(..., cmd) ->
globalVerbose = cmd.verbose
fn.apply cli, arguments
exec = (cmd, keepOutput) ->
if globalVerbose and !keepOutput
return child.execSync cmd, stdio: 'inherit'
if keepOutput
child.execSync cmd
else
child.execSync cmd, stdio: 'ignore'
readFile = (path) ->
fs.readFileSync path, encoding: 'ascii'
edit = (path, pairs) ->
fs.writeFileSync path, pairs.reduce (contents, [rx, replacement]) ->
contents.replace rx, replacement
, readFile path
pluckUuid = (line) ->
line.match(/\[(.+)\]/)[1]
getUuidForDevice = (deviceName) ->
device = getDeviceList().find (line) -> line.match deviceName
unless device
logErr "Cannot find device `#{deviceName}`"
pluckUuid device
toUnderscored = (s) ->
s.replace(camelRx, '$1_$2').toLowerCase()
checkPort = (port, cb) ->
sock = net.connect {port}, ->
sock.end()
http.get "http://localhost:#{port}/status", (res) ->
data = ''
res.on 'data', (chunk) -> data += chunk
res.on 'end', ->
cb data.toString() isnt 'packager-status:running'
.on 'error', -> cb true
.setTimeout 3000
sock.on 'error', ->
sock.end()
cb false
ensureFreePort = (cb) ->
checkPort rnPackagerPort, (inUse) ->
if inUse
logErr "
Port #{rnPackagerPort} is currently in use by another process
and is needed by the React Native packager.
"
cb()
generateConfig = (name) ->
log 'Creating Natal config'
config =
name: name
device: getUuidForDevice 'iPhone 6'
writeConfig config
config
writeConfig = (config) ->
try
fs.writeFileSync '.natal', JSON.stringify config, null, 2
catch {message}
logErr \
if message.match /EACCES/i
'Invalid write permissions for creating .natal config file'
else
message
readConfig = ->
try
JSON.parse readFile '.natal'
catch {message}
logErr \
if message.match /ENOENT/i
'No Natal config was found in this directory (.natal)'
else if message.match /EACCES/i
'No read permissions for .natal'
else if message.match /Unexpected/i
'.natal contains malformed JSON'
else
message
getBundleId = (name) ->
try
if line = readFile "native/ios/#{name}.xcodeproj/project.pbxproj"
.match /PRODUCT_BUNDLE_IDENTIFIER = (.+);/
line[1]
else if line = readFile "native/ios/#{name}/Info.plist"
.match /\<key\>CFBundleIdentifier\<\/key\>\n?\s*\<string\>(.+)\<\/string\>/
rfcIdRx = /\$\(PRODUCT_NAME\:rfc1034identifier\)/
if line[1].match rfcIdRx
line[1].replace rfcIdRx, name
else
line[1]
else
throw new Error 'Cannot find bundle identifier in project.pbxproj or Info.plist'
catch {message}
logErr message
installRnCli = ->
try
exec "npm i -g react-native-cli@#{rnCliMinVersion}"
catch
logErr """
react-native-cli@#{rnCliMinVersion} is required
Run `[sudo] npm i -g react-native-cli@#{rnCliMinVersion}` then try again
"""
init = (projName, interfaceName) ->
log "Creating #{projName}", 'bgMagenta'
log ''
if projName.toLowerCase() is 'react' or !projName.match validNameRx
logErr 'Invalid project name. Use an alphanumeric CamelCase name.'
try
cliVersion = exec('react-native --version', true).toString().trim()
unless semver.satisfies rnCliMinVersion, ">=#{rnCliMinVersion}"
installRnCli()
catch
installRnCli()
projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase()
projNameUs = toUnderscored projName
try
if fs.existsSync projNameHyph
throw new Error "Directory #{projNameHyph} already exists"
exec 'type lein'
exec 'type pod'
exec 'type watchman'
exec 'type xcodebuild'
podVersion = exec('pod --version', true).toString().trim().replace /\.beta.+$/, ''
unless semver.satisfies podVersion, ">=#{podMinVersion}"
throw new Error """
Natal requires CocoaPods #{podMinVersion} or higher (you have #{podVersion}).
Run [sudo] gem update cocoapods and try again.
"""
log 'Creating Leiningen project'
exec "lein new #{projNameHyph}"
log 'Updating Leiningen project'
process.chdir projNameHyph
exec "cp #{resources}project.clj project.clj"
edit \
'project.clj',
[
[projNameHyphRx, projNameHyph]
[/\$REACT_INTERFACE\$/, reactInterfaces[interfaceName]]
]
corePath = "src/#{projNameUs}/core.clj"
fs.unlinkSync corePath
corePath += 's'
exec "cp #{resources}#{interfaceName}.cljs #{corePath}"
edit corePath, [[projNameHyphRx, projNameHyph], [projNameRx, projName]]
log 'Creating React Native skeleton'
fs.mkdirSync 'native'
process.chdir 'native'
fs.writeFileSync 'package.json', JSON.stringify
name: projName
version: '0.0.1'
private: true
scripts:
start: 'node_modules/react-native/packager/packager.sh'
dependencies:
'react-native': rnVersion
, null, 2
exec 'npm i'
exec "
node -e
\"process.argv[3]='#{projName}';
require('react-native/local-cli/cli').init('.', '#{projName}')\"
"
exec 'rm -rf android'
fs.unlinkSync 'index.android.js'
fs.appendFileSync '.gitignore', '\n# CocoaPods\n#\nios/Pods\n'
log 'Installing Pod dependencies'
process.chdir 'ios'
exec "cp #{resources}Podfile ."
edit 'Podfile', [[projNameRx, projName]]
exec 'pod install'
log 'Updating Xcode project'
for ext in ['m', 'h']
path = "#{projName}/AppDelegate.#{ext}"
exec "cp #{resources}AppDelegate.#{ext} #{path}"
edit path, [[projNameRx, projName], [projNameHyphRx, projNameHyph]]
uuid1 = crypto
.createHash 'md5'
.update projName, 'utf8'
.digest('hex')[...24]
.toUpperCase()
uuid2 = uuid1.split ''
uuid2.splice 7, 1, ((parseInt(uuid1[7], 16) + 1) % 16).toString(16).toUpperCase()
uuid2 = uuid2.join ''
edit \
"#{projName}.xcodeproj/project.pbxproj",
[
[
/OTHER_LDFLAGS = "-ObjC";/g
'OTHER_LDFLAGS = "${inherited}";'
]
[
/\/\* End PBXBuildFile section \*\//
"\t\t#{uuid2} /* out in Resources */ =
{isa = PBXBuildFile; fileRef = #{uuid1} /* out */; };
\n/* End PBXBuildFile section */"
]
[
/\/\* End PBXFileReference section \*\//
"\t\t#{uuid1} /* out */ = {isa = PBXFileReference; lastKnownFileType
= folder; name = out; path = ../../target/out;
sourceTree = \"<group>\"; };\n/* End PBXFileReference section */"
]
[
/main.jsbundle \*\/\,/
"main.jsbundle */,\n\t\t\t\t#{uuid1} /* out */,"
]
[
/\/\* LaunchScreen.xib in Resources \*\/\,/
"/* LaunchScreen.xib in Resources */,
\n\t\t\t\t#{uuid2} /* out in Resources */,"
]
]
testId = readFile("#{projName}.xcodeproj/project.pbxproj")
.match(new RegExp "([0-9A-F]+) \/\\* #{projName}Tests \\*\/ = \\{")[1]
edit \
"#{projName}.xcodeproj/xcshareddata/xcschemes/#{projName}.xcscheme",
[
[
/\<Testables\>\n\s*\<\/Testables\>/
"""
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "#{testId}"
BuildableName = "#{projName}Tests.xctest"
BlueprintName = "#{projName}Tests"
ReferencedContainer = "container:#{projName}.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
"""
]
]
process.chdir '../..'
launch generateConfig projName
log ''
log 'To get started with your new app, first cd into its directory:', 'yellow'
log "cd #{projNameHyph}", 'inverse'
log ''
log 'Boot the REPL by typing:', 'yellow'
log 'natal repl', 'inverse'
log ''
log 'At the REPL prompt type this:', 'yellow'
log "(in-ns '#{projNameHyph}.core)", 'inverse'
log ''
log 'Changes you make via the REPL or by changing your .cljs files should appear live.', 'yellow'
log ''
log 'Try this command as an example:', 'yellow'
log sampleCommands[interfaceName], 'inverse'
log ''
log '✔ Done', 'bgMagenta'
log ''
catch {message}
logErr \
if message.match /type.+lein/i
'Leiningen is required (http://leiningen.org)'
else if message.match /type.+pod/i
'CocoaPods is required (https://cocoapods.org)'
else if message.match /type.+watchman/i
'Watchman is required (https://facebook.github.io/watchman)'
else if message.match /type.+xcodebuild/i
'Xcode Command Line Tools are required'
else if message.match /npm/i
"npm install failed. This may be a network issue. Check #{projNameHyph}/native/npm-debug.log for details."
else
message
launch = ({name, device}) ->
unless device in getDeviceUuids()
log 'Device ID not available, defaulting to iPhone 6 simulator', 'yellow'
{device} = generateConfig name
try
fs.statSync 'native/node_modules'
fs.statSync 'native/ios/Pods'
catch
logErr 'Dependencies are missing. Run natal deps to install them.'
log 'Compiling ClojureScript'
exec 'lein cljsbuild once dev'
log 'Compiling Xcode project'
try
exec "
xcodebuild
-workspace native/ios/#{name}.xcworkspace
-scheme #{name}
-destination platform='iOS Simulator',OS=latest,id='#{device}'
test
"
log 'Launching simulator'
exec "xcrun simctl launch #{device} #{getBundleId name}"
catch {message}
logErr message
openXcode = (name) ->
try
exec "open native/ios/#{name}.xcworkspace"
catch {message}
logErr \
if message.match /ENOENT/i
"""
Cannot find #{name}.xcworkspace in native/ios.
Run this command from your project's root directory.
"""
else if message.match /EACCES/i
"Invalid permissions for opening #{name}.xcworkspace in native/ios"
else
message
getDeviceList = ->
try
exec 'xcrun instruments -s devices', true
.toString()
.split '\n'
.filter (line) -> /^i/.test line
catch {message}
logErr 'Device listing failed: ' + message
getDeviceUuids = ->
getDeviceList().map (line) -> line.match(/\[(.+)\]/)[1]
startRepl = (name, autoChoose) ->
try
exec 'type rlwrap'
catch
log 'Note: rlwrap is not installed but is recommended for REPL use.', 'yellow'
log 'You can optionally install it and run `rlwrap natal repl` for proper arrow key support in the REPL.\n', 'gray'
log 'Starting REPL'
try
lein = child.spawn 'lein', 'trampoline run -m clojure.main -e'.split(' ').concat(
"""
(require '[cljs.repl :as repl])
(require '[ambly.core :as ambly])
(let [repl-env (ambly/repl-env#{if autoChoose then ' :choose-first-discovered true' else ''})]
(repl/repl repl-env
:watch \"src\"
:watch-fn
(fn []
(repl/load-file repl-env \"src/#{toUnderscored name}/core.cljs\"))
:analyze-path \"src\"))
"""),
cwd: process.cwd()
env: process.env
onLeinOut = (chunk) ->
if path = chunk.toString().match /Watch compilation log available at:\s(.+)/
lein.stdout.removeListener 'data', onLeinOut
setTimeout ->
tail = new Tail path[1]
tail.on 'line', (line) ->
if line.match /^WARNING/ or line.match /failed compiling/
log line, 'red'
lein.stdin.write '\n'
else if line.match /done\. Elapsed/
log line, 'green'
lein.stdin.write '\n'
else if line.match /^Change detected/
log '\n' + line, 'white'
else if line.match /^Watching paths/
log '\n' + line, 'white'
lein.stdin.write '\n'
else if line.match /^Compiling/
log line, 'white'
else
log line, 'gray'
, 1000
lein.stdout.on 'data', onLeinOut
lein.stdout.pipe process.stdout
process.stdin.pipe lein.stdin
catch {message}
logErr message
cli._name = 'natal'
cli.version pkgJson.version
cli.command 'init <name>'
.description 'create a new ClojureScript React Native project'
.option verboseFlag, verboseText
.option "-i, --interface [#{interfaceNames.join ' '}]", 'specify React interface'
.action verboseDec (name, cmd) ->
if cmd
interfaceName = cmd['interface'] or defaultInterface
else
interfaceName = defaultInterface
unless reactInterfaces[interfaceName]
logErr "Unsupported React interface: #{interfaceName}"
if typeof name isnt 'string'
logErr '''
natal init requires a project name as the first argument.
e.g.
natal init HelloWorld
'''
ensureFreePort -> init name, interfaceName
cli.command 'launch'
.description 'compile project and run in simulator'
.option verboseFlag, verboseText
.action verboseDec ->
ensureFreePort -> launch readConfig()
cli.command 'repl'
.description 'launch a ClojureScript REPL with background compilation'
.option verboseFlag, verboseText
.option '-c, --choose', 'choose target device from list'
.action verboseDec (cmd) ->
startRepl readConfig().name, !cmd.choose
cli.command 'listdevices'
.description 'list available simulator devices by index'
.option verboseFlag, verboseText
.action verboseDec ->
console.log (getDeviceList()
.map (line, i) -> "#{i}\t#{line.replace /\[.+\]/, ''}"
.join '\n')
cli.command 'setdevice <index>'
.description 'choose simulator device by index'
.option verboseFlag, verboseText
.action verboseDec (index) ->
unless device = getDeviceList()[parseInt index, 10]
logErr 'Invalid device index. Run natal listdevices for valid indexes.'
config = readConfig()
config.device = pluckUuid device
writeConfig config
cli.command 'xcode'
.description 'open Xcode project'
.option verboseFlag, verboseText
.action verboseDec ->
openXcode readConfig().name
cli.command 'deps'
.description 'install all dependencies for the project'
.option verboseFlag, verboseText
.option '-l, --lein', 'Leiningen jars only'
.option '-n, --npm', 'npm packages only'
.option '-p, --pods', 'pods only'
.action verboseDec (cmd) ->
all = ['lein', 'npm', 'pods'].every (o) -> !cmd[o]
try
if all or cmd.lein
log 'Installing Leiningen jars'
exec 'lein deps'
if all or cmd.npm
process.chdir 'native'
log 'Installing npm packages'
exec 'npm i'
if all or cmd.pods
log 'Installing pods'
process.chdir if all or cmd.npm then 'ios' else 'native/ios'
exec 'pod install'
catch {message}
logErr message
cli.on '*', (command) ->
logErr "unknown command #{command[0]}. See natal --help for valid commands"
unless semver.satisfies process.version[1...], nodeVersion
logErr """
Natal requires Node.js version #{nodeVersion}
You have #{process.version[1...]}
"""
if process.argv.length <= 2
cli.outputHelp()
else
cli.parse process.argv
| 61596 | # Natal
# Bootstrap ClojureScript React Native apps
# <NAME>
# http://oxism.com
# MIT License
fs = require 'fs'
net = require 'net'
http = require 'http'
crypto = require 'crypto'
child = require 'child_process'
cli = require 'commander'
chalk = require 'chalk'
semver = require 'semver'
{Tail} = require 'tail'
pkgJson = require __dirname + '/package.json'
globalVerbose = false
verboseFlag = '-v, --verbose'
verboseText = 'verbose output'
nodeVersion = pkgJson.engines.node
resources = __dirname + '/resources/'
validNameRx = /^[A-Z][0-9A-Z]*$/i
camelRx = /([a-z])([A-Z])/g
projNameRx = /\$PROJECT_NAME\$/g
projNameHyphRx = /\$PROJECT_NAME_HYPHENATED\$/g
rnVersion = '0.19.0'
rnPackagerPort = 8081
podMinVersion = '0.38.2'
rnCliMinVersion = '0.1.10'
process.title = 'natal'
reactInterfaces =
om: 'org.omcljs/om "0.9.0"'
'om-next': 'org.omcljs/om "1.0.0-alpha28"'
interfaceNames = Object.keys reactInterfaces
defaultInterface = 'om'
sampleCommands =
om: '(swap! app-state assoc :text "Hello Native World")'
'om-next': '(swap! app-state assoc :app/msg "Hello Native World")'
log = (s, color = 'green') ->
console.log chalk[color] s
logErr = (err, color = 'red') ->
console.error chalk[color] err
process.exit 1
verboseDec = (fn) ->
(..., cmd) ->
globalVerbose = cmd.verbose
fn.apply cli, arguments
exec = (cmd, keepOutput) ->
if globalVerbose and !keepOutput
return child.execSync cmd, stdio: 'inherit'
if keepOutput
child.execSync cmd
else
child.execSync cmd, stdio: 'ignore'
readFile = (path) ->
fs.readFileSync path, encoding: 'ascii'
edit = (path, pairs) ->
fs.writeFileSync path, pairs.reduce (contents, [rx, replacement]) ->
contents.replace rx, replacement
, readFile path
pluckUuid = (line) ->
line.match(/\[(.+)\]/)[1]
getUuidForDevice = (deviceName) ->
device = getDeviceList().find (line) -> line.match deviceName
unless device
logErr "Cannot find device `#{deviceName}`"
pluckUuid device
toUnderscored = (s) ->
s.replace(camelRx, '$1_$2').toLowerCase()
checkPort = (port, cb) ->
sock = net.connect {port}, ->
sock.end()
http.get "http://localhost:#{port}/status", (res) ->
data = ''
res.on 'data', (chunk) -> data += chunk
res.on 'end', ->
cb data.toString() isnt 'packager-status:running'
.on 'error', -> cb true
.setTimeout 3000
sock.on 'error', ->
sock.end()
cb false
ensureFreePort = (cb) ->
checkPort rnPackagerPort, (inUse) ->
if inUse
logErr "
Port #{rnPackagerPort} is currently in use by another process
and is needed by the React Native packager.
"
cb()
generateConfig = (name) ->
log 'Creating Natal config'
config =
name: name
device: getUuidForDevice 'iPhone 6'
writeConfig config
config
writeConfig = (config) ->
try
fs.writeFileSync '.natal', JSON.stringify config, null, 2
catch {message}
logErr \
if message.match /EACCES/i
'Invalid write permissions for creating .natal config file'
else
message
readConfig = ->
try
JSON.parse readFile '.natal'
catch {message}
logErr \
if message.match /ENOENT/i
'No Natal config was found in this directory (.natal)'
else if message.match /EACCES/i
'No read permissions for .natal'
else if message.match /Unexpected/i
'.natal contains malformed JSON'
else
message
getBundleId = (name) ->
try
if line = readFile "native/ios/#{name}.xcodeproj/project.pbxproj"
.match /PRODUCT_BUNDLE_IDENTIFIER = (.+);/
line[1]
else if line = readFile "native/ios/#{name}/Info.plist"
.match /\<key\>CFBundleIdentifier\<\/key\>\n?\s*\<string\>(.+)\<\/string\>/
rfcIdRx = /\$\(PRODUCT_NAME\:rfc1034identifier\)/
if line[1].match rfcIdRx
line[1].replace rfcIdRx, name
else
line[1]
else
throw new Error 'Cannot find bundle identifier in project.pbxproj or Info.plist'
catch {message}
logErr message
installRnCli = ->
try
exec "npm i -g react-native-cli@#{rnCliMinVersion}"
catch
logErr """
react-native-cli@#{rnCliMinVersion} is required
Run `[sudo] npm i -g react-native-cli@#{rnCliMinVersion}` then try again
"""
init = (projName, interfaceName) ->
log "Creating #{projName}", 'bgMagenta'
log ''
if projName.toLowerCase() is 'react' or !projName.match validNameRx
logErr 'Invalid project name. Use an alphanumeric CamelCase name.'
try
cliVersion = exec('react-native --version', true).toString().trim()
unless semver.satisfies rnCliMinVersion, ">=#{rnCliMinVersion}"
installRnCli()
catch
installRnCli()
projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase()
projNameUs = toUnderscored projName
try
if fs.existsSync projNameHyph
throw new Error "Directory #{projNameHyph} already exists"
exec 'type lein'
exec 'type pod'
exec 'type watchman'
exec 'type xcodebuild'
podVersion = exec('pod --version', true).toString().trim().replace /\.beta.+$/, ''
unless semver.satisfies podVersion, ">=#{podMinVersion}"
throw new Error """
Natal requires CocoaPods #{podMinVersion} or higher (you have #{podVersion}).
Run [sudo] gem update cocoapods and try again.
"""
log 'Creating Leiningen project'
exec "lein new #{projNameHyph}"
log 'Updating Leiningen project'
process.chdir projNameHyph
exec "cp #{resources}project.clj project.clj"
edit \
'project.clj',
[
[projNameHyphRx, projNameHyph]
[/\$REACT_INTERFACE\$/, reactInterfaces[interfaceName]]
]
corePath = "src/#{projNameUs}/core.clj"
fs.unlinkSync corePath
corePath += 's'
exec "cp #{resources}#{interfaceName}.cljs #{corePath}"
edit corePath, [[projNameHyphRx, projNameHyph], [projNameRx, projName]]
log 'Creating React Native skeleton'
fs.mkdirSync 'native'
process.chdir 'native'
fs.writeFileSync 'package.json', JSON.stringify
name: projName
version: '0.0.1'
private: true
scripts:
start: 'node_modules/react-native/packager/packager.sh'
dependencies:
'react-native': rnVersion
, null, 2
exec 'npm i'
exec "
node -e
\"process.argv[3]='#{projName}';
require('react-native/local-cli/cli').init('.', '#{projName}')\"
"
exec 'rm -rf android'
fs.unlinkSync 'index.android.js'
fs.appendFileSync '.gitignore', '\n# CocoaPods\n#\nios/Pods\n'
log 'Installing Pod dependencies'
process.chdir 'ios'
exec "cp #{resources}Podfile ."
edit 'Podfile', [[projNameRx, projName]]
exec 'pod install'
log 'Updating Xcode project'
for ext in ['m', 'h']
path = "#{projName}/AppDelegate.#{ext}"
exec "cp #{resources}AppDelegate.#{ext} #{path}"
edit path, [[projNameRx, projName], [projNameHyphRx, projNameHyph]]
uuid1 = crypto
.createHash 'md5'
.update projName, 'utf8'
.digest('hex')[...24]
.toUpperCase()
uuid2 = uuid1.split ''
uuid2.splice 7, 1, ((parseInt(uuid1[7], 16) + 1) % 16).toString(16).toUpperCase()
uuid2 = uuid2.join ''
edit \
"#{projName}.xcodeproj/project.pbxproj",
[
[
/OTHER_LDFLAGS = "-ObjC";/g
'OTHER_LDFLAGS = "${inherited}";'
]
[
/\/\* End PBXBuildFile section \*\//
"\t\t#{uuid2} /* out in Resources */ =
{isa = PBXBuildFile; fileRef = #{uuid1} /* out */; };
\n/* End PBXBuildFile section */"
]
[
/\/\* End PBXFileReference section \*\//
"\t\t#{uuid1} /* out */ = {isa = PBXFileReference; lastKnownFileType
= folder; name = out; path = ../../target/out;
sourceTree = \"<group>\"; };\n/* End PBXFileReference section */"
]
[
/main.jsbundle \*\/\,/
"main.jsbundle */,\n\t\t\t\t#{uuid1} /* out */,"
]
[
/\/\* LaunchScreen.xib in Resources \*\/\,/
"/* LaunchScreen.xib in Resources */,
\n\t\t\t\t#{uuid2} /* out in Resources */,"
]
]
testId = readFile("#{projName}.xcodeproj/project.pbxproj")
.match(new RegExp "([0-9A-F]+) \/\\* #{projName}Tests \\*\/ = \\{")[1]
edit \
"#{projName}.xcodeproj/xcshareddata/xcschemes/#{projName}.xcscheme",
[
[
/\<Testables\>\n\s*\<\/Testables\>/
"""
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "#{testId}"
BuildableName = "#{projName}Tests.xctest"
BlueprintName = "#{projName}Tests"
ReferencedContainer = "container:#{projName}.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
"""
]
]
process.chdir '../..'
launch generateConfig projName
log ''
log 'To get started with your new app, first cd into its directory:', 'yellow'
log "cd #{projNameHyph}", 'inverse'
log ''
log 'Boot the REPL by typing:', 'yellow'
log 'natal repl', 'inverse'
log ''
log 'At the REPL prompt type this:', 'yellow'
log "(in-ns '#{projNameHyph}.core)", 'inverse'
log ''
log 'Changes you make via the REPL or by changing your .cljs files should appear live.', 'yellow'
log ''
log 'Try this command as an example:', 'yellow'
log sampleCommands[interfaceName], 'inverse'
log ''
log '✔ Done', 'bgMagenta'
log ''
catch {message}
logErr \
if message.match /type.+lein/i
'Leiningen is required (http://leiningen.org)'
else if message.match /type.+pod/i
'CocoaPods is required (https://cocoapods.org)'
else if message.match /type.+watchman/i
'Watchman is required (https://facebook.github.io/watchman)'
else if message.match /type.+xcodebuild/i
'Xcode Command Line Tools are required'
else if message.match /npm/i
"npm install failed. This may be a network issue. Check #{projNameHyph}/native/npm-debug.log for details."
else
message
launch = ({name, device}) ->
unless device in getDeviceUuids()
log 'Device ID not available, defaulting to iPhone 6 simulator', 'yellow'
{device} = generateConfig name
try
fs.statSync 'native/node_modules'
fs.statSync 'native/ios/Pods'
catch
logErr 'Dependencies are missing. Run natal deps to install them.'
log 'Compiling ClojureScript'
exec 'lein cljsbuild once dev'
log 'Compiling Xcode project'
try
exec "
xcodebuild
-workspace native/ios/#{name}.xcworkspace
-scheme #{name}
-destination platform='iOS Simulator',OS=latest,id='#{device}'
test
"
log 'Launching simulator'
exec "xcrun simctl launch #{device} #{getBundleId name}"
catch {message}
logErr message
openXcode = (name) ->
try
exec "open native/ios/#{name}.xcworkspace"
catch {message}
logErr \
if message.match /ENOENT/i
"""
Cannot find #{name}.xcworkspace in native/ios.
Run this command from your project's root directory.
"""
else if message.match /EACCES/i
"Invalid permissions for opening #{name}.xcworkspace in native/ios"
else
message
getDeviceList = ->
try
exec 'xcrun instruments -s devices', true
.toString()
.split '\n'
.filter (line) -> /^i/.test line
catch {message}
logErr 'Device listing failed: ' + message
getDeviceUuids = ->
getDeviceList().map (line) -> line.match(/\[(.+)\]/)[1]
startRepl = (name, autoChoose) ->
try
exec 'type rlwrap'
catch
log 'Note: rlwrap is not installed but is recommended for REPL use.', 'yellow'
log 'You can optionally install it and run `rlwrap natal repl` for proper arrow key support in the REPL.\n', 'gray'
log 'Starting REPL'
try
lein = child.spawn 'lein', 'trampoline run -m clojure.main -e'.split(' ').concat(
"""
(require '[cljs.repl :as repl])
(require '[ambly.core :as ambly])
(let [repl-env (ambly/repl-env#{if autoChoose then ' :choose-first-discovered true' else ''})]
(repl/repl repl-env
:watch \"src\"
:watch-fn
(fn []
(repl/load-file repl-env \"src/#{toUnderscored name}/core.cljs\"))
:analyze-path \"src\"))
"""),
cwd: process.cwd()
env: process.env
onLeinOut = (chunk) ->
if path = chunk.toString().match /Watch compilation log available at:\s(.+)/
lein.stdout.removeListener 'data', onLeinOut
setTimeout ->
tail = new Tail path[1]
tail.on 'line', (line) ->
if line.match /^WARNING/ or line.match /failed compiling/
log line, 'red'
lein.stdin.write '\n'
else if line.match /done\. Elapsed/
log line, 'green'
lein.stdin.write '\n'
else if line.match /^Change detected/
log '\n' + line, 'white'
else if line.match /^Watching paths/
log '\n' + line, 'white'
lein.stdin.write '\n'
else if line.match /^Compiling/
log line, 'white'
else
log line, 'gray'
, 1000
lein.stdout.on 'data', onLeinOut
lein.stdout.pipe process.stdout
process.stdin.pipe lein.stdin
catch {message}
logErr message
cli._name = 'natal'
cli.version pkgJson.version
cli.command 'init <name>'
.description 'create a new ClojureScript React Native project'
.option verboseFlag, verboseText
.option "-i, --interface [#{interfaceNames.join ' '}]", 'specify React interface'
.action verboseDec (name, cmd) ->
if cmd
interfaceName = cmd['interface'] or defaultInterface
else
interfaceName = defaultInterface
unless reactInterfaces[interfaceName]
logErr "Unsupported React interface: #{interfaceName}"
if typeof name isnt 'string'
logErr '''
natal init requires a project name as the first argument.
e.g.
natal init HelloWorld
'''
ensureFreePort -> init name, interfaceName
cli.command 'launch'
.description 'compile project and run in simulator'
.option verboseFlag, verboseText
.action verboseDec ->
ensureFreePort -> launch readConfig()
cli.command 'repl'
.description 'launch a ClojureScript REPL with background compilation'
.option verboseFlag, verboseText
.option '-c, --choose', 'choose target device from list'
.action verboseDec (cmd) ->
startRepl readConfig().name, !cmd.choose
cli.command 'listdevices'
.description 'list available simulator devices by index'
.option verboseFlag, verboseText
.action verboseDec ->
console.log (getDeviceList()
.map (line, i) -> "#{i}\t#{line.replace /\[.+\]/, ''}"
.join '\n')
cli.command 'setdevice <index>'
.description 'choose simulator device by index'
.option verboseFlag, verboseText
.action verboseDec (index) ->
unless device = getDeviceList()[parseInt index, 10]
logErr 'Invalid device index. Run natal listdevices for valid indexes.'
config = readConfig()
config.device = pluckUuid device
writeConfig config
cli.command 'xcode'
.description 'open Xcode project'
.option verboseFlag, verboseText
.action verboseDec ->
openXcode readConfig().name
cli.command 'deps'
.description 'install all dependencies for the project'
.option verboseFlag, verboseText
.option '-l, --lein', 'Leiningen jars only'
.option '-n, --npm', 'npm packages only'
.option '-p, --pods', 'pods only'
.action verboseDec (cmd) ->
all = ['lein', 'npm', 'pods'].every (o) -> !cmd[o]
try
if all or cmd.lein
log 'Installing Leiningen jars'
exec 'lein deps'
if all or cmd.npm
process.chdir 'native'
log 'Installing npm packages'
exec 'npm i'
if all or cmd.pods
log 'Installing pods'
process.chdir if all or cmd.npm then 'ios' else 'native/ios'
exec 'pod install'
catch {message}
logErr message
cli.on '*', (command) ->
logErr "unknown command #{command[0]}. See natal --help for valid commands"
unless semver.satisfies process.version[1...], nodeVersion
logErr """
Natal requires Node.js version #{nodeVersion}
You have #{process.version[1...]}
"""
if process.argv.length <= 2
cli.outputHelp()
else
cli.parse process.argv
| true | # Natal
# Bootstrap ClojureScript React Native apps
# PI:NAME:<NAME>END_PI
# http://oxism.com
# MIT License
fs = require 'fs'
net = require 'net'
http = require 'http'
crypto = require 'crypto'
child = require 'child_process'
cli = require 'commander'
chalk = require 'chalk'
semver = require 'semver'
{Tail} = require 'tail'
pkgJson = require __dirname + '/package.json'
globalVerbose = false
verboseFlag = '-v, --verbose'
verboseText = 'verbose output'
nodeVersion = pkgJson.engines.node
resources = __dirname + '/resources/'
validNameRx = /^[A-Z][0-9A-Z]*$/i
camelRx = /([a-z])([A-Z])/g
projNameRx = /\$PROJECT_NAME\$/g
projNameHyphRx = /\$PROJECT_NAME_HYPHENATED\$/g
rnVersion = '0.19.0'
rnPackagerPort = 8081
podMinVersion = '0.38.2'
rnCliMinVersion = '0.1.10'
process.title = 'natal'
reactInterfaces =
om: 'org.omcljs/om "0.9.0"'
'om-next': 'org.omcljs/om "1.0.0-alpha28"'
interfaceNames = Object.keys reactInterfaces
defaultInterface = 'om'
sampleCommands =
om: '(swap! app-state assoc :text "Hello Native World")'
'om-next': '(swap! app-state assoc :app/msg "Hello Native World")'
log = (s, color = 'green') ->
console.log chalk[color] s
logErr = (err, color = 'red') ->
console.error chalk[color] err
process.exit 1
verboseDec = (fn) ->
(..., cmd) ->
globalVerbose = cmd.verbose
fn.apply cli, arguments
exec = (cmd, keepOutput) ->
if globalVerbose and !keepOutput
return child.execSync cmd, stdio: 'inherit'
if keepOutput
child.execSync cmd
else
child.execSync cmd, stdio: 'ignore'
readFile = (path) ->
fs.readFileSync path, encoding: 'ascii'
edit = (path, pairs) ->
fs.writeFileSync path, pairs.reduce (contents, [rx, replacement]) ->
contents.replace rx, replacement
, readFile path
pluckUuid = (line) ->
line.match(/\[(.+)\]/)[1]
getUuidForDevice = (deviceName) ->
device = getDeviceList().find (line) -> line.match deviceName
unless device
logErr "Cannot find device `#{deviceName}`"
pluckUuid device
toUnderscored = (s) ->
s.replace(camelRx, '$1_$2').toLowerCase()
checkPort = (port, cb) ->
sock = net.connect {port}, ->
sock.end()
http.get "http://localhost:#{port}/status", (res) ->
data = ''
res.on 'data', (chunk) -> data += chunk
res.on 'end', ->
cb data.toString() isnt 'packager-status:running'
.on 'error', -> cb true
.setTimeout 3000
sock.on 'error', ->
sock.end()
cb false
ensureFreePort = (cb) ->
checkPort rnPackagerPort, (inUse) ->
if inUse
logErr "
Port #{rnPackagerPort} is currently in use by another process
and is needed by the React Native packager.
"
cb()
generateConfig = (name) ->
log 'Creating Natal config'
config =
name: name
device: getUuidForDevice 'iPhone 6'
writeConfig config
config
writeConfig = (config) ->
try
fs.writeFileSync '.natal', JSON.stringify config, null, 2
catch {message}
logErr \
if message.match /EACCES/i
'Invalid write permissions for creating .natal config file'
else
message
readConfig = ->
try
JSON.parse readFile '.natal'
catch {message}
logErr \
if message.match /ENOENT/i
'No Natal config was found in this directory (.natal)'
else if message.match /EACCES/i
'No read permissions for .natal'
else if message.match /Unexpected/i
'.natal contains malformed JSON'
else
message
getBundleId = (name) ->
try
if line = readFile "native/ios/#{name}.xcodeproj/project.pbxproj"
.match /PRODUCT_BUNDLE_IDENTIFIER = (.+);/
line[1]
else if line = readFile "native/ios/#{name}/Info.plist"
.match /\<key\>CFBundleIdentifier\<\/key\>\n?\s*\<string\>(.+)\<\/string\>/
rfcIdRx = /\$\(PRODUCT_NAME\:rfc1034identifier\)/
if line[1].match rfcIdRx
line[1].replace rfcIdRx, name
else
line[1]
else
throw new Error 'Cannot find bundle identifier in project.pbxproj or Info.plist'
catch {message}
logErr message
installRnCli = ->
try
exec "npm i -g react-native-cli@#{rnCliMinVersion}"
catch
logErr """
react-native-cli@#{rnCliMinVersion} is required
Run `[sudo] npm i -g react-native-cli@#{rnCliMinVersion}` then try again
"""
init = (projName, interfaceName) ->
log "Creating #{projName}", 'bgMagenta'
log ''
if projName.toLowerCase() is 'react' or !projName.match validNameRx
logErr 'Invalid project name. Use an alphanumeric CamelCase name.'
try
cliVersion = exec('react-native --version', true).toString().trim()
unless semver.satisfies rnCliMinVersion, ">=#{rnCliMinVersion}"
installRnCli()
catch
installRnCli()
projNameHyph = projName.replace(camelRx, '$1-$2').toLowerCase()
projNameUs = toUnderscored projName
try
if fs.existsSync projNameHyph
throw new Error "Directory #{projNameHyph} already exists"
exec 'type lein'
exec 'type pod'
exec 'type watchman'
exec 'type xcodebuild'
podVersion = exec('pod --version', true).toString().trim().replace /\.beta.+$/, ''
unless semver.satisfies podVersion, ">=#{podMinVersion}"
throw new Error """
Natal requires CocoaPods #{podMinVersion} or higher (you have #{podVersion}).
Run [sudo] gem update cocoapods and try again.
"""
log 'Creating Leiningen project'
exec "lein new #{projNameHyph}"
log 'Updating Leiningen project'
process.chdir projNameHyph
exec "cp #{resources}project.clj project.clj"
edit \
'project.clj',
[
[projNameHyphRx, projNameHyph]
[/\$REACT_INTERFACE\$/, reactInterfaces[interfaceName]]
]
corePath = "src/#{projNameUs}/core.clj"
fs.unlinkSync corePath
corePath += 's'
exec "cp #{resources}#{interfaceName}.cljs #{corePath}"
edit corePath, [[projNameHyphRx, projNameHyph], [projNameRx, projName]]
log 'Creating React Native skeleton'
fs.mkdirSync 'native'
process.chdir 'native'
fs.writeFileSync 'package.json', JSON.stringify
name: projName
version: '0.0.1'
private: true
scripts:
start: 'node_modules/react-native/packager/packager.sh'
dependencies:
'react-native': rnVersion
, null, 2
exec 'npm i'
exec "
node -e
\"process.argv[3]='#{projName}';
require('react-native/local-cli/cli').init('.', '#{projName}')\"
"
exec 'rm -rf android'
fs.unlinkSync 'index.android.js'
fs.appendFileSync '.gitignore', '\n# CocoaPods\n#\nios/Pods\n'
log 'Installing Pod dependencies'
process.chdir 'ios'
exec "cp #{resources}Podfile ."
edit 'Podfile', [[projNameRx, projName]]
exec 'pod install'
log 'Updating Xcode project'
for ext in ['m', 'h']
path = "#{projName}/AppDelegate.#{ext}"
exec "cp #{resources}AppDelegate.#{ext} #{path}"
edit path, [[projNameRx, projName], [projNameHyphRx, projNameHyph]]
uuid1 = crypto
.createHash 'md5'
.update projName, 'utf8'
.digest('hex')[...24]
.toUpperCase()
uuid2 = uuid1.split ''
uuid2.splice 7, 1, ((parseInt(uuid1[7], 16) + 1) % 16).toString(16).toUpperCase()
uuid2 = uuid2.join ''
edit \
"#{projName}.xcodeproj/project.pbxproj",
[
[
/OTHER_LDFLAGS = "-ObjC";/g
'OTHER_LDFLAGS = "${inherited}";'
]
[
/\/\* End PBXBuildFile section \*\//
"\t\t#{uuid2} /* out in Resources */ =
{isa = PBXBuildFile; fileRef = #{uuid1} /* out */; };
\n/* End PBXBuildFile section */"
]
[
/\/\* End PBXFileReference section \*\//
"\t\t#{uuid1} /* out */ = {isa = PBXFileReference; lastKnownFileType
= folder; name = out; path = ../../target/out;
sourceTree = \"<group>\"; };\n/* End PBXFileReference section */"
]
[
/main.jsbundle \*\/\,/
"main.jsbundle */,\n\t\t\t\t#{uuid1} /* out */,"
]
[
/\/\* LaunchScreen.xib in Resources \*\/\,/
"/* LaunchScreen.xib in Resources */,
\n\t\t\t\t#{uuid2} /* out in Resources */,"
]
]
testId = readFile("#{projName}.xcodeproj/project.pbxproj")
.match(new RegExp "([0-9A-F]+) \/\\* #{projName}Tests \\*\/ = \\{")[1]
edit \
"#{projName}.xcodeproj/xcshareddata/xcschemes/#{projName}.xcscheme",
[
[
/\<Testables\>\n\s*\<\/Testables\>/
"""
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "#{testId}"
BuildableName = "#{projName}Tests.xctest"
BlueprintName = "#{projName}Tests"
ReferencedContainer = "container:#{projName}.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
"""
]
]
process.chdir '../..'
launch generateConfig projName
log ''
log 'To get started with your new app, first cd into its directory:', 'yellow'
log "cd #{projNameHyph}", 'inverse'
log ''
log 'Boot the REPL by typing:', 'yellow'
log 'natal repl', 'inverse'
log ''
log 'At the REPL prompt type this:', 'yellow'
log "(in-ns '#{projNameHyph}.core)", 'inverse'
log ''
log 'Changes you make via the REPL or by changing your .cljs files should appear live.', 'yellow'
log ''
log 'Try this command as an example:', 'yellow'
log sampleCommands[interfaceName], 'inverse'
log ''
log '✔ Done', 'bgMagenta'
log ''
catch {message}
logErr \
if message.match /type.+lein/i
'Leiningen is required (http://leiningen.org)'
else if message.match /type.+pod/i
'CocoaPods is required (https://cocoapods.org)'
else if message.match /type.+watchman/i
'Watchman is required (https://facebook.github.io/watchman)'
else if message.match /type.+xcodebuild/i
'Xcode Command Line Tools are required'
else if message.match /npm/i
"npm install failed. This may be a network issue. Check #{projNameHyph}/native/npm-debug.log for details."
else
message
launch = ({name, device}) ->
unless device in getDeviceUuids()
log 'Device ID not available, defaulting to iPhone 6 simulator', 'yellow'
{device} = generateConfig name
try
fs.statSync 'native/node_modules'
fs.statSync 'native/ios/Pods'
catch
logErr 'Dependencies are missing. Run natal deps to install them.'
log 'Compiling ClojureScript'
exec 'lein cljsbuild once dev'
log 'Compiling Xcode project'
try
exec "
xcodebuild
-workspace native/ios/#{name}.xcworkspace
-scheme #{name}
-destination platform='iOS Simulator',OS=latest,id='#{device}'
test
"
log 'Launching simulator'
exec "xcrun simctl launch #{device} #{getBundleId name}"
catch {message}
logErr message
openXcode = (name) ->
try
exec "open native/ios/#{name}.xcworkspace"
catch {message}
logErr \
if message.match /ENOENT/i
"""
Cannot find #{name}.xcworkspace in native/ios.
Run this command from your project's root directory.
"""
else if message.match /EACCES/i
"Invalid permissions for opening #{name}.xcworkspace in native/ios"
else
message
getDeviceList = ->
try
exec 'xcrun instruments -s devices', true
.toString()
.split '\n'
.filter (line) -> /^i/.test line
catch {message}
logErr 'Device listing failed: ' + message
getDeviceUuids = ->
getDeviceList().map (line) -> line.match(/\[(.+)\]/)[1]
startRepl = (name, autoChoose) ->
try
exec 'type rlwrap'
catch
log 'Note: rlwrap is not installed but is recommended for REPL use.', 'yellow'
log 'You can optionally install it and run `rlwrap natal repl` for proper arrow key support in the REPL.\n', 'gray'
log 'Starting REPL'
try
lein = child.spawn 'lein', 'trampoline run -m clojure.main -e'.split(' ').concat(
"""
(require '[cljs.repl :as repl])
(require '[ambly.core :as ambly])
(let [repl-env (ambly/repl-env#{if autoChoose then ' :choose-first-discovered true' else ''})]
(repl/repl repl-env
:watch \"src\"
:watch-fn
(fn []
(repl/load-file repl-env \"src/#{toUnderscored name}/core.cljs\"))
:analyze-path \"src\"))
"""),
cwd: process.cwd()
env: process.env
onLeinOut = (chunk) ->
if path = chunk.toString().match /Watch compilation log available at:\s(.+)/
lein.stdout.removeListener 'data', onLeinOut
setTimeout ->
tail = new Tail path[1]
tail.on 'line', (line) ->
if line.match /^WARNING/ or line.match /failed compiling/
log line, 'red'
lein.stdin.write '\n'
else if line.match /done\. Elapsed/
log line, 'green'
lein.stdin.write '\n'
else if line.match /^Change detected/
log '\n' + line, 'white'
else if line.match /^Watching paths/
log '\n' + line, 'white'
lein.stdin.write '\n'
else if line.match /^Compiling/
log line, 'white'
else
log line, 'gray'
, 1000
lein.stdout.on 'data', onLeinOut
lein.stdout.pipe process.stdout
process.stdin.pipe lein.stdin
catch {message}
logErr message
cli._name = 'natal'
cli.version pkgJson.version
cli.command 'init <name>'
.description 'create a new ClojureScript React Native project'
.option verboseFlag, verboseText
.option "-i, --interface [#{interfaceNames.join ' '}]", 'specify React interface'
.action verboseDec (name, cmd) ->
if cmd
interfaceName = cmd['interface'] or defaultInterface
else
interfaceName = defaultInterface
unless reactInterfaces[interfaceName]
logErr "Unsupported React interface: #{interfaceName}"
if typeof name isnt 'string'
logErr '''
natal init requires a project name as the first argument.
e.g.
natal init HelloWorld
'''
ensureFreePort -> init name, interfaceName
cli.command 'launch'
.description 'compile project and run in simulator'
.option verboseFlag, verboseText
.action verboseDec ->
ensureFreePort -> launch readConfig()
cli.command 'repl'
.description 'launch a ClojureScript REPL with background compilation'
.option verboseFlag, verboseText
.option '-c, --choose', 'choose target device from list'
.action verboseDec (cmd) ->
startRepl readConfig().name, !cmd.choose
cli.command 'listdevices'
.description 'list available simulator devices by index'
.option verboseFlag, verboseText
.action verboseDec ->
console.log (getDeviceList()
.map (line, i) -> "#{i}\t#{line.replace /\[.+\]/, ''}"
.join '\n')
cli.command 'setdevice <index>'
.description 'choose simulator device by index'
.option verboseFlag, verboseText
.action verboseDec (index) ->
unless device = getDeviceList()[parseInt index, 10]
logErr 'Invalid device index. Run natal listdevices for valid indexes.'
config = readConfig()
config.device = pluckUuid device
writeConfig config
cli.command 'xcode'
.description 'open Xcode project'
.option verboseFlag, verboseText
.action verboseDec ->
openXcode readConfig().name
cli.command 'deps'
.description 'install all dependencies for the project'
.option verboseFlag, verboseText
.option '-l, --lein', 'Leiningen jars only'
.option '-n, --npm', 'npm packages only'
.option '-p, --pods', 'pods only'
.action verboseDec (cmd) ->
all = ['lein', 'npm', 'pods'].every (o) -> !cmd[o]
try
if all or cmd.lein
log 'Installing Leiningen jars'
exec 'lein deps'
if all or cmd.npm
process.chdir 'native'
log 'Installing npm packages'
exec 'npm i'
if all or cmd.pods
log 'Installing pods'
process.chdir if all or cmd.npm then 'ios' else 'native/ios'
exec 'pod install'
catch {message}
logErr message
cli.on '*', (command) ->
logErr "unknown command #{command[0]}. See natal --help for valid commands"
unless semver.satisfies process.version[1...], nodeVersion
logErr """
Natal requires Node.js version #{nodeVersion}
You have #{process.version[1...]}
"""
if process.argv.length <= 2
cli.outputHelp()
else
cli.parse process.argv
|
[
{
"context": " agentOneAuthorization = \"Basic #{new Buffer( \"test+one@joukou.com:password\" ).toString( 'base64' )}\"\n\n after ( d",
"end": 1947,
"score": 0.9999111890792847,
"start": 1928,
"tag": "EMAIL",
"value": "test+one@joukou.com"
},
{
"context": "ation = \"Basic #{new... | test/routes.coffee | joukou/joukou-api | 0 | ###*
Copyright 2014 Joukou Ltd
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.
###
assert = require( 'assert' )
chai = require( 'chai' )
should = chai.should()
chai.use( require( 'chai-http' ) )
server = require( '../dist/server' )
riakpbc = require( '../dist/riak/pbc' )
log = ( v ) ->
console.log(require('util').inspect(v, depth: 10))
describe 'GET /', ->
specify 'responds 200 OK with a representation of the entry point', ( done ) ->
chai.request( server )
.get( '/' )
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: '/'
'joukou:agent-authn': [
{
title: 'Authenticate'
href: '/agent/authenticate'
}
]
'joukou:contact': [
{
title: 'Send a Message to Joukou'
href: '/contact'
}
]
'joukou:agent-create': [
{
title: 'Create an Agent'
href: '/agent'
}
]
)
done()
)
xdescribe 'POST /agent', ->
agentOneKey = null
agentOneAuthorization = "Basic #{new Buffer( "test+one@joukou.com:password" ).toString( 'base64' )}"
after ( done ) ->
riakpbc.del(
type: 'agent'
bucket: 'agent'
key: agentOneKey
, ( err, reply ) -> done( err ) )
specify 'responds 201 Created with a representation containing a link to the created agent in the given data is valid', ( done ) ->
chai.request( server )
.post( '/agent' )
.req( ( req ) ->
req.type( 'json' )
req.send(
email: 'test+one@joukou.com'
password: 'password'
)
)
.res( ( res ) ->
res.should.have.status( 201 )
res.headers.location.should.match( /^\/agent\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ )
agentOneKey = res.headers.location.match( /^\/agent\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ]
res.body.should.deep.equal(
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: '/agent'
'joukou:agent': [
{
href: "/agent/#{agentOneKey}"
}
]
)
done()
)
specify 'responds 403 Forbidden with a representation of the error if the given data in invalid', ( done ) ->
chai.request( server )
.post( '/agent' )
.req( ( req ) ->
req.type( 'json' )
)
.res( ( res ) ->
res.should.have.status( 403 )
done()
)
describe 'GET /agent/:agentKey', ->
specify 'responds 200 OK with a representation of the agent if the agent key is valid', ( done ) ->
chai.request( server )
.get( "/agent/#{agentOneKey}" )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
email: 'test+one@joukou.com'
_links:
curies: [
{
name: 'joukou',
templated: true,
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: "/agent/#{agentOneKey}"
'joukou:personas': [
{
title: 'List of Personas'
href: '/persona'
}
]
)
done()
)
specify 'responds 401 Unauthorized with a representation of the error if the agent key is invalid', ( done ) ->
chai.request( server )
.get( "/agent/c4b56b5e-0d47-4c8d-abd8-31f41c164b34" )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 401 )
done()
)
describe 'POST /agent/authenticate', ->
specify 'responds 200 OK with a representation containing a JSON Web Token if the provided Authorization header is authenticated', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 200 )
should.exist( res.body.token )
res.body.token.should.be.a( 'string' )
res.body.should.deep.equal(
token: res.body.token
_links:
curies: [
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
]
self:
href: '/agent/authenticate'
'joukou:agent': [
{
href: "/agent/#{agentOneKey}"
}
]
'joukou:personas': [
{
href: '/persona'
title: 'List of Personas'
}
]
)
done()
)
specify 'responds 401 Unauthorized if the provided Authorization header is not authenticated due to an incorrect password', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( 'test+one@joukou.com:bogus' ).toString( 'base64' )}")
)
.res( ( res ) ->
res.should.have.status( 401 )
res.body.should.be.empty
done()
)
specify 'responds 401 Unauthorized if the provided Authorization header is not authenticated due to an incorrect email', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( 'test+bogus@joukou.com:password' ).toString( 'base64' )}")
)
.res( ( res ) ->
res.should.have.status( 401 )
res.body.should.be.empty
done()
)
| 20364 | ###*
Copyright 2014 Joukou Ltd
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.
###
assert = require( 'assert' )
chai = require( 'chai' )
should = chai.should()
chai.use( require( 'chai-http' ) )
server = require( '../dist/server' )
riakpbc = require( '../dist/riak/pbc' )
log = ( v ) ->
console.log(require('util').inspect(v, depth: 10))
describe 'GET /', ->
specify 'responds 200 OK with a representation of the entry point', ( done ) ->
chai.request( server )
.get( '/' )
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: '/'
'joukou:agent-authn': [
{
title: 'Authenticate'
href: '/agent/authenticate'
}
]
'joukou:contact': [
{
title: 'Send a Message to Joukou'
href: '/contact'
}
]
'joukou:agent-create': [
{
title: 'Create an Agent'
href: '/agent'
}
]
)
done()
)
xdescribe 'POST /agent', ->
agentOneKey = null
agentOneAuthorization = "Basic #{new Buffer( "<EMAIL>:<PASSWORD>" ).toString( 'base64' )}"
after ( done ) ->
riakpbc.del(
type: 'agent'
bucket: 'agent'
key: agentOneKey
, ( err, reply ) -> done( err ) )
specify 'responds 201 Created with a representation containing a link to the created agent in the given data is valid', ( done ) ->
chai.request( server )
.post( '/agent' )
.req( ( req ) ->
req.type( 'json' )
req.send(
email: '<EMAIL>'
password: '<PASSWORD>'
)
)
.res( ( res ) ->
res.should.have.status( 201 )
res.headers.location.should.match( /^\/agent\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ )
agentOneKey = res.headers.location.match( /^\/agent\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ]
res.body.should.deep.equal(
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: '/agent'
'joukou:agent': [
{
href: "/agent/#{agentOneKey}"
}
]
)
done()
)
specify 'responds 403 Forbidden with a representation of the error if the given data in invalid', ( done ) ->
chai.request( server )
.post( '/agent' )
.req( ( req ) ->
req.type( 'json' )
)
.res( ( res ) ->
res.should.have.status( 403 )
done()
)
describe 'GET /agent/:agentKey', ->
specify 'responds 200 OK with a representation of the agent if the agent key is valid', ( done ) ->
chai.request( server )
.get( "/agent/#{agentOneKey}" )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
email: '<EMAIL>'
_links:
curies: [
{
name: '<NAME>',
templated: true,
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: "/agent/#{agentOneKey}"
'joukou:personas': [
{
title: 'List of Personas'
href: '/persona'
}
]
)
done()
)
specify 'responds 401 Unauthorized with a representation of the error if the agent key is invalid', ( done ) ->
chai.request( server )
.get( "/agent/c4b56b5e-0d47-4c8d-abd8-31f41c164b34" )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 401 )
done()
)
describe 'POST /agent/authenticate', ->
specify 'responds 200 OK with a representation containing a JSON Web Token if the provided Authorization header is authenticated', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 200 )
should.exist( res.body.token )
res.body.token.should.be.a( 'string' )
res.body.should.deep.equal(
token: res.body.token
_links:
curies: [
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
]
self:
href: '/agent/authenticate'
'joukou:agent': [
{
href: "/agent/#{agentOneKey}"
}
]
'joukou:personas': [
{
href: '/persona'
title: 'List of Personas'
}
]
)
done()
)
specify 'responds 401 Unauthorized if the provided Authorization header is not authenticated due to an incorrect password', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( '<EMAIL>:bogus' ).toString( 'base64' )}")
)
.res( ( res ) ->
res.should.have.status( 401 )
res.body.should.be.empty
done()
)
specify 'responds 401 Unauthorized if the provided Authorization header is not authenticated due to an incorrect email', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( '<EMAIL>:password' ).toString( 'base64' )}")
)
.res( ( res ) ->
res.should.have.status( 401 )
res.body.should.be.empty
done()
)
| true | ###*
Copyright 2014 Joukou Ltd
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.
###
assert = require( 'assert' )
chai = require( 'chai' )
should = chai.should()
chai.use( require( 'chai-http' ) )
server = require( '../dist/server' )
riakpbc = require( '../dist/riak/pbc' )
log = ( v ) ->
console.log(require('util').inspect(v, depth: 10))
describe 'GET /', ->
specify 'responds 200 OK with a representation of the entry point', ( done ) ->
chai.request( server )
.get( '/' )
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: '/'
'joukou:agent-authn': [
{
title: 'Authenticate'
href: '/agent/authenticate'
}
]
'joukou:contact': [
{
title: 'Send a Message to Joukou'
href: '/contact'
}
]
'joukou:agent-create': [
{
title: 'Create an Agent'
href: '/agent'
}
]
)
done()
)
xdescribe 'POST /agent', ->
agentOneKey = null
agentOneAuthorization = "Basic #{new Buffer( "PI:EMAIL:<EMAIL>END_PI:PI:PASSWORD:<PASSWORD>END_PI" ).toString( 'base64' )}"
after ( done ) ->
riakpbc.del(
type: 'agent'
bucket: 'agent'
key: agentOneKey
, ( err, reply ) -> done( err ) )
specify 'responds 201 Created with a representation containing a link to the created agent in the given data is valid', ( done ) ->
chai.request( server )
.post( '/agent' )
.req( ( req ) ->
req.type( 'json' )
req.send(
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
)
)
.res( ( res ) ->
res.should.have.status( 201 )
res.headers.location.should.match( /^\/agent\/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/ )
agentOneKey = res.headers.location.match( /^\/agent\/(\w{8}-\w{4}-\w{4}-\w{4}-\w{12})$/ )[ 1 ]
res.body.should.deep.equal(
_links:
curies: [
{
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: '/agent'
'joukou:agent': [
{
href: "/agent/#{agentOneKey}"
}
]
)
done()
)
specify 'responds 403 Forbidden with a representation of the error if the given data in invalid', ( done ) ->
chai.request( server )
.post( '/agent' )
.req( ( req ) ->
req.type( 'json' )
)
.res( ( res ) ->
res.should.have.status( 403 )
done()
)
describe 'GET /agent/:agentKey', ->
specify 'responds 200 OK with a representation of the agent if the agent key is valid', ( done ) ->
chai.request( server )
.get( "/agent/#{agentOneKey}" )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 200 )
res.body.should.deep.equal(
email: 'PI:EMAIL:<EMAIL>END_PI'
_links:
curies: [
{
name: 'PI:NAME:<NAME>END_PI',
templated: true,
href: 'https://rels.joukou.com/{rel}'
}
]
self:
href: "/agent/#{agentOneKey}"
'joukou:personas': [
{
title: 'List of Personas'
href: '/persona'
}
]
)
done()
)
specify 'responds 401 Unauthorized with a representation of the error if the agent key is invalid', ( done ) ->
chai.request( server )
.get( "/agent/c4b56b5e-0d47-4c8d-abd8-31f41c164b34" )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 401 )
done()
)
describe 'POST /agent/authenticate', ->
specify 'responds 200 OK with a representation containing a JSON Web Token if the provided Authorization header is authenticated', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', agentOneAuthorization )
)
.res( ( res ) ->
res.should.have.status( 200 )
should.exist( res.body.token )
res.body.token.should.be.a( 'string' )
res.body.should.deep.equal(
token: res.body.token
_links:
curies: [
name: 'joukou'
templated: true
href: 'https://rels.joukou.com/{rel}'
]
self:
href: '/agent/authenticate'
'joukou:agent': [
{
href: "/agent/#{agentOneKey}"
}
]
'joukou:personas': [
{
href: '/persona'
title: 'List of Personas'
}
]
)
done()
)
specify 'responds 401 Unauthorized if the provided Authorization header is not authenticated due to an incorrect password', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( 'PI:EMAIL:<EMAIL>END_PI:bogus' ).toString( 'base64' )}")
)
.res( ( res ) ->
res.should.have.status( 401 )
res.body.should.be.empty
done()
)
specify 'responds 401 Unauthorized if the provided Authorization header is not authenticated due to an incorrect email', ( done ) ->
chai.request( server )
.post( '/agent/authenticate' )
.req( ( req ) ->
req.set( 'Authorization', "Basic #{new Buffer( 'PI:EMAIL:<EMAIL>END_PI:password' ).toString( 'base64' )}")
)
.res( ( res ) ->
res.should.have.status( 401 )
res.body.should.be.empty
done()
)
|
[
{
"context": "\n options: {\n title: 'Bob',\n group: 'g0',\n fi",
"end": 4602,
"score": 0.999797523021698,
"start": 4599,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\n options: {\n title: 'Lazlo... | src/components/plot/axis.spec.coffee | p-koscielniak/hexagonjs | 61 | import { Axis } from './axis'
export default () ->
describe "Axis", ->
it 'constructing an axis with new Axis should work', ->
axis = new Axis()
axis.x.scaleType().should.equal('linear')
axis.y.scaleType().should.equal('linear')
axis = new Axis({x: {scaleType: 'discrete'}, y: {scaleType: 'time'}})
axis.x.scaleType().should.equal('discrete')
axis.y.scaleType().should.equal('time')
describe 'setter/getters should work', ->
checkSetterGetterAndOption = (dim, property, valuesToCheck) ->
it 'property ' + property + ' should set and get correctly', ->
valuesToCheck.forEach (v) ->
axis = new Axis
axis[dim][property](v).should.equal(axis)
axis[dim][property]().should.equal(v)
it 'option ' + property + ' should be passed through correctly', ->
valuesToCheck.forEach (v) ->
opts = {}
opts[dim] = {}
opts[dim][property] = v
axis = new Axis(opts)
axis[dim][property]().should.equal(v)
checkSetterGetterAndOption('x', 'scaleType', ['linear', 'time', 'discrete'])
checkSetterGetterAndOption('x', 'visible', [true, false])
checkSetterGetterAndOption('x', 'formatter', [(-> 'a'), (x) -> x])
checkSetterGetterAndOption('x', 'tickRotation', [0, 5, 10])
checkSetterGetterAndOption('x', 'min', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('x', 'max', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('x', 'discretePadding', [0, 5, 120])
checkSetterGetterAndOption('x', 'discreteLabels', [0, 5, 120])
checkSetterGetterAndOption('x', 'tickSpacing', [100, 200, 300])
checkSetterGetterAndOption('x', 'title', ['title-1', 'title-2'])
checkSetterGetterAndOption('x', 'scalePaddingMin', [0, 0.1, 0.2])
checkSetterGetterAndOption('x', 'scalePaddingMax', [0, 0.1, 0.2])
checkSetterGetterAndOption('x', 'ticksAll', [true, false])
checkSetterGetterAndOption('x', 'gridLines', [true, false])
checkSetterGetterAndOption('x', 'nthTickVisible', [0, 5, 100])
checkSetterGetterAndOption('x', 'axisTickLabelPosition', [true, false])
checkSetterGetterAndOption('x', 'showTicks', [true, false])
checkSetterGetterAndOption('y', 'scaleType', ['linear', 'time', 'discrete'])
checkSetterGetterAndOption('y', 'visible', [true, false])
checkSetterGetterAndOption('y', 'formatter', [(-> 'a'), (x) -> x])
checkSetterGetterAndOption('y', 'tickRotation', [0, 5, 10])
checkSetterGetterAndOption('y', 'min', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('y', 'max', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('y', 'discretePadding', [0, 5, 120])
checkSetterGetterAndOption('y', 'discreteLabels', [0, 5, 120])
checkSetterGetterAndOption('y', 'tickSpacing', [100, 200, 300])
checkSetterGetterAndOption('y', 'title', ['title-1', 'title-2'])
checkSetterGetterAndOption('y', 'scalePaddingMin', [0, 0.1, 0.2])
checkSetterGetterAndOption('y', 'scalePaddingMax', [0, 0.1, 0.2])
checkSetterGetterAndOption('y', 'ticksAll', [true, false])
checkSetterGetterAndOption('y', 'gridLines', [true, false])
checkSetterGetterAndOption('y', 'nthTickVisible', [0, 5, 100])
checkSetterGetterAndOption('y', 'axisTickLabelPosition', [true, false])
checkSetterGetterAndOption('y', 'showTicks', [true, false])
it 'should be able to get the list of series', ->
axis = new Axis
a1 = axis.addSeries()
a2 = axis.addSeries()
axis.series().should.eql([a1, a2])
it 'should be able to set the list of series', ->
axis = new Axis
a1 = axis.addSeries()
a2 = axis.addSeries()
axis.series().should.eql([a1, a2])
axis.series([a2, a1]).should.eql(axis)
axis.series().should.eql([a2, a1])
it 'calculateYBounds: should not ignore non-auto parameters', ->
axis = new Axis()
axis.calculateYBounds('auto', 'auto').should.eql { ymin: 0, ymax: 0 }
axis.calculateYBounds(1, 1).should.eql { ymin: 1, ymax: 1 }
axis.calculateYBounds(-1, 'auto').should.eql { ymin: -1, ymax: 0 }
it 'calculateYBounds: should correctly calculate y bounds when the data is sparse and the graph is stacked', ->
axis = new Axis({
x: {
scaleType: 'discrete'
},
y: {
min: 0
},
series: [
{
type: 'bar',
options: {
title: 'Bob',
group: 'g0',
fillColor: '#ffffff',
data: [{
x: 'verybig',
y: 10
}, {
x: 'alwayspresesnt',
y: 1
}]
}
},
{
type: 'bar',
options: {
title: 'Lazlo',
fillColor: '#ffffff',
group: 'g0',
data: [{
x: 'alwayspresesnt',
y: 2
}]
}
}
]
})
axis.tagSeries()
{ ymax } = axis.calculateYBounds('auto', 'auto')
ymax.should.eql(10)
| 76679 | import { Axis } from './axis'
export default () ->
describe "Axis", ->
it 'constructing an axis with new Axis should work', ->
axis = new Axis()
axis.x.scaleType().should.equal('linear')
axis.y.scaleType().should.equal('linear')
axis = new Axis({x: {scaleType: 'discrete'}, y: {scaleType: 'time'}})
axis.x.scaleType().should.equal('discrete')
axis.y.scaleType().should.equal('time')
describe 'setter/getters should work', ->
checkSetterGetterAndOption = (dim, property, valuesToCheck) ->
it 'property ' + property + ' should set and get correctly', ->
valuesToCheck.forEach (v) ->
axis = new Axis
axis[dim][property](v).should.equal(axis)
axis[dim][property]().should.equal(v)
it 'option ' + property + ' should be passed through correctly', ->
valuesToCheck.forEach (v) ->
opts = {}
opts[dim] = {}
opts[dim][property] = v
axis = new Axis(opts)
axis[dim][property]().should.equal(v)
checkSetterGetterAndOption('x', 'scaleType', ['linear', 'time', 'discrete'])
checkSetterGetterAndOption('x', 'visible', [true, false])
checkSetterGetterAndOption('x', 'formatter', [(-> 'a'), (x) -> x])
checkSetterGetterAndOption('x', 'tickRotation', [0, 5, 10])
checkSetterGetterAndOption('x', 'min', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('x', 'max', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('x', 'discretePadding', [0, 5, 120])
checkSetterGetterAndOption('x', 'discreteLabels', [0, 5, 120])
checkSetterGetterAndOption('x', 'tickSpacing', [100, 200, 300])
checkSetterGetterAndOption('x', 'title', ['title-1', 'title-2'])
checkSetterGetterAndOption('x', 'scalePaddingMin', [0, 0.1, 0.2])
checkSetterGetterAndOption('x', 'scalePaddingMax', [0, 0.1, 0.2])
checkSetterGetterAndOption('x', 'ticksAll', [true, false])
checkSetterGetterAndOption('x', 'gridLines', [true, false])
checkSetterGetterAndOption('x', 'nthTickVisible', [0, 5, 100])
checkSetterGetterAndOption('x', 'axisTickLabelPosition', [true, false])
checkSetterGetterAndOption('x', 'showTicks', [true, false])
checkSetterGetterAndOption('y', 'scaleType', ['linear', 'time', 'discrete'])
checkSetterGetterAndOption('y', 'visible', [true, false])
checkSetterGetterAndOption('y', 'formatter', [(-> 'a'), (x) -> x])
checkSetterGetterAndOption('y', 'tickRotation', [0, 5, 10])
checkSetterGetterAndOption('y', 'min', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('y', 'max', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('y', 'discretePadding', [0, 5, 120])
checkSetterGetterAndOption('y', 'discreteLabels', [0, 5, 120])
checkSetterGetterAndOption('y', 'tickSpacing', [100, 200, 300])
checkSetterGetterAndOption('y', 'title', ['title-1', 'title-2'])
checkSetterGetterAndOption('y', 'scalePaddingMin', [0, 0.1, 0.2])
checkSetterGetterAndOption('y', 'scalePaddingMax', [0, 0.1, 0.2])
checkSetterGetterAndOption('y', 'ticksAll', [true, false])
checkSetterGetterAndOption('y', 'gridLines', [true, false])
checkSetterGetterAndOption('y', 'nthTickVisible', [0, 5, 100])
checkSetterGetterAndOption('y', 'axisTickLabelPosition', [true, false])
checkSetterGetterAndOption('y', 'showTicks', [true, false])
it 'should be able to get the list of series', ->
axis = new Axis
a1 = axis.addSeries()
a2 = axis.addSeries()
axis.series().should.eql([a1, a2])
it 'should be able to set the list of series', ->
axis = new Axis
a1 = axis.addSeries()
a2 = axis.addSeries()
axis.series().should.eql([a1, a2])
axis.series([a2, a1]).should.eql(axis)
axis.series().should.eql([a2, a1])
it 'calculateYBounds: should not ignore non-auto parameters', ->
axis = new Axis()
axis.calculateYBounds('auto', 'auto').should.eql { ymin: 0, ymax: 0 }
axis.calculateYBounds(1, 1).should.eql { ymin: 1, ymax: 1 }
axis.calculateYBounds(-1, 'auto').should.eql { ymin: -1, ymax: 0 }
it 'calculateYBounds: should correctly calculate y bounds when the data is sparse and the graph is stacked', ->
axis = new Axis({
x: {
scaleType: 'discrete'
},
y: {
min: 0
},
series: [
{
type: 'bar',
options: {
title: '<NAME>',
group: 'g0',
fillColor: '#ffffff',
data: [{
x: 'verybig',
y: 10
}, {
x: 'alwayspresesnt',
y: 1
}]
}
},
{
type: 'bar',
options: {
title: '<NAME>',
fillColor: '#ffffff',
group: 'g0',
data: [{
x: 'alwayspresesnt',
y: 2
}]
}
}
]
})
axis.tagSeries()
{ ymax } = axis.calculateYBounds('auto', 'auto')
ymax.should.eql(10)
| true | import { Axis } from './axis'
export default () ->
describe "Axis", ->
it 'constructing an axis with new Axis should work', ->
axis = new Axis()
axis.x.scaleType().should.equal('linear')
axis.y.scaleType().should.equal('linear')
axis = new Axis({x: {scaleType: 'discrete'}, y: {scaleType: 'time'}})
axis.x.scaleType().should.equal('discrete')
axis.y.scaleType().should.equal('time')
describe 'setter/getters should work', ->
checkSetterGetterAndOption = (dim, property, valuesToCheck) ->
it 'property ' + property + ' should set and get correctly', ->
valuesToCheck.forEach (v) ->
axis = new Axis
axis[dim][property](v).should.equal(axis)
axis[dim][property]().should.equal(v)
it 'option ' + property + ' should be passed through correctly', ->
valuesToCheck.forEach (v) ->
opts = {}
opts[dim] = {}
opts[dim][property] = v
axis = new Axis(opts)
axis[dim][property]().should.equal(v)
checkSetterGetterAndOption('x', 'scaleType', ['linear', 'time', 'discrete'])
checkSetterGetterAndOption('x', 'visible', [true, false])
checkSetterGetterAndOption('x', 'formatter', [(-> 'a'), (x) -> x])
checkSetterGetterAndOption('x', 'tickRotation', [0, 5, 10])
checkSetterGetterAndOption('x', 'min', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('x', 'max', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('x', 'discretePadding', [0, 5, 120])
checkSetterGetterAndOption('x', 'discreteLabels', [0, 5, 120])
checkSetterGetterAndOption('x', 'tickSpacing', [100, 200, 300])
checkSetterGetterAndOption('x', 'title', ['title-1', 'title-2'])
checkSetterGetterAndOption('x', 'scalePaddingMin', [0, 0.1, 0.2])
checkSetterGetterAndOption('x', 'scalePaddingMax', [0, 0.1, 0.2])
checkSetterGetterAndOption('x', 'ticksAll', [true, false])
checkSetterGetterAndOption('x', 'gridLines', [true, false])
checkSetterGetterAndOption('x', 'nthTickVisible', [0, 5, 100])
checkSetterGetterAndOption('x', 'axisTickLabelPosition', [true, false])
checkSetterGetterAndOption('x', 'showTicks', [true, false])
checkSetterGetterAndOption('y', 'scaleType', ['linear', 'time', 'discrete'])
checkSetterGetterAndOption('y', 'visible', [true, false])
checkSetterGetterAndOption('y', 'formatter', [(-> 'a'), (x) -> x])
checkSetterGetterAndOption('y', 'tickRotation', [0, 5, 10])
checkSetterGetterAndOption('y', 'min', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('y', 'max', [0, -100, 100, 'auto'])
checkSetterGetterAndOption('y', 'discretePadding', [0, 5, 120])
checkSetterGetterAndOption('y', 'discreteLabels', [0, 5, 120])
checkSetterGetterAndOption('y', 'tickSpacing', [100, 200, 300])
checkSetterGetterAndOption('y', 'title', ['title-1', 'title-2'])
checkSetterGetterAndOption('y', 'scalePaddingMin', [0, 0.1, 0.2])
checkSetterGetterAndOption('y', 'scalePaddingMax', [0, 0.1, 0.2])
checkSetterGetterAndOption('y', 'ticksAll', [true, false])
checkSetterGetterAndOption('y', 'gridLines', [true, false])
checkSetterGetterAndOption('y', 'nthTickVisible', [0, 5, 100])
checkSetterGetterAndOption('y', 'axisTickLabelPosition', [true, false])
checkSetterGetterAndOption('y', 'showTicks', [true, false])
it 'should be able to get the list of series', ->
axis = new Axis
a1 = axis.addSeries()
a2 = axis.addSeries()
axis.series().should.eql([a1, a2])
it 'should be able to set the list of series', ->
axis = new Axis
a1 = axis.addSeries()
a2 = axis.addSeries()
axis.series().should.eql([a1, a2])
axis.series([a2, a1]).should.eql(axis)
axis.series().should.eql([a2, a1])
it 'calculateYBounds: should not ignore non-auto parameters', ->
axis = new Axis()
axis.calculateYBounds('auto', 'auto').should.eql { ymin: 0, ymax: 0 }
axis.calculateYBounds(1, 1).should.eql { ymin: 1, ymax: 1 }
axis.calculateYBounds(-1, 'auto').should.eql { ymin: -1, ymax: 0 }
it 'calculateYBounds: should correctly calculate y bounds when the data is sparse and the graph is stacked', ->
axis = new Axis({
x: {
scaleType: 'discrete'
},
y: {
min: 0
},
series: [
{
type: 'bar',
options: {
title: 'PI:NAME:<NAME>END_PI',
group: 'g0',
fillColor: '#ffffff',
data: [{
x: 'verybig',
y: 10
}, {
x: 'alwayspresesnt',
y: 1
}]
}
},
{
type: 'bar',
options: {
title: 'PI:NAME:<NAME>END_PI',
fillColor: '#ffffff',
group: 'g0',
data: [{
x: 'alwayspresesnt',
y: 2
}]
}
}
]
})
axis.tagSeries()
{ ymax } = axis.calculateYBounds('auto', 'auto')
ymax.should.eql(10)
|
[
{
"context": "ime scores for the relevant league\n#\n# Author:\n# Detry322\n\nquerystring = require 'querystring'\n\nformat_resp",
"end": 218,
"score": 0.9996185302734375,
"start": 210,
"tag": "USERNAME",
"value": "Detry322"
},
{
"context": "= \"Scores:\\n\"\n for i in [1..count] ... | src/espn.coffee | Detry322/hubot-espn | 5 | # Description:
# Get live sports data for MLB, NHL, NBA, NFL, and WNBA
#
# Configuration:
# None
#
# Commands:
# hubot espn <mlb, nfl, etc.> - get real-time scores for the relevant league
#
# Author:
# Detry322
querystring = require 'querystring'
format_response = (league, response) ->
data = querystring.parse(response)
count = +data["#{league}_s_count"]
if not count
return "No scores to display for #{league.toUpperCase()}"
result_string = "Scores:\n"
for i in [1..count] by 1
key = "#{league}_s_left#{i}"
result_string += "- #{data[key]}\n"
return result_string
module.exports = (robot) ->
robot.respond /espn (mlb|nhl|nba|wnba|nfl)$/i, (res) ->
league = res.match[1].toLowerCase()
robot.http("http://www.espn.com/#{league}/bottomline/scores").get() (err, result, body) ->
if err or result.statusCode isnt 200
res.send "There was a problem fetching score data :("
return
res.send format_response(league, body)
| 31828 | # Description:
# Get live sports data for MLB, NHL, NBA, NFL, and WNBA
#
# Configuration:
# None
#
# Commands:
# hubot espn <mlb, nfl, etc.> - get real-time scores for the relevant league
#
# Author:
# Detry322
querystring = require 'querystring'
format_response = (league, response) ->
data = querystring.parse(response)
count = +data["#{league}_s_count"]
if not count
return "No scores to display for #{league.toUpperCase()}"
result_string = "Scores:\n"
for i in [1..count] by 1
key = <KEY>
result_string += "- #{data[key]}\n"
return result_string
module.exports = (robot) ->
robot.respond /espn (mlb|nhl|nba|wnba|nfl)$/i, (res) ->
league = res.match[1].toLowerCase()
robot.http("http://www.espn.com/#{league}/bottomline/scores").get() (err, result, body) ->
if err or result.statusCode isnt 200
res.send "There was a problem fetching score data :("
return
res.send format_response(league, body)
| true | # Description:
# Get live sports data for MLB, NHL, NBA, NFL, and WNBA
#
# Configuration:
# None
#
# Commands:
# hubot espn <mlb, nfl, etc.> - get real-time scores for the relevant league
#
# Author:
# Detry322
querystring = require 'querystring'
format_response = (league, response) ->
data = querystring.parse(response)
count = +data["#{league}_s_count"]
if not count
return "No scores to display for #{league.toUpperCase()}"
result_string = "Scores:\n"
for i in [1..count] by 1
key = PI:KEY:<KEY>END_PI
result_string += "- #{data[key]}\n"
return result_string
module.exports = (robot) ->
robot.respond /espn (mlb|nhl|nba|wnba|nfl)$/i, (res) ->
league = res.match[1].toLowerCase()
robot.http("http://www.espn.com/#{league}/bottomline/scores").get() (err, result, body) ->
if err or result.statusCode isnt 200
res.send "There was a problem fetching score data :("
return
res.send format_response(league, body)
|
[
{
"context": "#########################\n# Created 15 Feb 2017 by Petr Krulis / petrkrulis.cz\n#################################",
"end": 117,
"score": 0.9998795390129089,
"start": 106,
"tag": "NAME",
"value": "Petr Krulis"
},
{
"context": "###########\n# Created 15 Feb 2017 by Petr ... | PanView.coffee | petrkrulis/PanView-Framer | 1 | ################################################################################
# Created 15 Feb 2017 by Petr Krulis / petrkrulis.cz
################################################################################
class PanView extends Layer
constructor: (@options={}) ->
#Defaults
@options.width ?= 1440
@options.height ?= 900
@options.devicePixelRatio ?= 1
@options.backgroundColor ?= "#fff"
#Call base class constructor and create layer
super
width: @options.width * @options.devicePixelRatio
height: @options.height * @options.devicePixelRatio
backgroundColor: @options.backgroundColor
clip: true
x: 0
y: 0
#Create the device
Framer.DeviceView.Devices["PanView"] =
deviceImageWidth: @options.width
deviceImageHeight: @options.height
screenWidth: @options.width
screenHeight: @options.height
backgroundColor: @options.backgroundColor
deviceType: Framer.Device.Type.Computer
#Set the device
Framer.Device.deviceType = "PanView"
Framer.Device.contentScale = 1 / @options.devicePixelRatio
@pixelAlign()
@draggable.momentum = false
@draggable.overdrag = false
@draggable.enabled = false
@draggable.constraints =
x: -@width + @width * 0.1
y: -@height + @width * 0.1
width: 3 * @width - 2 * @width * 0.1
height: 3 * @height - 2 * @width * 0.1
panView = this
#Press & hold space to enable dragging
document.addEventListener 'keypress', (event) ->
if event.keyCode == 32
panView.draggable.enabled = true
document.body.style.cursor = "-webkit-grab"
#Relase space to disable dragging
document.addEventListener 'keyup', (event) ->
panView.draggable.enabled = false
document.body.style.cursor = "auto"
#Press space & alt simultaneously to reset the position
document.addEventListener 'keydown', (event) ->
if event.keyCode == 32 && event.altKey
panView.x = 0
panView.y = 0
#Export the class
exports.PanView = PanView
| 135822 | ################################################################################
# Created 15 Feb 2017 by <NAME> / <EMAIL>
################################################################################
class PanView extends Layer
constructor: (@options={}) ->
#Defaults
@options.width ?= 1440
@options.height ?= 900
@options.devicePixelRatio ?= 1
@options.backgroundColor ?= "#fff"
#Call base class constructor and create layer
super
width: @options.width * @options.devicePixelRatio
height: @options.height * @options.devicePixelRatio
backgroundColor: @options.backgroundColor
clip: true
x: 0
y: 0
#Create the device
Framer.DeviceView.Devices["PanView"] =
deviceImageWidth: @options.width
deviceImageHeight: @options.height
screenWidth: @options.width
screenHeight: @options.height
backgroundColor: @options.backgroundColor
deviceType: Framer.Device.Type.Computer
#Set the device
Framer.Device.deviceType = "PanView"
Framer.Device.contentScale = 1 / @options.devicePixelRatio
@pixelAlign()
@draggable.momentum = false
@draggable.overdrag = false
@draggable.enabled = false
@draggable.constraints =
x: -@width + @width * 0.1
y: -@height + @width * 0.1
width: 3 * @width - 2 * @width * 0.1
height: 3 * @height - 2 * @width * 0.1
panView = this
#Press & hold space to enable dragging
document.addEventListener 'keypress', (event) ->
if event.keyCode == 32
panView.draggable.enabled = true
document.body.style.cursor = "-webkit-grab"
#Relase space to disable dragging
document.addEventListener 'keyup', (event) ->
panView.draggable.enabled = false
document.body.style.cursor = "auto"
#Press space & alt simultaneously to reset the position
document.addEventListener 'keydown', (event) ->
if event.keyCode == 32 && event.altKey
panView.x = 0
panView.y = 0
#Export the class
exports.PanView = PanView
| true | ################################################################################
# Created 15 Feb 2017 by PI:NAME:<NAME>END_PI / PI:EMAIL:<EMAIL>END_PI
################################################################################
class PanView extends Layer
constructor: (@options={}) ->
#Defaults
@options.width ?= 1440
@options.height ?= 900
@options.devicePixelRatio ?= 1
@options.backgroundColor ?= "#fff"
#Call base class constructor and create layer
super
width: @options.width * @options.devicePixelRatio
height: @options.height * @options.devicePixelRatio
backgroundColor: @options.backgroundColor
clip: true
x: 0
y: 0
#Create the device
Framer.DeviceView.Devices["PanView"] =
deviceImageWidth: @options.width
deviceImageHeight: @options.height
screenWidth: @options.width
screenHeight: @options.height
backgroundColor: @options.backgroundColor
deviceType: Framer.Device.Type.Computer
#Set the device
Framer.Device.deviceType = "PanView"
Framer.Device.contentScale = 1 / @options.devicePixelRatio
@pixelAlign()
@draggable.momentum = false
@draggable.overdrag = false
@draggable.enabled = false
@draggable.constraints =
x: -@width + @width * 0.1
y: -@height + @width * 0.1
width: 3 * @width - 2 * @width * 0.1
height: 3 * @height - 2 * @width * 0.1
panView = this
#Press & hold space to enable dragging
document.addEventListener 'keypress', (event) ->
if event.keyCode == 32
panView.draggable.enabled = true
document.body.style.cursor = "-webkit-grab"
#Relase space to disable dragging
document.addEventListener 'keyup', (event) ->
panView.draggable.enabled = false
document.body.style.cursor = "auto"
#Press space & alt simultaneously to reset the position
document.addEventListener 'keydown', (event) ->
if event.keyCode == 32 && event.altKey
panView.x = 0
panView.y = 0
#Export the class
exports.PanView = PanView
|
[
{
"context": "obj.user.key = \n key_id : me.key_id_64().toUpperCase()\n fingerprint : format_fingerprint me.f",
"end": 1279,
"score": 0.6453022956848145,
"start": 1268,
"tag": "KEY",
"value": "toUpperCase"
}
] | src/command/status.iced | substack/keybase-client | 1 | {Base} = require './base'
log = require '../log'
{ArgumentParser} = require 'argparse'
{add_option_dict} = require './argparse'
{PackageJson} = require '../package'
{session} = require '../session'
{make_esc} = require 'iced-error'
{env} = require '../env'
log = require '../log'
{User} = require '../user'
{format_fingerprint} = require('pgp-utils').util
##=======================================================================
exports.Command = class Command extends Base
#----------
OPTS :
T :
alias : 'text'
action : 'storeTrue'
help : 'output in text format; default is JSON'
#----------
use_session : () -> true
#----------
add_subcommand_parser : (scp) ->
opts =
help : "print current status"
name = "status"
sub = scp.addParser name, opts
add_option_dict sub, @OPTS
return [ name ]
#----------
run : (cb) ->
esc = make_esc cb, "Command::run"
if (un = env().get_username())?
await session.check esc defer logged_in
await User.load_me {secret : false}, esc defer me
obj =
status :
configured : true
logged_in : logged_in
user :
name : un
if me?
obj.user.key =
key_id : me.key_id_64().toUpperCase()
fingerprint : format_fingerprint me.fingerprint(true)
if (rp = me.list_remote_proofs())?
obj.user.proofs = rp
if (d = me.list_cryptocurrency_addresses())?
obj.user.cryptocurrency = d
else
obj = { status : { configured : false } }
@output obj
cb null
#-----------------
output_text : (obj) ->
if obj.status.configured
log.console.log "configged as #{obj.user.name}"
log.console.log " * #{if obj.status.logged_in then '' else 'NOT '}logged in"
if (ko = obj.user.key)?
log.console.log " * Key ID: #{ko.key_id}"
log.console.log " * Fingerprint: #{ko.fingerprint}"
if (rp = obj.user.proofs)?
log.console.log "Remote proofs:"
for k,v of rp
log.console.log " * #{k}: #{v}"
if (ct = obj.user.cryptocurrency)?
log.console.log "Cryptocurrency Addresses:"
for k,v of ct
log.console.log " * #{k}: #{v}"
else
log.error "Not configured"
#-----------------
output : (obj) ->
if @argv.text
@output_text obj
else
log.console.log JSON.stringify(obj, null, " ")
##=======================================================================
| 140293 | {Base} = require './base'
log = require '../log'
{ArgumentParser} = require 'argparse'
{add_option_dict} = require './argparse'
{PackageJson} = require '../package'
{session} = require '../session'
{make_esc} = require 'iced-error'
{env} = require '../env'
log = require '../log'
{User} = require '../user'
{format_fingerprint} = require('pgp-utils').util
##=======================================================================
exports.Command = class Command extends Base
#----------
OPTS :
T :
alias : 'text'
action : 'storeTrue'
help : 'output in text format; default is JSON'
#----------
use_session : () -> true
#----------
add_subcommand_parser : (scp) ->
opts =
help : "print current status"
name = "status"
sub = scp.addParser name, opts
add_option_dict sub, @OPTS
return [ name ]
#----------
run : (cb) ->
esc = make_esc cb, "Command::run"
if (un = env().get_username())?
await session.check esc defer logged_in
await User.load_me {secret : false}, esc defer me
obj =
status :
configured : true
logged_in : logged_in
user :
name : un
if me?
obj.user.key =
key_id : me.key_id_64().<KEY>()
fingerprint : format_fingerprint me.fingerprint(true)
if (rp = me.list_remote_proofs())?
obj.user.proofs = rp
if (d = me.list_cryptocurrency_addresses())?
obj.user.cryptocurrency = d
else
obj = { status : { configured : false } }
@output obj
cb null
#-----------------
output_text : (obj) ->
if obj.status.configured
log.console.log "configged as #{obj.user.name}"
log.console.log " * #{if obj.status.logged_in then '' else 'NOT '}logged in"
if (ko = obj.user.key)?
log.console.log " * Key ID: #{ko.key_id}"
log.console.log " * Fingerprint: #{ko.fingerprint}"
if (rp = obj.user.proofs)?
log.console.log "Remote proofs:"
for k,v of rp
log.console.log " * #{k}: #{v}"
if (ct = obj.user.cryptocurrency)?
log.console.log "Cryptocurrency Addresses:"
for k,v of ct
log.console.log " * #{k}: #{v}"
else
log.error "Not configured"
#-----------------
output : (obj) ->
if @argv.text
@output_text obj
else
log.console.log JSON.stringify(obj, null, " ")
##=======================================================================
| true | {Base} = require './base'
log = require '../log'
{ArgumentParser} = require 'argparse'
{add_option_dict} = require './argparse'
{PackageJson} = require '../package'
{session} = require '../session'
{make_esc} = require 'iced-error'
{env} = require '../env'
log = require '../log'
{User} = require '../user'
{format_fingerprint} = require('pgp-utils').util
##=======================================================================
exports.Command = class Command extends Base
#----------
OPTS :
T :
alias : 'text'
action : 'storeTrue'
help : 'output in text format; default is JSON'
#----------
use_session : () -> true
#----------
add_subcommand_parser : (scp) ->
opts =
help : "print current status"
name = "status"
sub = scp.addParser name, opts
add_option_dict sub, @OPTS
return [ name ]
#----------
run : (cb) ->
esc = make_esc cb, "Command::run"
if (un = env().get_username())?
await session.check esc defer logged_in
await User.load_me {secret : false}, esc defer me
obj =
status :
configured : true
logged_in : logged_in
user :
name : un
if me?
obj.user.key =
key_id : me.key_id_64().PI:KEY:<KEY>END_PI()
fingerprint : format_fingerprint me.fingerprint(true)
if (rp = me.list_remote_proofs())?
obj.user.proofs = rp
if (d = me.list_cryptocurrency_addresses())?
obj.user.cryptocurrency = d
else
obj = { status : { configured : false } }
@output obj
cb null
#-----------------
output_text : (obj) ->
if obj.status.configured
log.console.log "configged as #{obj.user.name}"
log.console.log " * #{if obj.status.logged_in then '' else 'NOT '}logged in"
if (ko = obj.user.key)?
log.console.log " * Key ID: #{ko.key_id}"
log.console.log " * Fingerprint: #{ko.fingerprint}"
if (rp = obj.user.proofs)?
log.console.log "Remote proofs:"
for k,v of rp
log.console.log " * #{k}: #{v}"
if (ct = obj.user.cryptocurrency)?
log.console.log "Cryptocurrency Addresses:"
for k,v of ct
log.console.log " * #{k}: #{v}"
else
log.error "Not configured"
#-----------------
output : (obj) ->
if @argv.text
@output_text obj
else
log.console.log JSON.stringify(obj, null, " ")
##=======================================================================
|
[
{
"context": "module.exports = ( () ->\n\n opts:\n token: \"%s\"\n parseKey: (k) -> \"<\"+k+\">%s</\"+k+\">\"\n parseVa",
"end": 48,
"score": 0.7459713220596313,
"start": 45,
"tag": "KEY",
"value": "\"%s"
}
] | index.coffee | coderofsalvation/json-dsl | 4 | module.exports = ( () ->
opts:
token: "%s"
parseKey: (k) -> "<"+k+">%s</"+k+">"
parseValue: (v,d) -> v
parseDSL: (json,data,str) ->
str = '' if not str?
if typeof json is "object"
for k,v of json
nk = @.parseKey k
nv = @.parse v, data, ''
str += nk.replace /%s/, nv
if typeof json is "string"
str += @.parseValue json, data
if not str?
return json
else return str
parse: (json,data) ->
@.parseDSL json,data
)()
| 176532 | module.exports = ( () ->
opts:
token: <KEY>"
parseKey: (k) -> "<"+k+">%s</"+k+">"
parseValue: (v,d) -> v
parseDSL: (json,data,str) ->
str = '' if not str?
if typeof json is "object"
for k,v of json
nk = @.parseKey k
nv = @.parse v, data, ''
str += nk.replace /%s/, nv
if typeof json is "string"
str += @.parseValue json, data
if not str?
return json
else return str
parse: (json,data) ->
@.parseDSL json,data
)()
| true | module.exports = ( () ->
opts:
token: PI:KEY:<KEY>END_PI"
parseKey: (k) -> "<"+k+">%s</"+k+">"
parseValue: (v,d) -> v
parseDSL: (json,data,str) ->
str = '' if not str?
if typeof json is "object"
for k,v of json
nk = @.parseKey k
nv = @.parse v, data, ''
str += nk.replace /%s/, nv
if typeof json is "string"
str += @.parseValue json, data
if not str?
return json
else return str
parse: (json,data) ->
@.parseDSL json,data
)()
|
[
{
"context": "1b7e02d42c0c0bbf558700000000\");\n inputs = [ [\"214af8788d11cf6e3a8dd2efb00d0c3facb446273dee2cf8023e1fae8b2afcbd\", \"00000000\"] ]\n scripts = [ \"522102feec7dd823",
"end": 6859,
"score": 0.8548488616943359,
"start": 6796,
"tag": "KEY",
"value": "14af8788d11cf6e3a8dd2ef... | app/src/utils/apps/coinkite.coffee | doged/ledger-wallet-doged-chrome | 1 | class @Coinkite
API_BASE: "https://api.coinkite.com"
CK_SIGNING_ADDRESS: "1GPWzXfpN9ht3g7KsSu8eTB92Na5Wpmu7g"
@CK_PATH: "0xb11e'/0xccc0'"
@factory: (callback) ->
ledger.storage.sync.get "__apps_coinkite_api_key", (r) =>
api_key = r.__apps_coinkite_api_key
ledger.storage.sync.get "__apps_coinkite_api_secret", (r) =>
secret = r.__apps_coinkite_api_secret
if typeof secret == "string"
callback(new Coinkite(api_key, secret))
else
callback undefined
constructor: (api_key, secret) ->
@apiKey = api_key
@secret = secret
@httpClient = new HttpClient(@API_BASE)
getExtendedPublicKey: (index, callback) ->
path = @_buildPath(index)
try
ledger.app.wallet.getExtendedPublicKey path, (key) =>
@xpub = key._xpub58
ledger.app.wallet.signMessageWithBitId path, "Coinkite", (signature) =>
callback?({xpub: @xpub, signature: signature, path: path}, null)
catch error
callback?(null, error)
getRequestData: (request, callback) ->
url = '/v1/co-sign/' + request
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
getCosigner: (data, callback) ->
@cosigner = null
try
ledger.app.wallet.getExtendedPublicKey Coinkite.CK_PATH, (key) =>
xpub = key._xpub58
async.eachSeries data.cosigners, ((cosigner, finishedCallback) =>
check = cosigner.xpubkey_check
if xpub.indexOf(check, xpub.length - check.length) > 0
@cosigner = cosigner.CK_refnum
finishedCallback()
), (finished) =>
callback @cosigner, data.has_signed_already[@cosigner]
catch error
callback @cosigner
getCosignData: (request, cosigner, callback) ->
@request = request
@cosigner = cosigner
url = '/v1/co-sign/' + request + '/' + cosigner
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data.signing_info, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
getCosignSummary: (request, cosigner, callback) ->
@request = request
@cosigner = cosigner
url = '/v1/co-sign/' + request + '/' + cosigner + '.html'
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
cosignRequest: (data, post, callback) ->
try
transaction = Bitcoin.Transaction.deserialize(data.raw_unsigned_txn);
outputs_number = transaction['outs'].length
outputs_script = ledger.app.wallet._lwCard.dongle.formatP2SHOutputScript(transaction)
inputs = []
paths = []
scripts = []
for input in data.input_info
paths.push(@_buildPath(data.ledger_key?.subkey_index) + "/" + input.sp)
inputs.push([input.txn, Bitcoin.convert.bytesToHex(ledger.bitcoin.numToBytes(parseInt(input.out_num), 4).reverse())])
scripts.push(data.redeem_scripts[input.sp].redeem)
ledger.app.wallet._lwCard.dongle.signP2SHTransaction_async(inputs, scripts, outputs_number, outputs_script, paths)
.then (result) =>
signatures = []
index = 0
for input in data.inputs
signatures.push([result[index], input[1], input[0]])
index++
if post
url = '/v1/co-sign/' + @request + '/' + @cosigner + '/sign'
@_setAuthHeaders(url)
@httpClient
.do type: 'PUT', url: url, dataType: 'json', contentType: 'application/json', data: { signatures: signatures }
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
else
callback?(signatures, null)
.fail (error) =>
callback?(null, error)
catch error
callback?(null, error)
getRequestFromJSON: (data) ->
if data.contents?
$.extend { api: true }, JSON.parse(data.contents)
else
$.extend { api: true }, data
buildSignedJSON: (request, callback) ->
try
@verifyExtendedPublicKey request, (result, error) =>
if result
@cosignRequest request, false, (result, error) =>
if error?
return callback?(null, error)
path = @_buildPath(request.ledger_key?.subkey_index)
rv =
cosigner: request.cosigner,
request: request.request,
signatures: result
body =
_humans: "This transaction has been signed by a Ledger Wallet Nano",
content: JSON.stringify(rv)
ledger.app.wallet.getPublicAddress path, (key, error) =>
if error?
return callback?(null, error)
else
body.signed_by = key.bitcoinAddress.value
ledger.app.wallet.signMessageWithBitId path, sha256_digest(body.content), (signature) =>
body.signature_sha256 = signature
callback?(JSON.stringify(body), null)
else
callback?(null, t("apps.coinkite.cosign.errors.wrong_nano_text"))
catch error
callback?(null, error)
postSignedJSON: (json, callback) =>
httpClient = new HttpClient("https://coinkite.com")
httpClient
.do type: 'PUT', url: '/co-sign/done-signature', contentType: 'text/plain', data: json
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
if error.responseJSON?
callback?(null, error.responseJSON.message)
else
callback?(null, error.statusText)
.done()
verifyExtendedPublicKey: (request, callback) ->
check = request.xpubkey_check
ledger.app.wallet.getExtendedPublicKey @_buildPath(request.ledger_key?.subkey_index), (key) =>
xpub = key._xpub58
callback?(xpub.indexOf(check, xpub.length - check.length) > 0)
testDongleCompatibility: (callback) ->
transaction = Bitcoin.Transaction.deserialize("0100000001b4e84a9115e3633abaa1730689db782aa3bb54fa429a3c52a7fa55a788d611fd0100000000ffffffff02a0860100000000001976a914069b75ac23920928eda632a20525a027e67d040188ac50c300000000000017a914c70abc77a8bb21997a7a901b7e02d42c0c0bbf558700000000");
inputs = [ ["214af8788d11cf6e3a8dd2efb00d0c3facb446273dee2cf8023e1fae8b2afcbd", "00000000"] ]
scripts = [ "522102feec7dd82317846908c20c342a02a8e8c17fb327390ce8d6669ef09a9c85904b210308aaece16e0f99b78e4beb30d8b18652af318428d6d64df26f8089010c7079f452ae" ]
outputs_number = transaction['outs'].length
outputs_script = ledger.app.wallet._lwCard.dongle.formatP2SHOutputScript(transaction)
paths = [ Coinkite.CK_PATH + "/0" ]
data = {
"input_info": [
{
"full_sp": "m/0",
"out_num": 1,
"sp": "0",
"txn": "fd11d688a755faa7523c9a42fa54bba32a78db890673a1ba3a63e315914ae8b4"
}
],
"inputs": [
[
"0",
"214af8788d11cf6e3a8dd2efb00d0c3facb446273dee2cf8023e1fae8b2afcbd"
]
],
"raw_unsigned_txn": "0100000001b4e84a9115e3633abaa1730689db782aa3bb54fa429a3c52a7fa55a788d611fd0100000000ffffffff02a0860100000000001976a914069b75ac23920928eda632a20525a027e67d040188ac50c300000000000017a914c70abc77a8bb21997a7a901b7e02d42c0c0bbf558700000000",
"redeem_scripts": {
"0": {
"addr": "3NjjSXDhRtn4yunA7P8DGGTQuyPnbktcs3",
"redeem": "522102feec7dd82317846908c20c342a02a8e8c17fb327390ce8d6669ef09a9c85904b210308aaece16e0f99b78e4beb30d8b18652af318428d6d64df26f8089010c7079f452ae"
}
},
}
try
ledger.app.wallet._lwCard.dongle.signP2SHTransaction_async(inputs, scripts, outputs_number, outputs_script, paths)
.then (result) =>
callback true
.fail (error) =>
callback false
catch error
callback false
_buildPath: (index) ->
path = Coinkite.CK_PATH
if index
path = path + "/" + index
return path
_setAuthHeaders: (endpoint) ->
endpoint = endpoint.split('?')[0]
ts = (new Date).toISOString()
data = endpoint + '|' + ts
@httpClient.setHttpHeader 'X-CK-Key', @apiKey
@httpClient.setHttpHeader 'X-CK-Sign', CryptoJS.HmacSHA256(data, @secret).toString()
@httpClient.setHttpHeader 'X-CK-Timestamp', ts | 125681 | class @Coinkite
API_BASE: "https://api.coinkite.com"
CK_SIGNING_ADDRESS: "1GPWzXfpN9ht3g7KsSu8eTB92Na5Wpmu7g"
@CK_PATH: "0xb11e'/0xccc0'"
@factory: (callback) ->
ledger.storage.sync.get "__apps_coinkite_api_key", (r) =>
api_key = r.__apps_coinkite_api_key
ledger.storage.sync.get "__apps_coinkite_api_secret", (r) =>
secret = r.__apps_coinkite_api_secret
if typeof secret == "string"
callback(new Coinkite(api_key, secret))
else
callback undefined
constructor: (api_key, secret) ->
@apiKey = api_key
@secret = secret
@httpClient = new HttpClient(@API_BASE)
getExtendedPublicKey: (index, callback) ->
path = @_buildPath(index)
try
ledger.app.wallet.getExtendedPublicKey path, (key) =>
@xpub = key._xpub58
ledger.app.wallet.signMessageWithBitId path, "Coinkite", (signature) =>
callback?({xpub: @xpub, signature: signature, path: path}, null)
catch error
callback?(null, error)
getRequestData: (request, callback) ->
url = '/v1/co-sign/' + request
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
getCosigner: (data, callback) ->
@cosigner = null
try
ledger.app.wallet.getExtendedPublicKey Coinkite.CK_PATH, (key) =>
xpub = key._xpub58
async.eachSeries data.cosigners, ((cosigner, finishedCallback) =>
check = cosigner.xpubkey_check
if xpub.indexOf(check, xpub.length - check.length) > 0
@cosigner = cosigner.CK_refnum
finishedCallback()
), (finished) =>
callback @cosigner, data.has_signed_already[@cosigner]
catch error
callback @cosigner
getCosignData: (request, cosigner, callback) ->
@request = request
@cosigner = cosigner
url = '/v1/co-sign/' + request + '/' + cosigner
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data.signing_info, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
getCosignSummary: (request, cosigner, callback) ->
@request = request
@cosigner = cosigner
url = '/v1/co-sign/' + request + '/' + cosigner + '.html'
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
cosignRequest: (data, post, callback) ->
try
transaction = Bitcoin.Transaction.deserialize(data.raw_unsigned_txn);
outputs_number = transaction['outs'].length
outputs_script = ledger.app.wallet._lwCard.dongle.formatP2SHOutputScript(transaction)
inputs = []
paths = []
scripts = []
for input in data.input_info
paths.push(@_buildPath(data.ledger_key?.subkey_index) + "/" + input.sp)
inputs.push([input.txn, Bitcoin.convert.bytesToHex(ledger.bitcoin.numToBytes(parseInt(input.out_num), 4).reverse())])
scripts.push(data.redeem_scripts[input.sp].redeem)
ledger.app.wallet._lwCard.dongle.signP2SHTransaction_async(inputs, scripts, outputs_number, outputs_script, paths)
.then (result) =>
signatures = []
index = 0
for input in data.inputs
signatures.push([result[index], input[1], input[0]])
index++
if post
url = '/v1/co-sign/' + @request + '/' + @cosigner + '/sign'
@_setAuthHeaders(url)
@httpClient
.do type: 'PUT', url: url, dataType: 'json', contentType: 'application/json', data: { signatures: signatures }
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
else
callback?(signatures, null)
.fail (error) =>
callback?(null, error)
catch error
callback?(null, error)
getRequestFromJSON: (data) ->
if data.contents?
$.extend { api: true }, JSON.parse(data.contents)
else
$.extend { api: true }, data
buildSignedJSON: (request, callback) ->
try
@verifyExtendedPublicKey request, (result, error) =>
if result
@cosignRequest request, false, (result, error) =>
if error?
return callback?(null, error)
path = @_buildPath(request.ledger_key?.subkey_index)
rv =
cosigner: request.cosigner,
request: request.request,
signatures: result
body =
_humans: "This transaction has been signed by a Ledger Wallet Nano",
content: JSON.stringify(rv)
ledger.app.wallet.getPublicAddress path, (key, error) =>
if error?
return callback?(null, error)
else
body.signed_by = key.bitcoinAddress.value
ledger.app.wallet.signMessageWithBitId path, sha256_digest(body.content), (signature) =>
body.signature_sha256 = signature
callback?(JSON.stringify(body), null)
else
callback?(null, t("apps.coinkite.cosign.errors.wrong_nano_text"))
catch error
callback?(null, error)
postSignedJSON: (json, callback) =>
httpClient = new HttpClient("https://coinkite.com")
httpClient
.do type: 'PUT', url: '/co-sign/done-signature', contentType: 'text/plain', data: json
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
if error.responseJSON?
callback?(null, error.responseJSON.message)
else
callback?(null, error.statusText)
.done()
verifyExtendedPublicKey: (request, callback) ->
check = request.xpubkey_check
ledger.app.wallet.getExtendedPublicKey @_buildPath(request.ledger_key?.subkey_index), (key) =>
xpub = key._xpub58
callback?(xpub.indexOf(check, xpub.length - check.length) > 0)
testDongleCompatibility: (callback) ->
transaction = Bitcoin.Transaction.deserialize("0100000001b4e84a9115e3633abaa1730689db782aa3bb54fa429a3c52a7fa55a788d611fd0100000000ffffffff02a0860100000000001976a914069b75ac23920928eda632a20525a027e67d040188ac50c300000000000017a914c70abc77a8bb21997a7a901b7e02d42c0c0bbf558700000000");
inputs = [ ["2<KEY>", "00000000"] ]
scripts = [ "522102feec7dd82317846908c20c342a02a8e8c17fb327390ce8d6669ef09a9c85904b210308aaece16e0f99b78e4beb30d8b18652af318428d6d64df26f8089010c7079f452ae" ]
outputs_number = transaction['outs'].length
outputs_script = ledger.app.wallet._lwCard.dongle.formatP2SHOutputScript(transaction)
paths = [ Coinkite.CK_PATH + "/0" ]
data = {
"input_info": [
{
"full_sp": "m/0",
"out_num": 1,
"sp": "0",
"txn": "fd11d688a755faa7523c9a42fa54bba32a78db890673a1ba3a63e315914ae8b4"
}
],
"inputs": [
[
"0",
"214af8788d11cf6e3a8dd2efb00d0c3facb446273dee2cf8023e1fae8b2afcbd"
]
],
"raw_unsigned_txn": "0100000001b4e84a9115e3633abaa1730689db782aa3bb54fa429a3c52a7fa55a788d611fd0100000000ffffffff02a0860100000000001976a914069b75ac23920928eda632a20525a027e67d040188ac50c300000000000017a914c70abc77a8bb21997a7a901b7e02d42c0c0bbf558700000000",
"redeem_scripts": {
"0": {
"addr": "3NjjSXDhRtn4yunA7P8DGGTQuyPnbktcs3",
"redeem": "522102feec7dd82317846908c20c342a02a8e8c17fb327390ce8d6669ef09a9c85904b210308aaece16e0f99b78e4beb30d8b18652af318428d6d64df26f8089010c7079f452ae"
}
},
}
try
ledger.app.wallet._lwCard.dongle.signP2SHTransaction_async(inputs, scripts, outputs_number, outputs_script, paths)
.then (result) =>
callback true
.fail (error) =>
callback false
catch error
callback false
_buildPath: (index) ->
path = Coinkite.CK_PATH
if index
path = path + "/" + index
return path
_setAuthHeaders: (endpoint) ->
endpoint = endpoint.split('?')[0]
ts = (new Date).toISOString()
data = endpoint + '|' + ts
@httpClient.setHttpHeader 'X-CK-Key', @apiKey
@httpClient.setHttpHeader 'X-CK-Sign', CryptoJS.HmacSHA256(data, @secret).toString()
@httpClient.setHttpHeader 'X-CK-Timestamp', ts | true | class @Coinkite
API_BASE: "https://api.coinkite.com"
CK_SIGNING_ADDRESS: "1GPWzXfpN9ht3g7KsSu8eTB92Na5Wpmu7g"
@CK_PATH: "0xb11e'/0xccc0'"
@factory: (callback) ->
ledger.storage.sync.get "__apps_coinkite_api_key", (r) =>
api_key = r.__apps_coinkite_api_key
ledger.storage.sync.get "__apps_coinkite_api_secret", (r) =>
secret = r.__apps_coinkite_api_secret
if typeof secret == "string"
callback(new Coinkite(api_key, secret))
else
callback undefined
constructor: (api_key, secret) ->
@apiKey = api_key
@secret = secret
@httpClient = new HttpClient(@API_BASE)
getExtendedPublicKey: (index, callback) ->
path = @_buildPath(index)
try
ledger.app.wallet.getExtendedPublicKey path, (key) =>
@xpub = key._xpub58
ledger.app.wallet.signMessageWithBitId path, "Coinkite", (signature) =>
callback?({xpub: @xpub, signature: signature, path: path}, null)
catch error
callback?(null, error)
getRequestData: (request, callback) ->
url = '/v1/co-sign/' + request
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
getCosigner: (data, callback) ->
@cosigner = null
try
ledger.app.wallet.getExtendedPublicKey Coinkite.CK_PATH, (key) =>
xpub = key._xpub58
async.eachSeries data.cosigners, ((cosigner, finishedCallback) =>
check = cosigner.xpubkey_check
if xpub.indexOf(check, xpub.length - check.length) > 0
@cosigner = cosigner.CK_refnum
finishedCallback()
), (finished) =>
callback @cosigner, data.has_signed_already[@cosigner]
catch error
callback @cosigner
getCosignData: (request, cosigner, callback) ->
@request = request
@cosigner = cosigner
url = '/v1/co-sign/' + request + '/' + cosigner
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data.signing_info, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
getCosignSummary: (request, cosigner, callback) ->
@request = request
@cosigner = cosigner
url = '/v1/co-sign/' + request + '/' + cosigner + '.html'
@_setAuthHeaders(url)
@httpClient
.do type: 'GET', url: url
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
cosignRequest: (data, post, callback) ->
try
transaction = Bitcoin.Transaction.deserialize(data.raw_unsigned_txn);
outputs_number = transaction['outs'].length
outputs_script = ledger.app.wallet._lwCard.dongle.formatP2SHOutputScript(transaction)
inputs = []
paths = []
scripts = []
for input in data.input_info
paths.push(@_buildPath(data.ledger_key?.subkey_index) + "/" + input.sp)
inputs.push([input.txn, Bitcoin.convert.bytesToHex(ledger.bitcoin.numToBytes(parseInt(input.out_num), 4).reverse())])
scripts.push(data.redeem_scripts[input.sp].redeem)
ledger.app.wallet._lwCard.dongle.signP2SHTransaction_async(inputs, scripts, outputs_number, outputs_script, paths)
.then (result) =>
signatures = []
index = 0
for input in data.inputs
signatures.push([result[index], input[1], input[0]])
index++
if post
url = '/v1/co-sign/' + @request + '/' + @cosigner + '/sign'
@_setAuthHeaders(url)
@httpClient
.do type: 'PUT', url: url, dataType: 'json', contentType: 'application/json', data: { signatures: signatures }
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
callback?(null, error.responseJSON.message + ' ' + error.responseJSON.help_msg)
.done()
else
callback?(signatures, null)
.fail (error) =>
callback?(null, error)
catch error
callback?(null, error)
getRequestFromJSON: (data) ->
if data.contents?
$.extend { api: true }, JSON.parse(data.contents)
else
$.extend { api: true }, data
buildSignedJSON: (request, callback) ->
try
@verifyExtendedPublicKey request, (result, error) =>
if result
@cosignRequest request, false, (result, error) =>
if error?
return callback?(null, error)
path = @_buildPath(request.ledger_key?.subkey_index)
rv =
cosigner: request.cosigner,
request: request.request,
signatures: result
body =
_humans: "This transaction has been signed by a Ledger Wallet Nano",
content: JSON.stringify(rv)
ledger.app.wallet.getPublicAddress path, (key, error) =>
if error?
return callback?(null, error)
else
body.signed_by = key.bitcoinAddress.value
ledger.app.wallet.signMessageWithBitId path, sha256_digest(body.content), (signature) =>
body.signature_sha256 = signature
callback?(JSON.stringify(body), null)
else
callback?(null, t("apps.coinkite.cosign.errors.wrong_nano_text"))
catch error
callback?(null, error)
postSignedJSON: (json, callback) =>
httpClient = new HttpClient("https://coinkite.com")
httpClient
.do type: 'PUT', url: '/co-sign/done-signature', contentType: 'text/plain', data: json
.then (data, statusText, jqXHR) =>
callback?(data, null)
.fail (error, statusText) =>
if error.responseJSON?
callback?(null, error.responseJSON.message)
else
callback?(null, error.statusText)
.done()
verifyExtendedPublicKey: (request, callback) ->
check = request.xpubkey_check
ledger.app.wallet.getExtendedPublicKey @_buildPath(request.ledger_key?.subkey_index), (key) =>
xpub = key._xpub58
callback?(xpub.indexOf(check, xpub.length - check.length) > 0)
testDongleCompatibility: (callback) ->
transaction = Bitcoin.Transaction.deserialize("0100000001b4e84a9115e3633abaa1730689db782aa3bb54fa429a3c52a7fa55a788d611fd0100000000ffffffff02a0860100000000001976a914069b75ac23920928eda632a20525a027e67d040188ac50c300000000000017a914c70abc77a8bb21997a7a901b7e02d42c0c0bbf558700000000");
inputs = [ ["2PI:KEY:<KEY>END_PI", "00000000"] ]
scripts = [ "522102feec7dd82317846908c20c342a02a8e8c17fb327390ce8d6669ef09a9c85904b210308aaece16e0f99b78e4beb30d8b18652af318428d6d64df26f8089010c7079f452ae" ]
outputs_number = transaction['outs'].length
outputs_script = ledger.app.wallet._lwCard.dongle.formatP2SHOutputScript(transaction)
paths = [ Coinkite.CK_PATH + "/0" ]
data = {
"input_info": [
{
"full_sp": "m/0",
"out_num": 1,
"sp": "0",
"txn": "fd11d688a755faa7523c9a42fa54bba32a78db890673a1ba3a63e315914ae8b4"
}
],
"inputs": [
[
"0",
"214af8788d11cf6e3a8dd2efb00d0c3facb446273dee2cf8023e1fae8b2afcbd"
]
],
"raw_unsigned_txn": "0100000001b4e84a9115e3633abaa1730689db782aa3bb54fa429a3c52a7fa55a788d611fd0100000000ffffffff02a0860100000000001976a914069b75ac23920928eda632a20525a027e67d040188ac50c300000000000017a914c70abc77a8bb21997a7a901b7e02d42c0c0bbf558700000000",
"redeem_scripts": {
"0": {
"addr": "3NjjSXDhRtn4yunA7P8DGGTQuyPnbktcs3",
"redeem": "522102feec7dd82317846908c20c342a02a8e8c17fb327390ce8d6669ef09a9c85904b210308aaece16e0f99b78e4beb30d8b18652af318428d6d64df26f8089010c7079f452ae"
}
},
}
try
ledger.app.wallet._lwCard.dongle.signP2SHTransaction_async(inputs, scripts, outputs_number, outputs_script, paths)
.then (result) =>
callback true
.fail (error) =>
callback false
catch error
callback false
_buildPath: (index) ->
path = Coinkite.CK_PATH
if index
path = path + "/" + index
return path
_setAuthHeaders: (endpoint) ->
endpoint = endpoint.split('?')[0]
ts = (new Date).toISOString()
data = endpoint + '|' + ts
@httpClient.setHttpHeader 'X-CK-Key', @apiKey
@httpClient.setHttpHeader 'X-CK-Sign', CryptoJS.HmacSHA256(data, @secret).toString()
@httpClient.setHttpHeader 'X-CK-Timestamp', ts |
[
{
"context": "يل الدخول\"\n signOut: \"تسجيل الخروج\"\n signUp: \"افتح حساب جديد\"\n OR: \"او\"\n forgotPassword: \"نسيت كل",
"end": 95,
"score": 0.5148271322250366,
"start": 94,
"tag": "NAME",
"value": "ت"
},
{
"context": "لدخول\"\n signOut: \"تسجيل الخروج\"\n signUp: \"افتح ح... | client/t9n/arabic.coffee | JutoApp/accounts-entry | 167 | ar =
signIn: "تسجيل الدخول"
signin: "تسجيل الدخول"
signOut: "تسجيل الخروج"
signUp: "افتح حساب جديد"
OR: "او"
forgotPassword: "نسيت كلمة السر؟"
emailAddress: "البريد الالكترونى"
emailResetLink: "اعادة تعيين البريد الالكترونى"
dontHaveAnAccount: "ليس عندك حساب؟"
resetYourPassword: "اعادة تعيين كلمة السر"
updateYourPassword: "جدد كلمة السر"
password: "كلمة السر"
usernameOrEmail: "اسم المستخدم او البريد الالكترونى"
email: "البريد الالكترونى"
ifYouAlreadyHaveAnAccount: "اذا كان عندك حساب"
signUpWithYourEmailAddress: "سجل ببريدك الالكترونى"
username: "اسم المستخدم"
optional: "اختيارى"
signupCode: "رمز التسجيل"
clickAgree: "بفتح حسابك انت توافق على"
privacyPolicy: "سياسة الخصوصية"
terms: "شروط الاستخدام"
sign: "تسجيل"
configure: "تعديل"
with: "مع"
createAccount: "افتح حساب جديد"
verificationPending: "Confirm your email address"
verificationPendingDetails: "A confirmation email has been sent to the email address you provided. Click on the confirmation link in the email to activate your account."
and: "و"
"Match failed": "المطابقة فشلت"
"User not found": "اسم المستخدم غير موجود"
error:
minChar: "سبعة حروف هو الحد الادنى لكلمة السر"
pwOneLetter: "كلمة السر تحتاج الى حرف اخر"
pwOneDigit: "كلمة السر يجب ان تحتوى على رقم واحد على الاقل"
usernameRequired: "اسم المستخدم مطلوب"
emailRequired: "البريد الالكترونى مطلوب"
signupCodeRequired: "رمز التسجيل مطلوب"
signupCodeIncorrect: "رمز التسجيل غير صحيح"
signInRequired: "عليك بتسجبل الدخول لفعل ذلك"
usernameIsEmail: "اسم المستخدم لا يمكن ان يكون بريد الكترونى"
T9n.map "ar", ar
| 12602 | ar =
signIn: "تسجيل الدخول"
signin: "تسجيل الدخول"
signOut: "تسجيل الخروج"
signUp: "اف<NAME>ح ح<NAME>"
OR: "او"
forgotPassword: "<PASSWORD>؟"
emailAddress: "البريد الالكترونى"
emailResetLink: "اعادة تعيين البريد الالكترونى"
dontHaveAnAccount: "ليس عندك حساب؟"
resetYourPassword: "<PASSWORD>"
updateYourPassword: "<PASSWORD>"
password: "<PASSWORD>"
usernameOrEmail: "<NAME> او البريد الالكترونى"
email: "البريد الالكترونى"
ifYouAlreadyHaveAnAccount: "اذا كان عندك حساب"
signUpWithYourEmailAddress: "سجل ببريدك الالكترونى"
username: "<NAME>"
optional: "اختيارى"
signupCode: "<NAME>"
clickAgree: "بفتح حسابك انت توافق على"
privacyPolicy: "سياسة الخصوصية"
terms: "شروط الاستخدام"
sign: "تسجيل"
configure: "تعديل"
with: "مع"
createAccount: "اف<NAME>"
verificationPending: "Confirm your email address"
verificationPendingDetails: "A confirmation email has been sent to the email address you provided. Click on the confirmation link in the email to activate your account."
and: "و"
"Match failed": "المطابقة فشلت"
"User not found": "اسم المستخدم غير موجود"
error:
minChar: "سبعة حروف هو الحد الادنى لكلمة السر"
pwOneLetter: "كلمة السر تحتاج الى حرف اخر"
pwOneDigit: "كلمة السر يجب ان تحتوى على رقم واحد على الاقل"
usernameRequired: "<NAME>"
emailRequired: "البريد الالكترونى مطلوب"
signupCodeRequired: "رمز التسجيل مطلوب"
signupCodeIncorrect: "رمز التسجيل غير صحيح"
signInRequired: "عليك بتسجبل الدخول لفعل ذلك"
usernameIsEmail: "<NAME> ي<NAME>كن ان يكون بريد الكترونى"
T9n.map "ar", ar
| true | ar =
signIn: "تسجيل الدخول"
signin: "تسجيل الدخول"
signOut: "تسجيل الخروج"
signUp: "افPI:NAME:<NAME>END_PIح حPI:NAME:<NAME>END_PI"
OR: "او"
forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI؟"
emailAddress: "البريد الالكترونى"
emailResetLink: "اعادة تعيين البريد الالكترونى"
dontHaveAnAccount: "ليس عندك حساب؟"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
usernameOrEmail: "PI:NAME:<NAME>END_PI او البريد الالكترونى"
email: "البريد الالكترونى"
ifYouAlreadyHaveAnAccount: "اذا كان عندك حساب"
signUpWithYourEmailAddress: "سجل ببريدك الالكترونى"
username: "PI:NAME:<NAME>END_PI"
optional: "اختيارى"
signupCode: "PI:NAME:<NAME>END_PI"
clickAgree: "بفتح حسابك انت توافق على"
privacyPolicy: "سياسة الخصوصية"
terms: "شروط الاستخدام"
sign: "تسجيل"
configure: "تعديل"
with: "مع"
createAccount: "افPI:NAME:<NAME>END_PI"
verificationPending: "Confirm your email address"
verificationPendingDetails: "A confirmation email has been sent to the email address you provided. Click on the confirmation link in the email to activate your account."
and: "و"
"Match failed": "المطابقة فشلت"
"User not found": "اسم المستخدم غير موجود"
error:
minChar: "سبعة حروف هو الحد الادنى لكلمة السر"
pwOneLetter: "كلمة السر تحتاج الى حرف اخر"
pwOneDigit: "كلمة السر يجب ان تحتوى على رقم واحد على الاقل"
usernameRequired: "PI:NAME:<NAME>END_PI"
emailRequired: "البريد الالكترونى مطلوب"
signupCodeRequired: "رمز التسجيل مطلوب"
signupCodeIncorrect: "رمز التسجيل غير صحيح"
signInRequired: "عليك بتسجبل الدخول لفعل ذلك"
usernameIsEmail: "PI:NAME:<NAME>END_PI يPI:NAME:<NAME>END_PIكن ان يكون بريد الكترونى"
T9n.map "ar", ar
|
[
{
"context": "host\" }\n ])\n .resolves({\n name: \"foo\"\n })\n .withArgs(\"clear:cookies\", [\n ",
"end": 27048,
"score": 0.6845391988754272,
"start": 27045,
"tag": "NAME",
"value": "foo"
},
{
"context": "host\" }\n ])\n .resolves({\n ... | packages/driver/test/cypress/integration/commands/cookies_spec.coffee | adancarrasco/cypress | 1 | _ = Cypress._
Promise = Cypress.Promise
describe "src/cy/commands/cookies", ->
beforeEach ->
## call through normally on everything
cy.stub(Cypress, "automation").rejects(new Error('Cypress.automation was not stubbed'))
context "test:before:run:async", ->
it "can test unstubbed, real server", ->
Cypress.automation.restore()
cy.setCookie('foo', 'bar')
it "clears cookies before each test run", ->
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { domain: "localhost", name: "foo" } ])
.resolves([])
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookies",
{ domain: "localhost" }
)
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { domain: "localhost", name: "foo" } ]
)
it "does not call clear:cookies when get:cookies returns empty array", ->
Cypress.automation.withArgs("get:cookies").resolves([])
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(Cypress.automation).not.to.be.calledWith(
"clear:cookies"
)
it "does not attempt to time out", ->
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { domain: "localhost", name: "foo" } ])
.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(timeout).not.to.be.called
context "#getCookies", ->
it "returns array of cookies", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.getCookies().should("deep.eq", []).then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookies",
{ domain: "localhost" }
)
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookies().then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookies({timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves([])
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.getCookies().then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookies")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookies"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.getCookies()` had an unexpected error reading cookies from #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.getCookies()
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("getCookies")
expect(lastLog.get("message")).to.eq("")
expect(err.message).to.eq("`cy.getCookies()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/getcookies")
done()
cy.getCookies({timeout: 50})
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([
{name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}
])
it "can turn off logging", ->
cy.getCookies({log: false}).then ->
expect(@lastLog).to.be.undefined
it "ends immediately", ->
cy.getCookies().then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.getCookies().then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.getCookies().then (cookies) ->
expect(cookies).to.deep.eq([{name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}])
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookies
expect(c["Num Cookies"]).to.eq 1
context "#getCookie", ->
it "returns single cookie by name", ->
Cypress.automation.withArgs("get:cookie").resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
cy.getCookie("foo").should("deep.eq", {
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
}).then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookie",
{ domain: "localhost", name: "foo" }
)
it "returns null when no cookie was found", ->
Cypress.automation.withArgs("get:cookie").resolves(null)
cy.getCookie("foo").should("be.null")
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookie("foo").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookie("foo", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves(null)
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.getCookie("foo").then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.getCookie()` had an unexpected error reading the requested cookie from #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.getCookie("foo")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("getCookie")
expect(lastLog.get("message")).to.eq("foo")
expect(err.message).to.eq("`cy.getCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/getcookie")
done()
cy.getCookie("foo", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.getCookie()` must be passed a string argument for name."
expect(lastLog.get("error").docsUrl).to.eq("https://on.cypress.io/getcookie")
expect(lastLog.get("error")).to.eq(err)
done()
cy.getCookie(123)
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookie"
@lastLog = log
Cypress.automation
.withArgs("get:cookie", { domain: "localhost", name: "foo" })
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
.withArgs("get:cookie", { domain: "localhost", name: "bar" })
.resolves(null)
it "can turn off logging", ->
cy.getCookie("foo", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "has correct message", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("message")).to.eq("foo")
it "snapshots immediately", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.getCookie("foo").then (cookie) ->
expect(cookie).to.deep.eq({name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false})
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookie
it "#consoleProps when no cookie found", ->
cy.getCookie("bar").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq "null"
expect(c["Note"]).to.eq("No cookie with the name: 'bar' was found.")
context "#setCookie", ->
beforeEach ->
cy.stub(Cypress.utils, "addTwentyYears").returns(12345)
it "returns set cookie", ->
Cypress.automation.withArgs("set:cookie").resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: false, httpOnly: false, expiry: 12345
})
cy.setCookie("foo", "bar").should("deep.eq", {
name: "foo", value: "bar", domain: "localhost", path: "/", secure: false, httpOnly: false, expiry: 12345
}).then ->
expect(Cypress.automation).to.be.calledWith(
"set:cookie",
{ domain: "localhost", name: "foo", value: "bar", path: "/", secure: false, httpOnly: false, expiry: 12345, sameSite: undefined }
)
it "can change options", ->
Cypress.automation.withArgs("set:cookie").resolves({
name: "foo", value: "bar", domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987
})
cy.setCookie("foo", "bar", {domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987}).should("deep.eq", {
name: "foo", value: "bar", domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987
}).then ->
expect(Cypress.automation).to.be.calledWith(
"set:cookie",
{ domain: "brian.dev.local", name: "foo", value: "bar", path: "/foo", secure: true, httpOnly: true, expiry: 987, sameSite: undefined }
)
it "does not mutate options", ->
Cypress.automation.resolves()
options = {}
cy.setCookie("foo", "bar", {}).then ->
expect(options).deep.eq({})
it "can set cookies with sameSite", ->
Cypress.automation.restore()
Cypress.utils.addTwentyYears.restore()
Cypress.sinon.stub(Cypress, 'config').callThrough()
.withArgs('experimentalGetCookiesSameSite').returns(true)
cy.setCookie('one', 'bar', { sameSite: 'none', secure: true })
cy.getCookie('one').should('include', { sameSite: 'no_restriction' })
cy.setCookie('two', 'bar', { sameSite: 'no_restriction', secure: true })
cy.getCookie('two').should('include', { sameSite: 'no_restriction' })
cy.setCookie('three', 'bar', { sameSite: 'Lax' })
cy.getCookie('three').should('include', { sameSite: 'lax' })
cy.setCookie('four', 'bar', { sameSite: 'Strict' })
cy.getCookie('four').should('include', { sameSite: 'strict' })
cy.setCookie('five', 'bar')
## @see https://bugzilla.mozilla.org/show_bug.cgi?id=1624668
if Cypress.isBrowser('firefox')
cy.getCookie('five').should('include', { sameSite: 'no_restriction' })
else
cy.getCookie('five').should('not.have.property', 'sameSite')
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.setCookie("foo", "bar").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.setCookie("foo", "bar", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves(null)
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.setCookie("foo", "bar").then ->
expect(cy.clearTimeout).to.be.calledWith("set:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "setCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.include "some err message"
expect(lastLog.get("error").name).to.eq "CypressError"
expect(lastLog.get("error").stack).to.include error.stack
done()
cy.setCookie("foo", "bar")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("setCookie")
expect(lastLog.get("message")).to.eq("foo, bar")
expect(err.message).to.include("`cy.setCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/setcookie")
done()
cy.setCookie("foo", "bar", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.setCookie()` must be passed two string arguments for `name` and `value`."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie(123)
it "requires a string value", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.setCookie()` must be passed two string arguments for `name` and `value`."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie("foo", 123)
it "when an invalid samesite prop is supplied", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq """
If a `sameSite` value is supplied to `cy.setCookie()`, it must be a string from the following list:
> no_restriction, lax, strict
You passed:
> bad
"""
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie('foo', 'bar', { sameSite: 'bad' })
it "when samesite=none is supplied and secure is not set", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq """
Only cookies with the `secure` flag set to `true` can use `sameSite: 'None'`.
Pass `secure: true` to `cy.setCookie()` to set a cookie with `sameSite: 'None'`.
"""
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie('foo', 'bar', { sameSite: 'None' })
context "when setting an invalid cookie", ->
it "throws an error if the backend responds with an error", (done) ->
err = new Error("backend could not set cookie")
Cypress.automation.withArgs("set:cookie").rejects(err)
cy.on "fail", (err) =>
expect(Cypress.automation.withArgs("set:cookie")).to.be.calledOnce
expect(err.message).to.contain('unexpected error setting the requested cookie')
expect(err.message).to.contain(err.message)
done()
## browser backend should yell since this is invalid
cy.setCookie("foo", " bar")
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "setCookie"
@lastLog = log
Cypress.automation
.withArgs("set:cookie", {
domain: "localhost", name: "foo", value: "bar", path: "/", secure: false, httpOnly: false, expiry: 12345, sameSite: undefined
})
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
it "can turn off logging", ->
cy.setCookie("foo", "bar", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.setCookie("foo", "bar").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.setCookie("foo", "bar").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.setCookie("foo", "bar").then (cookie) ->
expect(cookie).to.deep.eq({name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false})
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookie
context "#clearCookie", ->
it "returns null", ->
Cypress.automation.withArgs("clear:cookie").resolves(null)
cy.clearCookie("foo").should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookie",
{ domain: "localhost", name: "foo" }
)
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookie("foo").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookie("foo", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves([])
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.clearCookie("foo").then ->
expect(cy.clearTimeout).to.be.calledWith("clear:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookie()` had an unexpected error clearing the requested cookie in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.clearCookie("foo")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("clearCookie")
expect(lastLog.get("message")).to.eq("foo")
expect(err.message).to.eq("`cy.clearCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/clearcookie")
done()
cy.clearCookie("foo", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.clearCookie()` must be passed a string argument for name."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/clearcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookie(123)
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookie"
@lastLog = log
Cypress.automation
.withArgs("clear:cookie", { domain: "localhost", name: "foo" })
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
.withArgs("clear:cookie", { domain: "localhost", name: "bar" })
.resolves(null)
it "can turn off logging", ->
cy.clearCookie("foo", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.clearCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.clearCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.clearCookie("foo").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookie"]).to.deep.eq {name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}
it "#consoleProps when no matching cookie was found", ->
cy.clearCookie("bar").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookie"]).to.be.undefined
expect(c["Note"]).to.eq "No cookie with the name: 'bar' was found or removed."
context "#clearCookies", ->
it "returns null", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.clearCookies().should("be.null")
it "does not call 'clear:cookies' when no cookies were returned", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.clearCookies().then ->
expect(Cypress.automation).not.to.be.calledWith(
"clear:cookies"
)
it "calls 'clear:cookies' only with clearableCookies", ->
Cypress.automation
.withArgs("get:cookies")
.resolves([
{ name: "foo" },
{ name: "bar" }
])
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
])
.resolves({
name: "foo"
})
cy.stub(Cypress.Cookies, "getClearableCookies")
.withArgs([{name: "foo"}, {name: "bar"}])
.returns([{name: "foo"}])
cy.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { name: "foo", domain: "localhost" } ]
)
it "calls 'clear:cookies' with all cookies", ->
Cypress.Cookies.preserveOnce("bar", "baz")
Cypress.automation
.withArgs("get:cookies")
.resolves([
{ name: "foo" },
{ name: "bar" }
{ name: "baz" }
])
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
])
.resolves({
name: "foo"
})
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
{ name: "bar", domain: "localhost" }
{ name: "baz", domain: "localhost" }
])
.resolves({
name: "foo"
})
cy
.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { name: "foo", domain: "localhost" } ]
)
.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies", [
{ name: "foo", domain: "localhost" }
{ name: "bar", domain: "localhost" }
{ name: "baz", domain: "localhost" }
]
)
describe "timeout", ->
beforeEach ->
Cypress.automation
.withArgs("get:cookies")
.resolves([{}])
.withArgs("clear:cookies")
.resolves({})
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookies().then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookies({timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.clearCookies().then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookies")
expect(cy.clearTimeout).to.be.calledWith("clear:cookies")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
@logs.push(log)
return null
it "logs once on 'get:cookies' error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookies()` had an unexpected error clearing cookies in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookies()
it "throws after timing out", (done) ->
Cypress.automation.resolves([{ name: "foo" }])
Cypress.automation.withArgs("clear:cookies").resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("clearCookies")
expect(lastLog.get("message")).to.eq("")
expect(err.message).to.eq("`cy.clearCookies()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/clearcookies")
done()
cy.clearCookies({timeout: 50})
it "logs once on 'clear:cookies' error", (done) ->
Cypress.automation.withArgs("get:cookies").resolves([
{name: "foo"}, {name: "bar"}
])
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.withArgs("clear:cookies").rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookies()` had an unexpected error clearing cookies in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookies()
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { name: "foo", domain: "localhost" } ])
.resolves([
{ name: "foo" }
])
it "can turn off logging", ->
cy.clearCookies({log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.clearCookies().then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.clearCookies().then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.deep.eq [{name: "foo"}]
expect(c["Num Cookies"]).to.eq 1
describe ".log with no cookies returned", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([])
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.be.undefined
expect(c["Note"]).to.eq "No cookies were found or removed."
describe ".log when no cookies were cleared", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { name: "foo", domain: "localhost" } ])
.resolves([])
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.be.undefined
expect(c["Note"]).to.eq "No cookies were found or removed."
| 109583 | _ = Cypress._
Promise = Cypress.Promise
describe "src/cy/commands/cookies", ->
beforeEach ->
## call through normally on everything
cy.stub(Cypress, "automation").rejects(new Error('Cypress.automation was not stubbed'))
context "test:before:run:async", ->
it "can test unstubbed, real server", ->
Cypress.automation.restore()
cy.setCookie('foo', 'bar')
it "clears cookies before each test run", ->
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { domain: "localhost", name: "foo" } ])
.resolves([])
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookies",
{ domain: "localhost" }
)
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { domain: "localhost", name: "foo" } ]
)
it "does not call clear:cookies when get:cookies returns empty array", ->
Cypress.automation.withArgs("get:cookies").resolves([])
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(Cypress.automation).not.to.be.calledWith(
"clear:cookies"
)
it "does not attempt to time out", ->
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { domain: "localhost", name: "foo" } ])
.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(timeout).not.to.be.called
context "#getCookies", ->
it "returns array of cookies", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.getCookies().should("deep.eq", []).then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookies",
{ domain: "localhost" }
)
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookies().then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookies({timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves([])
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.getCookies().then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookies")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookies"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.getCookies()` had an unexpected error reading cookies from #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.getCookies()
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("getCookies")
expect(lastLog.get("message")).to.eq("")
expect(err.message).to.eq("`cy.getCookies()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/getcookies")
done()
cy.getCookies({timeout: 50})
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([
{name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}
])
it "can turn off logging", ->
cy.getCookies({log: false}).then ->
expect(@lastLog).to.be.undefined
it "ends immediately", ->
cy.getCookies().then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.getCookies().then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.getCookies().then (cookies) ->
expect(cookies).to.deep.eq([{name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}])
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookies
expect(c["Num Cookies"]).to.eq 1
context "#getCookie", ->
it "returns single cookie by name", ->
Cypress.automation.withArgs("get:cookie").resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
cy.getCookie("foo").should("deep.eq", {
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
}).then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookie",
{ domain: "localhost", name: "foo" }
)
it "returns null when no cookie was found", ->
Cypress.automation.withArgs("get:cookie").resolves(null)
cy.getCookie("foo").should("be.null")
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookie("foo").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookie("foo", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves(null)
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.getCookie("foo").then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.getCookie()` had an unexpected error reading the requested cookie from #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.getCookie("foo")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("getCookie")
expect(lastLog.get("message")).to.eq("foo")
expect(err.message).to.eq("`cy.getCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/getcookie")
done()
cy.getCookie("foo", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.getCookie()` must be passed a string argument for name."
expect(lastLog.get("error").docsUrl).to.eq("https://on.cypress.io/getcookie")
expect(lastLog.get("error")).to.eq(err)
done()
cy.getCookie(123)
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookie"
@lastLog = log
Cypress.automation
.withArgs("get:cookie", { domain: "localhost", name: "foo" })
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
.withArgs("get:cookie", { domain: "localhost", name: "bar" })
.resolves(null)
it "can turn off logging", ->
cy.getCookie("foo", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "has correct message", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("message")).to.eq("foo")
it "snapshots immediately", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.getCookie("foo").then (cookie) ->
expect(cookie).to.deep.eq({name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false})
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookie
it "#consoleProps when no cookie found", ->
cy.getCookie("bar").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq "null"
expect(c["Note"]).to.eq("No cookie with the name: 'bar' was found.")
context "#setCookie", ->
beforeEach ->
cy.stub(Cypress.utils, "addTwentyYears").returns(12345)
it "returns set cookie", ->
Cypress.automation.withArgs("set:cookie").resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: false, httpOnly: false, expiry: 12345
})
cy.setCookie("foo", "bar").should("deep.eq", {
name: "foo", value: "bar", domain: "localhost", path: "/", secure: false, httpOnly: false, expiry: 12345
}).then ->
expect(Cypress.automation).to.be.calledWith(
"set:cookie",
{ domain: "localhost", name: "foo", value: "bar", path: "/", secure: false, httpOnly: false, expiry: 12345, sameSite: undefined }
)
it "can change options", ->
Cypress.automation.withArgs("set:cookie").resolves({
name: "foo", value: "bar", domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987
})
cy.setCookie("foo", "bar", {domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987}).should("deep.eq", {
name: "foo", value: "bar", domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987
}).then ->
expect(Cypress.automation).to.be.calledWith(
"set:cookie",
{ domain: "brian.dev.local", name: "foo", value: "bar", path: "/foo", secure: true, httpOnly: true, expiry: 987, sameSite: undefined }
)
it "does not mutate options", ->
Cypress.automation.resolves()
options = {}
cy.setCookie("foo", "bar", {}).then ->
expect(options).deep.eq({})
it "can set cookies with sameSite", ->
Cypress.automation.restore()
Cypress.utils.addTwentyYears.restore()
Cypress.sinon.stub(Cypress, 'config').callThrough()
.withArgs('experimentalGetCookiesSameSite').returns(true)
cy.setCookie('one', 'bar', { sameSite: 'none', secure: true })
cy.getCookie('one').should('include', { sameSite: 'no_restriction' })
cy.setCookie('two', 'bar', { sameSite: 'no_restriction', secure: true })
cy.getCookie('two').should('include', { sameSite: 'no_restriction' })
cy.setCookie('three', 'bar', { sameSite: 'Lax' })
cy.getCookie('three').should('include', { sameSite: 'lax' })
cy.setCookie('four', 'bar', { sameSite: 'Strict' })
cy.getCookie('four').should('include', { sameSite: 'strict' })
cy.setCookie('five', 'bar')
## @see https://bugzilla.mozilla.org/show_bug.cgi?id=1624668
if Cypress.isBrowser('firefox')
cy.getCookie('five').should('include', { sameSite: 'no_restriction' })
else
cy.getCookie('five').should('not.have.property', 'sameSite')
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.setCookie("foo", "bar").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.setCookie("foo", "bar", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves(null)
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.setCookie("foo", "bar").then ->
expect(cy.clearTimeout).to.be.calledWith("set:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "setCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.include "some err message"
expect(lastLog.get("error").name).to.eq "CypressError"
expect(lastLog.get("error").stack).to.include error.stack
done()
cy.setCookie("foo", "bar")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("setCookie")
expect(lastLog.get("message")).to.eq("foo, bar")
expect(err.message).to.include("`cy.setCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/setcookie")
done()
cy.setCookie("foo", "bar", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.setCookie()` must be passed two string arguments for `name` and `value`."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie(123)
it "requires a string value", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.setCookie()` must be passed two string arguments for `name` and `value`."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie("foo", 123)
it "when an invalid samesite prop is supplied", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq """
If a `sameSite` value is supplied to `cy.setCookie()`, it must be a string from the following list:
> no_restriction, lax, strict
You passed:
> bad
"""
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie('foo', 'bar', { sameSite: 'bad' })
it "when samesite=none is supplied and secure is not set", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq """
Only cookies with the `secure` flag set to `true` can use `sameSite: 'None'`.
Pass `secure: true` to `cy.setCookie()` to set a cookie with `sameSite: 'None'`.
"""
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie('foo', 'bar', { sameSite: 'None' })
context "when setting an invalid cookie", ->
it "throws an error if the backend responds with an error", (done) ->
err = new Error("backend could not set cookie")
Cypress.automation.withArgs("set:cookie").rejects(err)
cy.on "fail", (err) =>
expect(Cypress.automation.withArgs("set:cookie")).to.be.calledOnce
expect(err.message).to.contain('unexpected error setting the requested cookie')
expect(err.message).to.contain(err.message)
done()
## browser backend should yell since this is invalid
cy.setCookie("foo", " bar")
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "setCookie"
@lastLog = log
Cypress.automation
.withArgs("set:cookie", {
domain: "localhost", name: "foo", value: "bar", path: "/", secure: false, httpOnly: false, expiry: 12345, sameSite: undefined
})
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
it "can turn off logging", ->
cy.setCookie("foo", "bar", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.setCookie("foo", "bar").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.setCookie("foo", "bar").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.setCookie("foo", "bar").then (cookie) ->
expect(cookie).to.deep.eq({name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false})
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookie
context "#clearCookie", ->
it "returns null", ->
Cypress.automation.withArgs("clear:cookie").resolves(null)
cy.clearCookie("foo").should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookie",
{ domain: "localhost", name: "foo" }
)
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookie("foo").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookie("foo", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves([])
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.clearCookie("foo").then ->
expect(cy.clearTimeout).to.be.calledWith("clear:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookie()` had an unexpected error clearing the requested cookie in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.clearCookie("foo")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("clearCookie")
expect(lastLog.get("message")).to.eq("foo")
expect(err.message).to.eq("`cy.clearCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/clearcookie")
done()
cy.clearCookie("foo", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.clearCookie()` must be passed a string argument for name."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/clearcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookie(123)
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookie"
@lastLog = log
Cypress.automation
.withArgs("clear:cookie", { domain: "localhost", name: "foo" })
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
.withArgs("clear:cookie", { domain: "localhost", name: "bar" })
.resolves(null)
it "can turn off logging", ->
cy.clearCookie("foo", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.clearCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.clearCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.clearCookie("foo").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookie"]).to.deep.eq {name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}
it "#consoleProps when no matching cookie was found", ->
cy.clearCookie("bar").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookie"]).to.be.undefined
expect(c["Note"]).to.eq "No cookie with the name: 'bar' was found or removed."
context "#clearCookies", ->
it "returns null", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.clearCookies().should("be.null")
it "does not call 'clear:cookies' when no cookies were returned", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.clearCookies().then ->
expect(Cypress.automation).not.to.be.calledWith(
"clear:cookies"
)
it "calls 'clear:cookies' only with clearableCookies", ->
Cypress.automation
.withArgs("get:cookies")
.resolves([
{ name: "foo" },
{ name: "bar" }
])
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
])
.resolves({
name: "foo"
})
cy.stub(Cypress.Cookies, "getClearableCookies")
.withArgs([{name: "foo"}, {name: "bar"}])
.returns([{name: "foo"}])
cy.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { name: "foo", domain: "localhost" } ]
)
it "calls 'clear:cookies' with all cookies", ->
Cypress.Cookies.preserveOnce("bar", "baz")
Cypress.automation
.withArgs("get:cookies")
.resolves([
{ name: "foo" },
{ name: "bar" }
{ name: "baz" }
])
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
])
.resolves({
name: "<NAME>"
})
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
{ name: "bar", domain: "localhost" }
{ name: "baz", domain: "localhost" }
])
.resolves({
name: "<NAME>"
})
cy
.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { name: "foo", domain: "localhost" } ]
)
.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies", [
{ name: "foo", domain: "localhost" }
{ name: "bar", domain: "localhost" }
{ name: "baz", domain: "localhost" }
]
)
describe "timeout", ->
beforeEach ->
Cypress.automation
.withArgs("get:cookies")
.resolves([{}])
.withArgs("clear:cookies")
.resolves({})
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookies().then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookies({timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.clearCookies().then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookies")
expect(cy.clearTimeout).to.be.calledWith("clear:cookies")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
@logs.push(log)
return null
it "logs once on 'get:cookies' error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookies()` had an unexpected error clearing cookies in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookies()
it "throws after timing out", (done) ->
Cypress.automation.resolves([{ name: "foo" }])
Cypress.automation.withArgs("clear:cookies").resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("clearCookies")
expect(lastLog.get("message")).to.eq("")
expect(err.message).to.eq("`cy.clearCookies()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/clearcookies")
done()
cy.clearCookies({timeout: 50})
it "logs once on 'clear:cookies' error", (done) ->
Cypress.automation.withArgs("get:cookies").resolves([
{name: "foo"}, {name: "bar"}
])
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.withArgs("clear:cookies").rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookies()` had an unexpected error clearing cookies in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookies()
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { name: "foo", domain: "localhost" } ])
.resolves([
{ name: "foo" }
])
it "can turn off logging", ->
cy.clearCookies({log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.clearCookies().then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.clearCookies().then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.deep.eq [{name: "foo"}]
expect(c["Num Cookies"]).to.eq 1
describe ".log with no cookies returned", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([])
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.be.undefined
expect(c["Note"]).to.eq "No cookies were found or removed."
describe ".log when no cookies were cleared", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { name: "foo", domain: "localhost" } ])
.resolves([])
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.be.undefined
expect(c["Note"]).to.eq "No cookies were found or removed."
| true | _ = Cypress._
Promise = Cypress.Promise
describe "src/cy/commands/cookies", ->
beforeEach ->
## call through normally on everything
cy.stub(Cypress, "automation").rejects(new Error('Cypress.automation was not stubbed'))
context "test:before:run:async", ->
it "can test unstubbed, real server", ->
Cypress.automation.restore()
cy.setCookie('foo', 'bar')
it "clears cookies before each test run", ->
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { domain: "localhost", name: "foo" } ])
.resolves([])
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookies",
{ domain: "localhost" }
)
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { domain: "localhost", name: "foo" } ]
)
it "does not call clear:cookies when get:cookies returns empty array", ->
Cypress.automation.withArgs("get:cookies").resolves([])
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(Cypress.automation).not.to.be.calledWith(
"clear:cookies"
)
it "does not attempt to time out", ->
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { domain: "localhost", name: "foo" } ])
.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
Cypress.emitThen("test:before:run:async", {})
.then ->
expect(timeout).not.to.be.called
context "#getCookies", ->
it "returns array of cookies", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.getCookies().should("deep.eq", []).then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookies",
{ domain: "localhost" }
)
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookies().then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookies({timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves([])
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.getCookies().then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookies")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookies"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.getCookies()` had an unexpected error reading cookies from #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.getCookies()
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("getCookies")
expect(lastLog.get("message")).to.eq("")
expect(err.message).to.eq("`cy.getCookies()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/getcookies")
done()
cy.getCookies({timeout: 50})
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([
{name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}
])
it "can turn off logging", ->
cy.getCookies({log: false}).then ->
expect(@lastLog).to.be.undefined
it "ends immediately", ->
cy.getCookies().then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.getCookies().then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.getCookies().then (cookies) ->
expect(cookies).to.deep.eq([{name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}])
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookies
expect(c["Num Cookies"]).to.eq 1
context "#getCookie", ->
it "returns single cookie by name", ->
Cypress.automation.withArgs("get:cookie").resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
cy.getCookie("foo").should("deep.eq", {
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
}).then ->
expect(Cypress.automation).to.be.calledWith(
"get:cookie",
{ domain: "localhost", name: "foo" }
)
it "returns null when no cookie was found", ->
Cypress.automation.withArgs("get:cookie").resolves(null)
cy.getCookie("foo").should("be.null")
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookie("foo").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.getCookie("foo", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves(null)
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.getCookie("foo").then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.getCookie()` had an unexpected error reading the requested cookie from #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.getCookie("foo")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("getCookie")
expect(lastLog.get("message")).to.eq("foo")
expect(err.message).to.eq("`cy.getCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/getcookie")
done()
cy.getCookie("foo", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.getCookie()` must be passed a string argument for name."
expect(lastLog.get("error").docsUrl).to.eq("https://on.cypress.io/getcookie")
expect(lastLog.get("error")).to.eq(err)
done()
cy.getCookie(123)
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "getCookie"
@lastLog = log
Cypress.automation
.withArgs("get:cookie", { domain: "localhost", name: "foo" })
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
.withArgs("get:cookie", { domain: "localhost", name: "bar" })
.resolves(null)
it "can turn off logging", ->
cy.getCookie("foo", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "has correct message", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("message")).to.eq("foo")
it "snapshots immediately", ->
cy.getCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.getCookie("foo").then (cookie) ->
expect(cookie).to.deep.eq({name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false})
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookie
it "#consoleProps when no cookie found", ->
cy.getCookie("bar").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq "null"
expect(c["Note"]).to.eq("No cookie with the name: 'bar' was found.")
context "#setCookie", ->
beforeEach ->
cy.stub(Cypress.utils, "addTwentyYears").returns(12345)
it "returns set cookie", ->
Cypress.automation.withArgs("set:cookie").resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: false, httpOnly: false, expiry: 12345
})
cy.setCookie("foo", "bar").should("deep.eq", {
name: "foo", value: "bar", domain: "localhost", path: "/", secure: false, httpOnly: false, expiry: 12345
}).then ->
expect(Cypress.automation).to.be.calledWith(
"set:cookie",
{ domain: "localhost", name: "foo", value: "bar", path: "/", secure: false, httpOnly: false, expiry: 12345, sameSite: undefined }
)
it "can change options", ->
Cypress.automation.withArgs("set:cookie").resolves({
name: "foo", value: "bar", domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987
})
cy.setCookie("foo", "bar", {domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987}).should("deep.eq", {
name: "foo", value: "bar", domain: "brian.dev.local", path: "/foo", secure: true, httpOnly: true, expiry: 987
}).then ->
expect(Cypress.automation).to.be.calledWith(
"set:cookie",
{ domain: "brian.dev.local", name: "foo", value: "bar", path: "/foo", secure: true, httpOnly: true, expiry: 987, sameSite: undefined }
)
it "does not mutate options", ->
Cypress.automation.resolves()
options = {}
cy.setCookie("foo", "bar", {}).then ->
expect(options).deep.eq({})
it "can set cookies with sameSite", ->
Cypress.automation.restore()
Cypress.utils.addTwentyYears.restore()
Cypress.sinon.stub(Cypress, 'config').callThrough()
.withArgs('experimentalGetCookiesSameSite').returns(true)
cy.setCookie('one', 'bar', { sameSite: 'none', secure: true })
cy.getCookie('one').should('include', { sameSite: 'no_restriction' })
cy.setCookie('two', 'bar', { sameSite: 'no_restriction', secure: true })
cy.getCookie('two').should('include', { sameSite: 'no_restriction' })
cy.setCookie('three', 'bar', { sameSite: 'Lax' })
cy.getCookie('three').should('include', { sameSite: 'lax' })
cy.setCookie('four', 'bar', { sameSite: 'Strict' })
cy.getCookie('four').should('include', { sameSite: 'strict' })
cy.setCookie('five', 'bar')
## @see https://bugzilla.mozilla.org/show_bug.cgi?id=1624668
if Cypress.isBrowser('firefox')
cy.getCookie('five').should('include', { sameSite: 'no_restriction' })
else
cy.getCookie('five').should('not.have.property', 'sameSite')
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.setCookie("foo", "bar").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.setCookie("foo", "bar", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves(null)
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.setCookie("foo", "bar").then ->
expect(cy.clearTimeout).to.be.calledWith("set:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "setCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.include "some err message"
expect(lastLog.get("error").name).to.eq "CypressError"
expect(lastLog.get("error").stack).to.include error.stack
done()
cy.setCookie("foo", "bar")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("setCookie")
expect(lastLog.get("message")).to.eq("foo, bar")
expect(err.message).to.include("`cy.setCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/setcookie")
done()
cy.setCookie("foo", "bar", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.setCookie()` must be passed two string arguments for `name` and `value`."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie(123)
it "requires a string value", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.setCookie()` must be passed two string arguments for `name` and `value`."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie("foo", 123)
it "when an invalid samesite prop is supplied", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq """
If a `sameSite` value is supplied to `cy.setCookie()`, it must be a string from the following list:
> no_restriction, lax, strict
You passed:
> bad
"""
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie('foo', 'bar', { sameSite: 'bad' })
it "when samesite=none is supplied and secure is not set", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq """
Only cookies with the `secure` flag set to `true` can use `sameSite: 'None'`.
Pass `secure: true` to `cy.setCookie()` to set a cookie with `sameSite: 'None'`.
"""
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/setcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.setCookie('foo', 'bar', { sameSite: 'None' })
context "when setting an invalid cookie", ->
it "throws an error if the backend responds with an error", (done) ->
err = new Error("backend could not set cookie")
Cypress.automation.withArgs("set:cookie").rejects(err)
cy.on "fail", (err) =>
expect(Cypress.automation.withArgs("set:cookie")).to.be.calledOnce
expect(err.message).to.contain('unexpected error setting the requested cookie')
expect(err.message).to.contain(err.message)
done()
## browser backend should yell since this is invalid
cy.setCookie("foo", " bar")
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "setCookie"
@lastLog = log
Cypress.automation
.withArgs("set:cookie", {
domain: "localhost", name: "foo", value: "bar", path: "/", secure: false, httpOnly: false, expiry: 12345, sameSite: undefined
})
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
it "can turn off logging", ->
cy.setCookie("foo", "bar", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.setCookie("foo", "bar").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.setCookie("foo", "bar").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.setCookie("foo", "bar").then (cookie) ->
expect(cookie).to.deep.eq({name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false})
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.deep.eq cookie
context "#clearCookie", ->
it "returns null", ->
Cypress.automation.withArgs("clear:cookie").resolves(null)
cy.clearCookie("foo").should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookie",
{ domain: "localhost", name: "foo" }
)
describe "timeout", ->
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookie("foo").then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves(null)
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookie("foo", {timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
Cypress.automation.resolves([])
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.clearCookie("foo").then ->
expect(cy.clearTimeout).to.be.calledWith("clear:cookie")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookie"
@lastLog = log
@logs.push(log)
return null
it "logs once on error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookie()` had an unexpected error clearing the requested cookie in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
done()
cy.clearCookie("foo")
it "throws after timing out", (done) ->
Cypress.automation.resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("clearCookie")
expect(lastLog.get("message")).to.eq("foo")
expect(err.message).to.eq("`cy.clearCookie()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/clearcookie")
done()
cy.clearCookie("foo", {timeout: 50})
it "requires a string name", (done) ->
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.eq "`cy.clearCookie()` must be passed a string argument for name."
expect(lastLog.get("error").docsUrl).to.eq "https://on.cypress.io/clearcookie"
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookie(123)
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookie"
@lastLog = log
Cypress.automation
.withArgs("clear:cookie", { domain: "localhost", name: "foo" })
.resolves({
name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false
})
.withArgs("clear:cookie", { domain: "localhost", name: "bar" })
.resolves(null)
it "can turn off logging", ->
cy.clearCookie("foo", {log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.clearCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.clearCookie("foo").then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.clearCookie("foo").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookie"]).to.deep.eq {name: "foo", value: "bar", domain: "localhost", path: "/", secure: true, httpOnly: false}
it "#consoleProps when no matching cookie was found", ->
cy.clearCookie("bar").then (cookie) ->
expect(cookie).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookie"]).to.be.undefined
expect(c["Note"]).to.eq "No cookie with the name: 'bar' was found or removed."
context "#clearCookies", ->
it "returns null", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.clearCookies().should("be.null")
it "does not call 'clear:cookies' when no cookies were returned", ->
Cypress.automation.withArgs("get:cookies").resolves([])
cy.clearCookies().then ->
expect(Cypress.automation).not.to.be.calledWith(
"clear:cookies"
)
it "calls 'clear:cookies' only with clearableCookies", ->
Cypress.automation
.withArgs("get:cookies")
.resolves([
{ name: "foo" },
{ name: "bar" }
])
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
])
.resolves({
name: "foo"
})
cy.stub(Cypress.Cookies, "getClearableCookies")
.withArgs([{name: "foo"}, {name: "bar"}])
.returns([{name: "foo"}])
cy.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { name: "foo", domain: "localhost" } ]
)
it "calls 'clear:cookies' with all cookies", ->
Cypress.Cookies.preserveOnce("bar", "baz")
Cypress.automation
.withArgs("get:cookies")
.resolves([
{ name: "foo" },
{ name: "bar" }
{ name: "baz" }
])
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
])
.resolves({
name: "PI:NAME:<NAME>END_PI"
})
.withArgs("clear:cookies", [
{ name: "foo", domain: "localhost" }
{ name: "bar", domain: "localhost" }
{ name: "baz", domain: "localhost" }
])
.resolves({
name: "PI:NAME:<NAME>END_PI"
})
cy
.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies",
[ { name: "foo", domain: "localhost" } ]
)
.clearCookies().should("be.null").then ->
expect(Cypress.automation).to.be.calledWith(
"clear:cookies", [
{ name: "foo", domain: "localhost" }
{ name: "bar", domain: "localhost" }
{ name: "baz", domain: "localhost" }
]
)
describe "timeout", ->
beforeEach ->
Cypress.automation
.withArgs("get:cookies")
.resolves([{}])
.withArgs("clear:cookies")
.resolves({})
it "sets timeout to Cypress.config(responseTimeout)", ->
Cypress.config("responseTimeout", 2500)
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookies().then ->
expect(timeout).to.be.calledWith(2500)
it "can override timeout", ->
Cypress.automation.resolves([])
timeout = cy.spy(Promise.prototype, "timeout")
cy.clearCookies({timeout: 1000}).then ->
expect(timeout).to.be.calledWith(1000)
it "clears the current timeout and restores after success", ->
cy.timeout(100)
cy.spy(cy, "clearTimeout")
cy.clearCookies().then ->
expect(cy.clearTimeout).to.be.calledWith("get:cookies")
expect(cy.clearTimeout).to.be.calledWith("clear:cookies")
## restores the timeout afterwards
expect(cy.timeout()).to.eq(100)
describe "errors", ->
beforeEach ->
Cypress.config("defaultCommandTimeout", 50)
@logs = []
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
@logs.push(log)
return null
it "logs once on 'get:cookies' error", (done) ->
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookies()` had an unexpected error clearing cookies in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookies()
it "throws after timing out", (done) ->
Cypress.automation.resolves([{ name: "foo" }])
Cypress.automation.withArgs("clear:cookies").resolves(Promise.delay(1000))
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error")).to.eq(err)
expect(lastLog.get("state")).to.eq("failed")
expect(lastLog.get("name")).to.eq("clearCookies")
expect(lastLog.get("message")).to.eq("")
expect(err.message).to.eq("`cy.clearCookies()` timed out waiting `50ms` to complete.")
expect(err.docsUrl).to.eq("https://on.cypress.io/clearcookies")
done()
cy.clearCookies({timeout: 50})
it "logs once on 'clear:cookies' error", (done) ->
Cypress.automation.withArgs("get:cookies").resolves([
{name: "foo"}, {name: "bar"}
])
error = new Error("some err message")
error.name = "foo"
error.stack = "stack"
Cypress.automation.withArgs("clear:cookies").rejects(error)
cy.on "fail", (err) =>
lastLog = @lastLog
expect(@logs.length).to.eq(1)
expect(lastLog.get("error").message).to.contain "`cy.clearCookies()` had an unexpected error clearing cookies in #{Cypress.browser.displayName}."
expect(lastLog.get("error").message).to.contain "some err message"
expect(lastLog.get("error").message).to.contain error.stack
expect(lastLog.get("error")).to.eq(err)
done()
cy.clearCookies()
describe ".log", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { name: "foo", domain: "localhost" } ])
.resolves([
{ name: "foo" }
])
it "can turn off logging", ->
cy.clearCookies({log: false}).then ->
expect(@log).to.be.undefined
it "ends immediately", ->
cy.clearCookies().then ->
lastLog = @lastLog
expect(lastLog.get("ended")).to.be.true
expect(lastLog.get("state")).to.eq("passed")
it "snapshots immediately", ->
cy.clearCookies().then ->
lastLog = @lastLog
expect(lastLog.get("snapshots").length).to.eq(1)
expect(lastLog.get("snapshots")[0]).to.be.an("object")
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.deep.eq [{name: "foo"}]
expect(c["Num Cookies"]).to.eq 1
describe ".log with no cookies returned", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([])
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.be.undefined
expect(c["Note"]).to.eq "No cookies were found or removed."
describe ".log when no cookies were cleared", ->
beforeEach ->
cy.on "log:added", (attrs, log) =>
if attrs.name is "clearCookies"
@lastLog = log
Cypress.automation
.withArgs("get:cookies", { domain: "localhost" })
.resolves([ { name: "foo" } ])
.withArgs("clear:cookies", [ { name: "foo", domain: "localhost" } ])
.resolves([])
it "#consoleProps", ->
cy.clearCookies().then (cookies) ->
expect(cookies).to.be.null
c = @lastLog.invoke("consoleProps")
expect(c["Yielded"]).to.eq("null")
expect(c["Cleared Cookies"]).to.be.undefined
expect(c["Note"]).to.eq "No cookies were found or removed."
|
[
{
"context": " assign_to: this\n default:\n name: @name\n password: @password\n queue: []\n ",
"end": 709,
"score": 0.7901337146759033,
"start": 704,
"tag": "USERNAME",
"value": "@name"
},
{
"context": " default:\n name: @name\n passw... | src/server/channel.coffee | 2called-chaos/synctube_node | 0 | PersistedStorage = require("./persisted_storage.js").Class
PlaylistManager = require("./playlist_manager.js").Class
COLORS = require("./colors.js")
UTIL = require("./util.js")
exports.Class = class SyncTubeServerChannel
debug: (a...) -> @server.debug("[#{@name}]", a...)
info: (a...) -> @server.info("[#{@name}]", a...)
warn: (a...) -> @server.warn("[#{@name}]", a...)
error: (a...) -> @server.error("[#{@name}]", a...)
constructor: (@server, @name, @password) ->
@control = []
@host = 0
@subscribers = []
@ready = false
@ready_timeout = null
@persisted = new PersistedStorage @server, "channel/#{UTIL.sha1(@name)}",
assign_to: this
default:
name: @name
password: @password
queue: []
playlists: {}
playlistActiveSet: "default"
desired: false
options:
defaultCtype: @server.opts.defaultCtype
defaultUrl: @server.opts.defaultUrl
defaultAutoplay: @server.opts.defaultAutoplay
maxDrift: @server.opts.maxDrift
packetInterval: @server.opts.packetInterval
readyGracePeriod: 2000
chatMode: "public" # public, admin-only, disabled
playlistMode: "full" # full, disabled
@persisted.beforeSave (ps, store) =>
# reset playlist index because it makes everything easier
#v.index = -1 for k, v of store.playlists
# delete playlist maps
delete v["map"] for k, v of store.playlists
# delete volatile playlists
for k, v of store.playlists
unless v.persisted
wasActive = k == store.playlistActiveSet
@debug "removing volatile playlist #{k}#{if wasActive then " (was active, switching to default)" else ""}"
delete store.playlists[k]
@playlistActiveSet = @persisted.set("playlistActiveSet", "default") if wasActive
@setDefaultDesired() unless @desired
@playlistManager = new PlaylistManager(this, @playlists)
@playlistManager.rebuildMaps()
@playlistManager.onListChange (set) => @playlistActiveSet = @persisted.set("playlistActiveSet", set)
@playlistManager.load(@playlistActiveSet)
@init()
init: -> # plugin hook
getRPCKey: ->
kbase = "#{@name}:"
kbase += "#{@password}" if @password?
UTIL.sha1(kbase)
defaultDesired: ->
{
ctype: @options.defaultCtype
url: @options.defaultUrl
seek: 0
loop: false
seek_update: new Date
state: if @options.defaultAutoplay then "play" else "pause"
}
setDefaultDesired: (broadcast = true) ->
@persisted.set("desired", @defaultDesired())
@broadcastCode(false, "desired", @desired)
broadcast: (client, message, color, client_color, sendToAuthor = true) ->
for c in @subscribers
continue if c == client && !sendToAuthor
c.sendMessage(message, color, client.name, client_color || client?.color)
broadcastChat: (client, message, color, client_color, sendToAuthor = true) ->
if @options.chatMode == "disabled" || (@options.chatMode == "admin-only" && @control.indexOf(client) == -1)
return client.sendSystemMessage("chat is #{@options.chatMode}!", COLORS.muted)
@broadcast(client, message, color, client_color, sendToAuthor)
broadcastCode: (client, type, data, sendToAuthor = true) ->
for c in @subscribers
continue if c == client && !sendToAuthor
c.sendCode(type, data)
sendSettings: (client) ->
clients = if client then [client] else @subscribers
for sub in clients
sub.sendCode "server_settings", packetInterval: @options.packetInterval, maxDrift: @options.maxDrift
updateSubscriberList: (client) ->
@broadcastCode(client, "subscriber_list", channel: @name, subscribers: @getSubscriberList(client))
getSubscriberList: (client) ->
list = []
list.push(@getSubscriberData(client, c, i)) for c, i in @subscribers
list
getSubscriberData: (client, sub, index) ->
data =
index: sub.index
name: sub.name || sub.old_name
control: @control.indexOf(sub) > -1
isHost: @control[@host] == sub
isyou: client == sub
drift: 0
state: sub.state || {}
# calculcate drift
leader = @control[0]
if sub.state?.seek && leader?.state?.seek?
seekdiff = leader?.state?.seek - sub.state.seek
seekdiff -= (leader.lastPacket - sub.lastPacket) / 1000 if leader.lastPacket && sub.lastPacket && leader?.state?.state == "playing"
data.drift = seekdiff.toFixed(3)
data.drift = 0 if data.drift == "0.000"
data.progress = data.state.state || "uninitialized"
switch data.state?.state
when "unstarted" then data.icon = "cog"; data.icon_class = "text-muted"
when "ended" then data.icon = "stop"; data.icon_class = "text-danger"
when "playing" then data.icon = "play"; data.icon_class = "text-success"
when "paused" then data.icon = "pause"; data.icon_class = "text-warning"
when "buffering" then data.icon = "spinner"; data.icon_class = "text-warning"
when "cued" then data.icon = "eject"; data.icon_class = "text-muted"
when "ready" then data.icon = "check-square-o"; data.icon_class = "text-muted"
else data.icon = "cog"; data.icon_class = "text-danger"
data
live: (ctype, url) ->
@persisted.set("desired", { ctype: ctype, url: url, state: "pause", seek: 0, loop: false, seek_update: new Date})
@ready = []
@broadcastCode(false, "desired", Object.assign({}, @desired, { forceLoad: true }))
# start after grace period
@ready_timeout = UTIL.delay @options.readyGracePeriod, =>
@ready = false
@desired.state = "play"
@broadcastCode(false, "video_action", action: "resume", reason: "gracePeriod")
play: (ctype, url, playNext = false, intermission = false) ->
if intermission
@playlistManager.intermission(ctype, url)
else if playNext
@playlistManager.playNext(ctype, url)
else
@playlistManager.append(ctype, url)
pauseVideo: (client, sendMessage = true) ->
return unless @control.indexOf(client) > -1
@broadcastCode(client, "video_action", action: "pause", {}, false)
@broadcastCode(client, "video_action", action: "seek", to: client.state.seek, paused: true, false) if client.state?.seek?
playVideo: (client, sendMessage = true) ->
return unless @control.indexOf(client) > -1
@broadcastCode(client, "video_action", action: "resume", reason: "playVideo", false)
grantControl: (client, sendMessage = true) ->
return if @control.indexOf(client) > -1
@control.push(client)
client.control = this
client.sendSystemMessage("You are in control of #{@name}!", COLORS.green) if sendMessage
client.sendCode("taken_control", channel: @name)
client.sendCode("taken_host", channel: @name) if @host == @control.indexOf(client)
@updateSubscriberList(client)
@debug "granted control to client ##{client.index}(#{client.ip})"
revokeControl: (client, sendMessage = true, reason = null) ->
return if @control.indexOf(client) == -1
client.sendCode("lost_host", channel: @name) if @host == @control.indexOf(client)
client.sendCode("lost_control", channel: @name)
client.sendSystemMessage("You lost control of #{@name}#{if reason then " (#{reason})" else ""}!", COLORS.red) if sendMessage
@control.splice(@control.indexOf(client), 1)
client.control = null
@updateSubscriberList(client)
@debug "revoked control from client ##{client.index}(#{client.ip})"
subscribe: (client, sendMessage = true) ->
return if @subscribers.indexOf(client) > -1
client.subscribed?.unsubscribe?(client)
@subscribers.push(client)
client.subscribed = this
client.state = {}
client.sendSystemMessage("You joined #{@name}!", COLORS.green) if sendMessage
client.sendCode("subscribe", channel: @name)
@sendSettings(client)
@playlistManager?.cUpdateList(client)
client.sendCode("desired", Object.assign({}, @desired, { force: true }))
@broadcast(client, "<i>joined the party!</i>", COLORS.green, COLORS.muted, false)
@updateSubscriberList(client)
@debug "subscribed client ##{client.index}(#{client.ip})"
unsubscribe: (client, sendMessage = true, reason = null) ->
return if @subscribers.indexOf(client) == -1
client.control.revokeControl(client, sendMessage, reason) if client.control == this
@subscribers.splice(@subscribers.indexOf(client), 1)
client.subscribed = null
client.state = {}
client.sendSystemMessage("You left #{@name}#{if reason then " (#{reason})" else ""}!", COLORS.red) if sendMessage
client.sendCode("unsubscribe", channel: @name)
@broadcast(client, "<i>left the party :(</i>", COLORS.red, COLORS.muted, false)
@updateSubscriberList(client)
@debug "unsubscribed client ##{client.index}(#{client.ip})"
destroy: (client, reason) ->
@info "channel deleted by #{client.name}[#{client.ip}] (#{@subscribers.length} subscribers)#{if reason then ": #{reason}" else ""}"
@unsubscribe(c, true, "channel deleted#{if reason then " (#{reason})" else ""}") for c in @subscribers.slice(0).reverse()
delete @server.channels[@name]
clientColor: (client) ->
if @control[@host] == client
COLORS.red
else if @control.indexOf(client) > -1
COLORS.info
else
null
findClient: (client, who) ->
require("./client.js").Class.find(client, who, @subscribers, "channel")
| 199528 | PersistedStorage = require("./persisted_storage.js").Class
PlaylistManager = require("./playlist_manager.js").Class
COLORS = require("./colors.js")
UTIL = require("./util.js")
exports.Class = class SyncTubeServerChannel
debug: (a...) -> @server.debug("[#{@name}]", a...)
info: (a...) -> @server.info("[#{@name}]", a...)
warn: (a...) -> @server.warn("[#{@name}]", a...)
error: (a...) -> @server.error("[#{@name}]", a...)
constructor: (@server, @name, @password) ->
@control = []
@host = 0
@subscribers = []
@ready = false
@ready_timeout = null
@persisted = new PersistedStorage @server, "channel/#{UTIL.sha1(@name)}",
assign_to: this
default:
name: @name
password: <PASSWORD>
queue: []
playlists: {}
playlistActiveSet: "default"
desired: false
options:
defaultCtype: @server.opts.defaultCtype
defaultUrl: @server.opts.defaultUrl
defaultAutoplay: @server.opts.defaultAutoplay
maxDrift: @server.opts.maxDrift
packetInterval: @server.opts.packetInterval
readyGracePeriod: 2000
chatMode: "public" # public, admin-only, disabled
playlistMode: "full" # full, disabled
@persisted.beforeSave (ps, store) =>
# reset playlist index because it makes everything easier
#v.index = -1 for k, v of store.playlists
# delete playlist maps
delete v["map"] for k, v of store.playlists
# delete volatile playlists
for k, v of store.playlists
unless v.persisted
wasActive = k == store.playlistActiveSet
@debug "removing volatile playlist #{k}#{if wasActive then " (was active, switching to default)" else ""}"
delete store.playlists[k]
@playlistActiveSet = @persisted.set("playlistActiveSet", "default") if wasActive
@setDefaultDesired() unless @desired
@playlistManager = new PlaylistManager(this, @playlists)
@playlistManager.rebuildMaps()
@playlistManager.onListChange (set) => @playlistActiveSet = @persisted.set("playlistActiveSet", set)
@playlistManager.load(@playlistActiveSet)
@init()
init: -> # plugin hook
getRPCKey: ->
kbase = "#{@name}:"
kbase += "#{@password}" if @password?
UTIL.sha1(kbase)
defaultDesired: ->
{
ctype: @options.defaultCtype
url: @options.defaultUrl
seek: 0
loop: false
seek_update: new Date
state: if @options.defaultAutoplay then "play" else "pause"
}
setDefaultDesired: (broadcast = true) ->
@persisted.set("desired", @defaultDesired())
@broadcastCode(false, "desired", @desired)
broadcast: (client, message, color, client_color, sendToAuthor = true) ->
for c in @subscribers
continue if c == client && !sendToAuthor
c.sendMessage(message, color, client.name, client_color || client?.color)
broadcastChat: (client, message, color, client_color, sendToAuthor = true) ->
if @options.chatMode == "disabled" || (@options.chatMode == "admin-only" && @control.indexOf(client) == -1)
return client.sendSystemMessage("chat is #{@options.chatMode}!", COLORS.muted)
@broadcast(client, message, color, client_color, sendToAuthor)
broadcastCode: (client, type, data, sendToAuthor = true) ->
for c in @subscribers
continue if c == client && !sendToAuthor
c.sendCode(type, data)
sendSettings: (client) ->
clients = if client then [client] else @subscribers
for sub in clients
sub.sendCode "server_settings", packetInterval: @options.packetInterval, maxDrift: @options.maxDrift
updateSubscriberList: (client) ->
@broadcastCode(client, "subscriber_list", channel: @name, subscribers: @getSubscriberList(client))
getSubscriberList: (client) ->
list = []
list.push(@getSubscriberData(client, c, i)) for c, i in @subscribers
list
getSubscriberData: (client, sub, index) ->
data =
index: sub.index
name: sub.name || sub.old_name
control: @control.indexOf(sub) > -1
isHost: @control[@host] == sub
isyou: client == sub
drift: 0
state: sub.state || {}
# calculcate drift
leader = @control[0]
if sub.state?.seek && leader?.state?.seek?
seekdiff = leader?.state?.seek - sub.state.seek
seekdiff -= (leader.lastPacket - sub.lastPacket) / 1000 if leader.lastPacket && sub.lastPacket && leader?.state?.state == "playing"
data.drift = seekdiff.toFixed(3)
data.drift = 0 if data.drift == "0.000"
data.progress = data.state.state || "uninitialized"
switch data.state?.state
when "unstarted" then data.icon = "cog"; data.icon_class = "text-muted"
when "ended" then data.icon = "stop"; data.icon_class = "text-danger"
when "playing" then data.icon = "play"; data.icon_class = "text-success"
when "paused" then data.icon = "pause"; data.icon_class = "text-warning"
when "buffering" then data.icon = "spinner"; data.icon_class = "text-warning"
when "cued" then data.icon = "eject"; data.icon_class = "text-muted"
when "ready" then data.icon = "check-square-o"; data.icon_class = "text-muted"
else data.icon = "cog"; data.icon_class = "text-danger"
data
live: (ctype, url) ->
@persisted.set("desired", { ctype: ctype, url: url, state: "pause", seek: 0, loop: false, seek_update: new Date})
@ready = []
@broadcastCode(false, "desired", Object.assign({}, @desired, { forceLoad: true }))
# start after grace period
@ready_timeout = UTIL.delay @options.readyGracePeriod, =>
@ready = false
@desired.state = "play"
@broadcastCode(false, "video_action", action: "resume", reason: "gracePeriod")
play: (ctype, url, playNext = false, intermission = false) ->
if intermission
@playlistManager.intermission(ctype, url)
else if playNext
@playlistManager.playNext(ctype, url)
else
@playlistManager.append(ctype, url)
pauseVideo: (client, sendMessage = true) ->
return unless @control.indexOf(client) > -1
@broadcastCode(client, "video_action", action: "pause", {}, false)
@broadcastCode(client, "video_action", action: "seek", to: client.state.seek, paused: true, false) if client.state?.seek?
playVideo: (client, sendMessage = true) ->
return unless @control.indexOf(client) > -1
@broadcastCode(client, "video_action", action: "resume", reason: "playVideo", false)
grantControl: (client, sendMessage = true) ->
return if @control.indexOf(client) > -1
@control.push(client)
client.control = this
client.sendSystemMessage("You are in control of #{@name}!", COLORS.green) if sendMessage
client.sendCode("taken_control", channel: @name)
client.sendCode("taken_host", channel: @name) if @host == @control.indexOf(client)
@updateSubscriberList(client)
@debug "granted control to client ##{client.index}(#{client.ip})"
revokeControl: (client, sendMessage = true, reason = null) ->
return if @control.indexOf(client) == -1
client.sendCode("lost_host", channel: @name) if @host == @control.indexOf(client)
client.sendCode("lost_control", channel: @name)
client.sendSystemMessage("You lost control of #{@name}#{if reason then " (#{reason})" else ""}!", COLORS.red) if sendMessage
@control.splice(@control.indexOf(client), 1)
client.control = null
@updateSubscriberList(client)
@debug "revoked control from client ##{client.index}(#{client.ip})"
subscribe: (client, sendMessage = true) ->
return if @subscribers.indexOf(client) > -1
client.subscribed?.unsubscribe?(client)
@subscribers.push(client)
client.subscribed = this
client.state = {}
client.sendSystemMessage("You joined #{@name}!", COLORS.green) if sendMessage
client.sendCode("subscribe", channel: @name)
@sendSettings(client)
@playlistManager?.cUpdateList(client)
client.sendCode("desired", Object.assign({}, @desired, { force: true }))
@broadcast(client, "<i>joined the party!</i>", COLORS.green, COLORS.muted, false)
@updateSubscriberList(client)
@debug "subscribed client ##{client.index}(#{client.ip})"
unsubscribe: (client, sendMessage = true, reason = null) ->
return if @subscribers.indexOf(client) == -1
client.control.revokeControl(client, sendMessage, reason) if client.control == this
@subscribers.splice(@subscribers.indexOf(client), 1)
client.subscribed = null
client.state = {}
client.sendSystemMessage("You left #{@name}#{if reason then " (#{reason})" else ""}!", COLORS.red) if sendMessage
client.sendCode("unsubscribe", channel: @name)
@broadcast(client, "<i>left the party :(</i>", COLORS.red, COLORS.muted, false)
@updateSubscriberList(client)
@debug "unsubscribed client ##{client.index}(#{client.ip})"
destroy: (client, reason) ->
@info "channel deleted by #{client.name}[#{client.ip}] (#{@subscribers.length} subscribers)#{if reason then ": #{reason}" else ""}"
@unsubscribe(c, true, "channel deleted#{if reason then " (#{reason})" else ""}") for c in @subscribers.slice(0).reverse()
delete @server.channels[@name]
clientColor: (client) ->
if @control[@host] == client
COLORS.red
else if @control.indexOf(client) > -1
COLORS.info
else
null
findClient: (client, who) ->
require("./client.js").Class.find(client, who, @subscribers, "channel")
| true | PersistedStorage = require("./persisted_storage.js").Class
PlaylistManager = require("./playlist_manager.js").Class
COLORS = require("./colors.js")
UTIL = require("./util.js")
exports.Class = class SyncTubeServerChannel
debug: (a...) -> @server.debug("[#{@name}]", a...)
info: (a...) -> @server.info("[#{@name}]", a...)
warn: (a...) -> @server.warn("[#{@name}]", a...)
error: (a...) -> @server.error("[#{@name}]", a...)
constructor: (@server, @name, @password) ->
@control = []
@host = 0
@subscribers = []
@ready = false
@ready_timeout = null
@persisted = new PersistedStorage @server, "channel/#{UTIL.sha1(@name)}",
assign_to: this
default:
name: @name
password: PI:PASSWORD:<PASSWORD>END_PI
queue: []
playlists: {}
playlistActiveSet: "default"
desired: false
options:
defaultCtype: @server.opts.defaultCtype
defaultUrl: @server.opts.defaultUrl
defaultAutoplay: @server.opts.defaultAutoplay
maxDrift: @server.opts.maxDrift
packetInterval: @server.opts.packetInterval
readyGracePeriod: 2000
chatMode: "public" # public, admin-only, disabled
playlistMode: "full" # full, disabled
@persisted.beforeSave (ps, store) =>
# reset playlist index because it makes everything easier
#v.index = -1 for k, v of store.playlists
# delete playlist maps
delete v["map"] for k, v of store.playlists
# delete volatile playlists
for k, v of store.playlists
unless v.persisted
wasActive = k == store.playlistActiveSet
@debug "removing volatile playlist #{k}#{if wasActive then " (was active, switching to default)" else ""}"
delete store.playlists[k]
@playlistActiveSet = @persisted.set("playlistActiveSet", "default") if wasActive
@setDefaultDesired() unless @desired
@playlistManager = new PlaylistManager(this, @playlists)
@playlistManager.rebuildMaps()
@playlistManager.onListChange (set) => @playlistActiveSet = @persisted.set("playlistActiveSet", set)
@playlistManager.load(@playlistActiveSet)
@init()
init: -> # plugin hook
getRPCKey: ->
kbase = "#{@name}:"
kbase += "#{@password}" if @password?
UTIL.sha1(kbase)
defaultDesired: ->
{
ctype: @options.defaultCtype
url: @options.defaultUrl
seek: 0
loop: false
seek_update: new Date
state: if @options.defaultAutoplay then "play" else "pause"
}
setDefaultDesired: (broadcast = true) ->
@persisted.set("desired", @defaultDesired())
@broadcastCode(false, "desired", @desired)
broadcast: (client, message, color, client_color, sendToAuthor = true) ->
for c in @subscribers
continue if c == client && !sendToAuthor
c.sendMessage(message, color, client.name, client_color || client?.color)
broadcastChat: (client, message, color, client_color, sendToAuthor = true) ->
if @options.chatMode == "disabled" || (@options.chatMode == "admin-only" && @control.indexOf(client) == -1)
return client.sendSystemMessage("chat is #{@options.chatMode}!", COLORS.muted)
@broadcast(client, message, color, client_color, sendToAuthor)
broadcastCode: (client, type, data, sendToAuthor = true) ->
for c in @subscribers
continue if c == client && !sendToAuthor
c.sendCode(type, data)
sendSettings: (client) ->
clients = if client then [client] else @subscribers
for sub in clients
sub.sendCode "server_settings", packetInterval: @options.packetInterval, maxDrift: @options.maxDrift
updateSubscriberList: (client) ->
@broadcastCode(client, "subscriber_list", channel: @name, subscribers: @getSubscriberList(client))
getSubscriberList: (client) ->
list = []
list.push(@getSubscriberData(client, c, i)) for c, i in @subscribers
list
getSubscriberData: (client, sub, index) ->
data =
index: sub.index
name: sub.name || sub.old_name
control: @control.indexOf(sub) > -1
isHost: @control[@host] == sub
isyou: client == sub
drift: 0
state: sub.state || {}
# calculcate drift
leader = @control[0]
if sub.state?.seek && leader?.state?.seek?
seekdiff = leader?.state?.seek - sub.state.seek
seekdiff -= (leader.lastPacket - sub.lastPacket) / 1000 if leader.lastPacket && sub.lastPacket && leader?.state?.state == "playing"
data.drift = seekdiff.toFixed(3)
data.drift = 0 if data.drift == "0.000"
data.progress = data.state.state || "uninitialized"
switch data.state?.state
when "unstarted" then data.icon = "cog"; data.icon_class = "text-muted"
when "ended" then data.icon = "stop"; data.icon_class = "text-danger"
when "playing" then data.icon = "play"; data.icon_class = "text-success"
when "paused" then data.icon = "pause"; data.icon_class = "text-warning"
when "buffering" then data.icon = "spinner"; data.icon_class = "text-warning"
when "cued" then data.icon = "eject"; data.icon_class = "text-muted"
when "ready" then data.icon = "check-square-o"; data.icon_class = "text-muted"
else data.icon = "cog"; data.icon_class = "text-danger"
data
live: (ctype, url) ->
@persisted.set("desired", { ctype: ctype, url: url, state: "pause", seek: 0, loop: false, seek_update: new Date})
@ready = []
@broadcastCode(false, "desired", Object.assign({}, @desired, { forceLoad: true }))
# start after grace period
@ready_timeout = UTIL.delay @options.readyGracePeriod, =>
@ready = false
@desired.state = "play"
@broadcastCode(false, "video_action", action: "resume", reason: "gracePeriod")
play: (ctype, url, playNext = false, intermission = false) ->
if intermission
@playlistManager.intermission(ctype, url)
else if playNext
@playlistManager.playNext(ctype, url)
else
@playlistManager.append(ctype, url)
pauseVideo: (client, sendMessage = true) ->
return unless @control.indexOf(client) > -1
@broadcastCode(client, "video_action", action: "pause", {}, false)
@broadcastCode(client, "video_action", action: "seek", to: client.state.seek, paused: true, false) if client.state?.seek?
playVideo: (client, sendMessage = true) ->
return unless @control.indexOf(client) > -1
@broadcastCode(client, "video_action", action: "resume", reason: "playVideo", false)
grantControl: (client, sendMessage = true) ->
return if @control.indexOf(client) > -1
@control.push(client)
client.control = this
client.sendSystemMessage("You are in control of #{@name}!", COLORS.green) if sendMessage
client.sendCode("taken_control", channel: @name)
client.sendCode("taken_host", channel: @name) if @host == @control.indexOf(client)
@updateSubscriberList(client)
@debug "granted control to client ##{client.index}(#{client.ip})"
revokeControl: (client, sendMessage = true, reason = null) ->
return if @control.indexOf(client) == -1
client.sendCode("lost_host", channel: @name) if @host == @control.indexOf(client)
client.sendCode("lost_control", channel: @name)
client.sendSystemMessage("You lost control of #{@name}#{if reason then " (#{reason})" else ""}!", COLORS.red) if sendMessage
@control.splice(@control.indexOf(client), 1)
client.control = null
@updateSubscriberList(client)
@debug "revoked control from client ##{client.index}(#{client.ip})"
subscribe: (client, sendMessage = true) ->
return if @subscribers.indexOf(client) > -1
client.subscribed?.unsubscribe?(client)
@subscribers.push(client)
client.subscribed = this
client.state = {}
client.sendSystemMessage("You joined #{@name}!", COLORS.green) if sendMessage
client.sendCode("subscribe", channel: @name)
@sendSettings(client)
@playlistManager?.cUpdateList(client)
client.sendCode("desired", Object.assign({}, @desired, { force: true }))
@broadcast(client, "<i>joined the party!</i>", COLORS.green, COLORS.muted, false)
@updateSubscriberList(client)
@debug "subscribed client ##{client.index}(#{client.ip})"
unsubscribe: (client, sendMessage = true, reason = null) ->
return if @subscribers.indexOf(client) == -1
client.control.revokeControl(client, sendMessage, reason) if client.control == this
@subscribers.splice(@subscribers.indexOf(client), 1)
client.subscribed = null
client.state = {}
client.sendSystemMessage("You left #{@name}#{if reason then " (#{reason})" else ""}!", COLORS.red) if sendMessage
client.sendCode("unsubscribe", channel: @name)
@broadcast(client, "<i>left the party :(</i>", COLORS.red, COLORS.muted, false)
@updateSubscriberList(client)
@debug "unsubscribed client ##{client.index}(#{client.ip})"
destroy: (client, reason) ->
@info "channel deleted by #{client.name}[#{client.ip}] (#{@subscribers.length} subscribers)#{if reason then ": #{reason}" else ""}"
@unsubscribe(c, true, "channel deleted#{if reason then " (#{reason})" else ""}") for c in @subscribers.slice(0).reverse()
delete @server.channels[@name]
clientColor: (client) ->
if @control[@host] == client
COLORS.red
else if @control.indexOf(client) > -1
COLORS.info
else
null
findClient: (client, who) ->
require("./client.js").Class.find(client, who, @subscribers, "channel")
|
[
{
"context": ": 'postapp.com:8080',\n key: 'an invalid key', secret: 'a-test-secret' })\n request.post @",
"end": 8388,
"score": 0.8512929677963257,
"start": 8385,
"tag": "KEY",
"value": "key"
},
{
"context": "80',\n key: 'an invalid key', secret: 'a-test-s... | test/apps_controller_test.coffee | jjzhang166/w3gram-server | 0 | request = require 'request'
sinon = require 'sinon'
describe 'HTTP server', ->
before (done) ->
@server = w3gram_test_config.server()
@appCache = w3gram_test_config.appCache()
@appList = w3gram_test_config.appList()
@appList.teardown (error) =>
if error
console.error error
process.exit 1
@server.listen =>
@httpRoot = @server.httpUrl()
done()
after (done) ->
@server.close done
beforeEach (done) ->
@sandbox = sinon.sandbox.create()
@appCache.reset()
@appList.setup (error) ->
if error
console.error error
process.exit 1
done()
afterEach (done) ->
@sandbox.restore()
@appCache.reset()
@appList.teardown (error) ->
if error
console.error error
process.exit 1
done()
describe 'GET /mak', ->
it 'returns the MAK if there are no apps', (done) ->
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 200
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
w3gram_test_config.appList().getMak (error, mak) =>
expect(error).not.to.be.ok
expect(json.mak).to.equal mak
done()
it '403s if there are registered apps', (done) ->
@appList.create name: 'mak-403-test', (error, app) =>
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '500s on AppCache#hasApps errors', (done) ->
@sandbox.stub(@appCache, 'hasApps').callsArgWith 0, new Error()
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
it '500s on AppCache#getMak errors', (done) ->
@sandbox.stub(@appCache, 'getMak').callsArgWith 0, new Error()
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
describe 'OPTIONS /apps', ->
it 'returns a CORS-compliant response', (done) ->
requestOptions =
url: "#{@httpRoot}/apps"
method: 'OPTIONS'
headers:
origin: 'https://example.push.consumer.com'
request requestOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 204
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['access-control-allow-methods']).to.equal(
'POST')
expect(response.headers['access-control-max-age']).to.equal(
'31536000')
done()
describe 'POST /apps', ->
beforeEach (done) ->
@appCache.getMak (error, mak) =>
expect(error).to.equal null
@mak = mak
@postOptions =
url: "#{@httpRoot}/apps",
headers:
'content-type': 'application/json; charset=utf-8'
body: JSON.stringify(
mak: @mak
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
done()
it 'creates an app if all params match', (done) ->
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 201
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.name).to.equal 'Post App Name'
expect(json.origin).to.equal 'postapp.com:8080'
expect(json.key).to.be.a 'string'
expect(json.key.length).to.be.at.least 16
expect(json.secret).to.be.a 'string'
expect(json.secret.length).to.be.at.least 32
done()
it 'uses the key and secret in params when provided', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'a-test-key', secret: 'a-test-secret' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 201
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.name).to.equal 'Post App Name'
expect(json.origin).to.equal 'postapp.com:8080'
expect(json.key).to.equal 'a-test-key'
expect(json.secret).to.equal 'a-test-secret'
done()
it '403s if mak is missing', (done) ->
@postOptions.body = JSON.stringify(
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '403s if mak is wrong', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak + '-but-wrong'
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '400s if app is missing', (done) ->
@postOptions.body = JSON.stringify mak: @mak
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.name is missing', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak
app: { origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.origin is missing', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak
app: { name: 'Post App Name' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.key is invalid', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'an invalid key', secret: 'a-test-secret' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Invalid app key'
done()
it '400s if app.secret is invalid', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'a-test-key', secret: 'an invalid secret' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Invalid app secret'
done()
it '500s on AppCache#getMak errors', (done) ->
@sandbox.stub(@appCache, 'getMak').callsArgWith 0, new Error()
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
it '500s on AppList#create errors', (done) ->
@sandbox.stub(@appList, 'create').callsArgWith 1, new Error()
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
| 158270 | request = require 'request'
sinon = require 'sinon'
describe 'HTTP server', ->
before (done) ->
@server = w3gram_test_config.server()
@appCache = w3gram_test_config.appCache()
@appList = w3gram_test_config.appList()
@appList.teardown (error) =>
if error
console.error error
process.exit 1
@server.listen =>
@httpRoot = @server.httpUrl()
done()
after (done) ->
@server.close done
beforeEach (done) ->
@sandbox = sinon.sandbox.create()
@appCache.reset()
@appList.setup (error) ->
if error
console.error error
process.exit 1
done()
afterEach (done) ->
@sandbox.restore()
@appCache.reset()
@appList.teardown (error) ->
if error
console.error error
process.exit 1
done()
describe 'GET /mak', ->
it 'returns the MAK if there are no apps', (done) ->
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 200
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
w3gram_test_config.appList().getMak (error, mak) =>
expect(error).not.to.be.ok
expect(json.mak).to.equal mak
done()
it '403s if there are registered apps', (done) ->
@appList.create name: 'mak-403-test', (error, app) =>
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '500s on AppCache#hasApps errors', (done) ->
@sandbox.stub(@appCache, 'hasApps').callsArgWith 0, new Error()
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
it '500s on AppCache#getMak errors', (done) ->
@sandbox.stub(@appCache, 'getMak').callsArgWith 0, new Error()
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
describe 'OPTIONS /apps', ->
it 'returns a CORS-compliant response', (done) ->
requestOptions =
url: "#{@httpRoot}/apps"
method: 'OPTIONS'
headers:
origin: 'https://example.push.consumer.com'
request requestOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 204
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['access-control-allow-methods']).to.equal(
'POST')
expect(response.headers['access-control-max-age']).to.equal(
'31536000')
done()
describe 'POST /apps', ->
beforeEach (done) ->
@appCache.getMak (error, mak) =>
expect(error).to.equal null
@mak = mak
@postOptions =
url: "#{@httpRoot}/apps",
headers:
'content-type': 'application/json; charset=utf-8'
body: JSON.stringify(
mak: @mak
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
done()
it 'creates an app if all params match', (done) ->
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 201
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.name).to.equal 'Post App Name'
expect(json.origin).to.equal 'postapp.com:8080'
expect(json.key).to.be.a 'string'
expect(json.key.length).to.be.at.least 16
expect(json.secret).to.be.a 'string'
expect(json.secret.length).to.be.at.least 32
done()
it 'uses the key and secret in params when provided', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'a-test-key', secret: 'a-test-secret' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 201
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.name).to.equal 'Post App Name'
expect(json.origin).to.equal 'postapp.com:8080'
expect(json.key).to.equal 'a-test-key'
expect(json.secret).to.equal 'a-test-secret'
done()
it '403s if mak is missing', (done) ->
@postOptions.body = JSON.stringify(
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '403s if mak is wrong', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak + '-but-wrong'
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '400s if app is missing', (done) ->
@postOptions.body = JSON.stringify mak: @mak
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.name is missing', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak
app: { origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.origin is missing', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak
app: { name: 'Post App Name' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.key is invalid', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'an invalid <KEY>', secret: 'a-<KEY>' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Invalid app key'
done()
it '400s if app.secret is invalid', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'a-<KEY>key', secret: '<KEY>' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Invalid app secret'
done()
it '500s on AppCache#getMak errors', (done) ->
@sandbox.stub(@appCache, 'getMak').callsArgWith 0, new Error()
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
it '500s on AppList#create errors', (done) ->
@sandbox.stub(@appList, 'create').callsArgWith 1, new Error()
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
| true | request = require 'request'
sinon = require 'sinon'
describe 'HTTP server', ->
before (done) ->
@server = w3gram_test_config.server()
@appCache = w3gram_test_config.appCache()
@appList = w3gram_test_config.appList()
@appList.teardown (error) =>
if error
console.error error
process.exit 1
@server.listen =>
@httpRoot = @server.httpUrl()
done()
after (done) ->
@server.close done
beforeEach (done) ->
@sandbox = sinon.sandbox.create()
@appCache.reset()
@appList.setup (error) ->
if error
console.error error
process.exit 1
done()
afterEach (done) ->
@sandbox.restore()
@appCache.reset()
@appList.teardown (error) ->
if error
console.error error
process.exit 1
done()
describe 'GET /mak', ->
it 'returns the MAK if there are no apps', (done) ->
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 200
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
w3gram_test_config.appList().getMak (error, mak) =>
expect(error).not.to.be.ok
expect(json.mak).to.equal mak
done()
it '403s if there are registered apps', (done) ->
@appList.create name: 'mak-403-test', (error, app) =>
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '500s on AppCache#hasApps errors', (done) ->
@sandbox.stub(@appCache, 'hasApps').callsArgWith 0, new Error()
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
it '500s on AppCache#getMak errors', (done) ->
@sandbox.stub(@appCache, 'getMak').callsArgWith 0, new Error()
request.get "#{@httpRoot}/mak", (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
describe 'OPTIONS /apps', ->
it 'returns a CORS-compliant response', (done) ->
requestOptions =
url: "#{@httpRoot}/apps"
method: 'OPTIONS'
headers:
origin: 'https://example.push.consumer.com'
request requestOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 204
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['access-control-allow-methods']).to.equal(
'POST')
expect(response.headers['access-control-max-age']).to.equal(
'31536000')
done()
describe 'POST /apps', ->
beforeEach (done) ->
@appCache.getMak (error, mak) =>
expect(error).to.equal null
@mak = mak
@postOptions =
url: "#{@httpRoot}/apps",
headers:
'content-type': 'application/json; charset=utf-8'
body: JSON.stringify(
mak: @mak
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
done()
it 'creates an app if all params match', (done) ->
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 201
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.name).to.equal 'Post App Name'
expect(json.origin).to.equal 'postapp.com:8080'
expect(json.key).to.be.a 'string'
expect(json.key.length).to.be.at.least 16
expect(json.secret).to.be.a 'string'
expect(json.secret.length).to.be.at.least 32
done()
it 'uses the key and secret in params when provided', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'a-test-key', secret: 'a-test-secret' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 201
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.name).to.equal 'Post App Name'
expect(json.origin).to.equal 'postapp.com:8080'
expect(json.key).to.equal 'a-test-key'
expect(json.secret).to.equal 'a-test-secret'
done()
it '403s if mak is missing', (done) ->
@postOptions.body = JSON.stringify(
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '403s if mak is wrong', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak + '-but-wrong'
app: { name: 'Post App Name', origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 403
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(body).to.equal ''
done()
it '400s if app is missing', (done) ->
@postOptions.body = JSON.stringify mak: @mak
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.name is missing', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak
app: { origin: 'postapp.com:8080' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.origin is missing', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak
app: { name: 'Post App Name' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Missing app property'
done()
it '400s if app.key is invalid', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'an invalid PI:KEY:<KEY>END_PI', secret: 'a-PI:KEY:<KEY>END_PI' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Invalid app key'
done()
it '400s if app.secret is invalid', (done) ->
@postOptions.body = JSON.stringify(
mak: @mak,
app: {
name: 'Post App Name', origin: 'postapp.com:8080',
key: 'a-PI:KEY:<KEY>END_PIkey', secret: 'PI:KEY:<KEY>END_PI' })
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 400
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Invalid app secret'
done()
it '500s on AppCache#getMak errors', (done) ->
@sandbox.stub(@appCache, 'getMak').callsArgWith 0, new Error()
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
it '500s on AppList#create errors', (done) ->
@sandbox.stub(@appList, 'create').callsArgWith 1, new Error()
request.post @postOptions, (error, response, body) =>
expect(error).not.to.be.ok
expect(response.statusCode).to.equal 500
expect(response.headers['access-control-allow-origin']).to.equal '*'
expect(response.headers['content-type']).to.equal(
'application/json; charset=utf-8')
json = JSON.parse body
expect(json.error).to.equal 'Database error'
done()
|
[
{
"context": "# Description\n# watson\n#\n# Commands:\n# watson - returns answer of quest",
"end": 23,
"score": 0.7055359482765198,
"start": 17,
"tag": "NAME",
"value": "watson"
}
] | scripts/watsonqa.coffee | blackaplysia/travelqabot | 0 | # Description
# watson
#
# Commands:
# watson - returns answer of question
url = require 'url'
https = require 'https'
shortid= require 'shortid'
redis_client = require './redis_client'
bmconf = require './bmconf'
module.exports = (robot) ->
robot.respond /.*/, (msg) ->
question = msg.message.text.replace /^travelqabot\s*/, ''
query = url.parse "#{bmconf.qa.url}/v1/question/travel"
options =
host: query.hostname
port: query.port
path: query.pathname
method: 'POST'
headers:
'Content-Type': 'application/json'
'Accept': 'application/json'
'X-synctimeout': '30'
'Authorization': bmconf.qa.auth
watson_req = https.request options, (result) ->
result.setEncoding 'utf-8'
response_string = ''
result.on 'data', (chunk) ->
response_string += chunk
result.on 'end', () ->
id = shortid.generate()
redis_client.set id, response_string
uri_h = process.env.TRAVELQABOT_URI_SERVER ? "http://localhost:3000"
uri_d = process.env.TRAVELQABOT_URI_DIR ? "/d"
link = "#{uri_h}#{uri_d}/#{id}"
response_length = process.env.TRAVELQABOT_RESPONSE_LENGTH ? "90"
watson_answer = JSON.parse(response_string)[0]
if watson_answer?
q = watson_answer.question;
if q
if q.evidencelist?.length? > 0
msg.send "#{q.evidencelist[0].text.substring(0, response_length)} #{link}"
else if q.errorNotifications? > 0
msg.send "Error: #{q.errornotifications[0].text}"
else
msg.send 'Error: No evidences or errors specified by Watson'
else
msg.send 'Error: No contents generated by Watson'
watson_req.on 'error', (err) ->
msg.send "Ooops, #{err}"
questionData =
'question':
'evidenceRequest':
'items': 1
'questionText': question
watson_req.write JSON.stringify(questionData)
watson_req.end()
| 89420 | # Description
# <NAME>
#
# Commands:
# watson - returns answer of question
url = require 'url'
https = require 'https'
shortid= require 'shortid'
redis_client = require './redis_client'
bmconf = require './bmconf'
module.exports = (robot) ->
robot.respond /.*/, (msg) ->
question = msg.message.text.replace /^travelqabot\s*/, ''
query = url.parse "#{bmconf.qa.url}/v1/question/travel"
options =
host: query.hostname
port: query.port
path: query.pathname
method: 'POST'
headers:
'Content-Type': 'application/json'
'Accept': 'application/json'
'X-synctimeout': '30'
'Authorization': bmconf.qa.auth
watson_req = https.request options, (result) ->
result.setEncoding 'utf-8'
response_string = ''
result.on 'data', (chunk) ->
response_string += chunk
result.on 'end', () ->
id = shortid.generate()
redis_client.set id, response_string
uri_h = process.env.TRAVELQABOT_URI_SERVER ? "http://localhost:3000"
uri_d = process.env.TRAVELQABOT_URI_DIR ? "/d"
link = "#{uri_h}#{uri_d}/#{id}"
response_length = process.env.TRAVELQABOT_RESPONSE_LENGTH ? "90"
watson_answer = JSON.parse(response_string)[0]
if watson_answer?
q = watson_answer.question;
if q
if q.evidencelist?.length? > 0
msg.send "#{q.evidencelist[0].text.substring(0, response_length)} #{link}"
else if q.errorNotifications? > 0
msg.send "Error: #{q.errornotifications[0].text}"
else
msg.send 'Error: No evidences or errors specified by Watson'
else
msg.send 'Error: No contents generated by Watson'
watson_req.on 'error', (err) ->
msg.send "Ooops, #{err}"
questionData =
'question':
'evidenceRequest':
'items': 1
'questionText': question
watson_req.write JSON.stringify(questionData)
watson_req.end()
| true | # Description
# PI:NAME:<NAME>END_PI
#
# Commands:
# watson - returns answer of question
url = require 'url'
https = require 'https'
shortid= require 'shortid'
redis_client = require './redis_client'
bmconf = require './bmconf'
module.exports = (robot) ->
robot.respond /.*/, (msg) ->
question = msg.message.text.replace /^travelqabot\s*/, ''
query = url.parse "#{bmconf.qa.url}/v1/question/travel"
options =
host: query.hostname
port: query.port
path: query.pathname
method: 'POST'
headers:
'Content-Type': 'application/json'
'Accept': 'application/json'
'X-synctimeout': '30'
'Authorization': bmconf.qa.auth
watson_req = https.request options, (result) ->
result.setEncoding 'utf-8'
response_string = ''
result.on 'data', (chunk) ->
response_string += chunk
result.on 'end', () ->
id = shortid.generate()
redis_client.set id, response_string
uri_h = process.env.TRAVELQABOT_URI_SERVER ? "http://localhost:3000"
uri_d = process.env.TRAVELQABOT_URI_DIR ? "/d"
link = "#{uri_h}#{uri_d}/#{id}"
response_length = process.env.TRAVELQABOT_RESPONSE_LENGTH ? "90"
watson_answer = JSON.parse(response_string)[0]
if watson_answer?
q = watson_answer.question;
if q
if q.evidencelist?.length? > 0
msg.send "#{q.evidencelist[0].text.substring(0, response_length)} #{link}"
else if q.errorNotifications? > 0
msg.send "Error: #{q.errornotifications[0].text}"
else
msg.send 'Error: No evidences or errors specified by Watson'
else
msg.send 'Error: No contents generated by Watson'
watson_req.on 'error', (err) ->
msg.send "Ooops, #{err}"
questionData =
'question':
'evidenceRequest':
'items': 1
'questionText': question
watson_req.write JSON.stringify(questionData)
watson_req.end()
|
[
{
"context": "$ ->\n # 2019-4-11 luky xi cheng qi xiu hao le!\n $('button[data-toggle]').on 'click',(e)->\n ",
"end": 46,
"score": 0.9300097227096558,
"start": 19,
"tag": "NAME",
"value": "luky xi cheng qi xiu hao le"
}
] | coffees/mine-superuser-list-tickets.coffee | android1and1/tickets | 0 | $ ->
# 2019-4-11 luky xi cheng qi xiu hao le!
$('button[data-toggle]').on 'click',(e)->
if $(e.target).text() is '收起'
$(e.target).button('reset')
else
$(e.target).button 'cower'
| 195090 | $ ->
# 2019-4-11 <NAME>!
$('button[data-toggle]').on 'click',(e)->
if $(e.target).text() is '收起'
$(e.target).button('reset')
else
$(e.target).button 'cower'
| true | $ ->
# 2019-4-11 PI:NAME:<NAME>END_PI!
$('button[data-toggle]').on 'click',(e)->
if $(e.target).text() is '收起'
$(e.target).button('reset')
else
$(e.target).button 'cower'
|
[
{
"context": " ).map(d3.format('.05f'))\n\n url = 'mailto:haihui@grep.ro?subject=Map%20note&body=' +\n encodeURIComp",
"end": 418,
"score": 0.9999292492866516,
"start": 404,
"tag": "EMAIL",
"value": "haihui@grep.ro"
}
] | src/ui/note.coffee | mgax/ghid-montan | 0 | app.note = (options) ->
map = options.map
btn = options.g.append('a')
.attr('xlink:href', '#')
btn.append('circle')
.attr('r', 17)
btn.append('text')
.attr('transform', "translate(-3,5)")
.text('!')
render = ->
lngLat = map.proj.inverse(
map.projection.invert(
[map.width / 2, map.height / 2])
).map(d3.format('.05f'))
url = 'mailto:haihui@grep.ro?subject=Map%20note&body=' +
encodeURIComponent('Location: ' + lngLat.join('/') + '\n\n\n')
btn.attr('xlink:href', url)
map.dispatch.on 'zoomend.note', ->
render()
map.dispatch.on 'redraw.note', ->
render()
| 43690 | app.note = (options) ->
map = options.map
btn = options.g.append('a')
.attr('xlink:href', '#')
btn.append('circle')
.attr('r', 17)
btn.append('text')
.attr('transform', "translate(-3,5)")
.text('!')
render = ->
lngLat = map.proj.inverse(
map.projection.invert(
[map.width / 2, map.height / 2])
).map(d3.format('.05f'))
url = 'mailto:<EMAIL>?subject=Map%20note&body=' +
encodeURIComponent('Location: ' + lngLat.join('/') + '\n\n\n')
btn.attr('xlink:href', url)
map.dispatch.on 'zoomend.note', ->
render()
map.dispatch.on 'redraw.note', ->
render()
| true | app.note = (options) ->
map = options.map
btn = options.g.append('a')
.attr('xlink:href', '#')
btn.append('circle')
.attr('r', 17)
btn.append('text')
.attr('transform', "translate(-3,5)")
.text('!')
render = ->
lngLat = map.proj.inverse(
map.projection.invert(
[map.width / 2, map.height / 2])
).map(d3.format('.05f'))
url = 'mailto:PI:EMAIL:<EMAIL>END_PI?subject=Map%20note&body=' +
encodeURIComponent('Location: ' + lngLat.join('/') + '\n\n\n')
btn.attr('xlink:href', url)
map.dispatch.on 'zoomend.note', ->
render()
map.dispatch.on 'redraw.note', ->
render()
|
[
{
"context": "rIntensify\"\n\n\t@isKeyworded: true\n\t@modifierName: \"Intensify\"\n\t@description: null\n\t@keywordDefinition: \"Eff",
"end": 246,
"score": 0.6605929136276245,
"start": 240,
"tag": "NAME",
"value": "Intens"
}
] | app/sdk/modifiers/modifierIntensify.coffee | willroberts/duelyst | 5 | Modifier = require './modifier'
ApplyCardToBoardAction = require 'app/sdk/actions/applyCardToBoardAction'
class ModifierIntensify extends Modifier
type:"ModifierIntensify"
@type:"ModifierIntensify"
@isKeyworded: true
@modifierName: "Intensify"
@description: null
@keywordDefinition: "Effect is boosted each time you play it."
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
getIsActionRelevant: (action) ->
# watch for instances of playing this card
if action instanceof ApplyCardToBoardAction and action.getOwnerId() is @getOwnerId() and action.getCard().getBaseCardId() is @getCard().getBaseCardId()
return true
else
return false
getIntensifyAmount: () ->
amount = 0
relevantActions = @getGameSession().filterActions(@getIsActionRelevant.bind(@))
if relevantActions?
amount = relevantActions.length
return amount
onActivate: () ->
super()
@onIntensify()
onIntensify: () ->
# override me in sub classes to implement special behavior
module.exports = ModifierIntensify
| 96346 | Modifier = require './modifier'
ApplyCardToBoardAction = require 'app/sdk/actions/applyCardToBoardAction'
class ModifierIntensify extends Modifier
type:"ModifierIntensify"
@type:"ModifierIntensify"
@isKeyworded: true
@modifierName: "<NAME>ify"
@description: null
@keywordDefinition: "Effect is boosted each time you play it."
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
getIsActionRelevant: (action) ->
# watch for instances of playing this card
if action instanceof ApplyCardToBoardAction and action.getOwnerId() is @getOwnerId() and action.getCard().getBaseCardId() is @getCard().getBaseCardId()
return true
else
return false
getIntensifyAmount: () ->
amount = 0
relevantActions = @getGameSession().filterActions(@getIsActionRelevant.bind(@))
if relevantActions?
amount = relevantActions.length
return amount
onActivate: () ->
super()
@onIntensify()
onIntensify: () ->
# override me in sub classes to implement special behavior
module.exports = ModifierIntensify
| true | Modifier = require './modifier'
ApplyCardToBoardAction = require 'app/sdk/actions/applyCardToBoardAction'
class ModifierIntensify extends Modifier
type:"ModifierIntensify"
@type:"ModifierIntensify"
@isKeyworded: true
@modifierName: "PI:NAME:<NAME>END_PIify"
@description: null
@keywordDefinition: "Effect is boosted each time you play it."
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
getIsActionRelevant: (action) ->
# watch for instances of playing this card
if action instanceof ApplyCardToBoardAction and action.getOwnerId() is @getOwnerId() and action.getCard().getBaseCardId() is @getCard().getBaseCardId()
return true
else
return false
getIntensifyAmount: () ->
amount = 0
relevantActions = @getGameSession().filterActions(@getIsActionRelevant.bind(@))
if relevantActions?
amount = relevantActions.length
return amount
onActivate: () ->
super()
@onIntensify()
onIntensify: () ->
# override me in sub classes to implement special behavior
module.exports = ModifierIntensify
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993525147438049,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-repl-setprompt.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.
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
os = require("os")
util = require("util")
args = [
"-e"
"var e = new (require(\"repl\")).REPLServer(\"foo.. \"); e.context.e = e;"
]
p = "bar.. "
child = spawn(process.execPath, args)
child.stdout.setEncoding "utf8"
data = ""
child.stdout.on "data", (d) ->
data += d
return
child.stdin.end util.format("e.setPrompt('%s');%s", p, os.EOL)
child.on "close", (code, signal) ->
assert.strictEqual code, 0
assert.ok not signal
lines = data.split(/\n/)
assert.strictEqual lines.pop(), p
return
| 48039 | # 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.
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
os = require("os")
util = require("util")
args = [
"-e"
"var e = new (require(\"repl\")).REPLServer(\"foo.. \"); e.context.e = e;"
]
p = "bar.. "
child = spawn(process.execPath, args)
child.stdout.setEncoding "utf8"
data = ""
child.stdout.on "data", (d) ->
data += d
return
child.stdin.end util.format("e.setPrompt('%s');%s", p, os.EOL)
child.on "close", (code, signal) ->
assert.strictEqual code, 0
assert.ok not signal
lines = data.split(/\n/)
assert.strictEqual lines.pop(), p
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.
common = require("../common")
assert = require("assert")
spawn = require("child_process").spawn
os = require("os")
util = require("util")
args = [
"-e"
"var e = new (require(\"repl\")).REPLServer(\"foo.. \"); e.context.e = e;"
]
p = "bar.. "
child = spawn(process.execPath, args)
child.stdout.setEncoding "utf8"
data = ""
child.stdout.on "data", (d) ->
data += d
return
child.stdin.end util.format("e.setPrompt('%s');%s", p, os.EOL)
child.on "close", (code, signal) ->
assert.strictEqual code, 0
assert.ok not signal
lines = data.split(/\n/)
assert.strictEqual lines.pop(), p
return
|
[
{
"context": " Backbone.Model({\n patients: [{id: 5, name: \"Elijah Hoppe\"}, {id: 7, name: \"Sofia Grimes\"}]\n services:",
"end": 366,
"score": 0.9998627305030823,
"start": 354,
"tag": "NAME",
"value": "Elijah Hoppe"
},
{
"context": "s: [{id: 5, name: \"Elijah Hoppe\"}, {... | spec/javascripts/core/apps/invoice/form-view.spec.coffee | houzelio/houzel | 2 | import FormView from 'javascripts/core/apps/invoice/form-view'
describe("Invoice Form View", () ->
MyRegion = Marionette.Region.extend({
el: '#main-region'
})
beforeEach ->
@myServices = [{id: 2, name: "Check in", value: 109.99}, {id: 3, name: "Exam Lab", value: 99.99}]
myModel = new Backbone.Model({
patients: [{id: 5, name: "Elijah Hoppe"}, {id: 7, name: "Sofia Grimes"}]
services: @myServices
invoice_services: [{id: 1, name: "Exam Lab", value: 104.99, reference_id: 3}]
})
@myRegion = new MyRegion
@myView = new FormView {model: myModel }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
it("should instance a new grid", () ->
expect(@myView.grid).toBeTruthy()
)
)
describe("after rendering", () ->
beforeEach ->
@myView.render()
it("should set the title correctly", () ->
expect(@myView.$el.find('.content-title').children()).not.toBe('')
)
it("should set the link for the button Back properly", () ->
expect(@myView.$el.find('.content-btn').children().attr("href")).toBeNonEmptyString()
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView, '_showPickers').and.callThrough()
spyOn(@myView, '_showSelects').and.callThrough()
spyOn(@myView.grid, 'showView').and.callThrough()
@myRegion.show(@myView)
it("shows the picker components", () ->
expect(@myView._showPickers).toHaveBeenCalled()
)
it("shows the grid component", () ->
expect(@myView.grid.showView).toHaveBeenCalled()
)
it("should show the elements when it exists on DOM", () ->
expect(@myView.$el.find('.table td').closest('tr').length).toBe(2)
)
describe("with a patient", () ->
it("shows the patient's information", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "Elijah Hoppe", address: "LoremLorem"}
patient_id: 5
services: @myServices
})
myView = new FormView {model: myModel}
@myRegion.show(myView)
expect(myView.$el.find('#patient-sel')).not.toBeInDOM()
expect(myView.$el).toContainText("Elijah Hoppe")
)
)
describe("without a patient", () ->
it("shows the select components", () ->
expect(@myView._showSelects).toHaveBeenCalled()
)
)
)
describe("Events", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpyObj('spy', ['save'])
@myView.render()
it("triggers the Save event", () ->
@myObject.listenTo(@myView, 'invoice:save', @spy.save)
@myView.$el.find('#save-btn').click()
expect(@spy.save).toHaveBeenCalled()
)
)
describe("handling services", () ->
addService = (value, myView) ->
myView.selects['#service-sel'].setValue(value)
myView.$el.find('#service-btn').click()
beforeEach ->
@myRegion.show(@myView)
it("should add a service to the invoice", () ->
addService(2, @myView)
expect(@myView.$el.find('#grid td').closest('tr').length).toBe(2)
expect(@myView.$el.find('#grid')).toContainText("Check in")
expect(@myView.$el.find('#total-td')).toHaveText('214.98')
)
it("should add services as many as possible", () ->
addService(2, @myView)
addService(2, @myView)
addService(3, @myView)
addService(2, @myView)
expect(@myView.$el.find('#grid td').closest('tr').length).toBe(5)
expect(@myView.$el.find('#grid td').closest('tr:contains("Check in")').length).toBe(3)
expect(@myView.$el.find('#grid td').closest('tr:contains("Exam Lab")').length).toBe(2)
expect(@myView.$el.find('#total-td')).toHaveText('534.95')
)
it("should remove a service from the invoice", () ->
@myView.$el.find('#grid td:first').closest('tr').find('a[data-remove="true"]').click()
expect(@myView.$el.find('#grid td:first').closest('tr')).toHaveClass('empty')
expect(@myView.$el.find('#total-td')).toHaveText('0.00')
)
)
)
| 136430 | import FormView from 'javascripts/core/apps/invoice/form-view'
describe("Invoice Form View", () ->
MyRegion = Marionette.Region.extend({
el: '#main-region'
})
beforeEach ->
@myServices = [{id: 2, name: "Check in", value: 109.99}, {id: 3, name: "Exam Lab", value: 99.99}]
myModel = new Backbone.Model({
patients: [{id: 5, name: "<NAME>"}, {id: 7, name: "<NAME>"}]
services: @myServices
invoice_services: [{id: 1, name: "Exam Lab", value: 104.99, reference_id: 3}]
})
@myRegion = new MyRegion
@myView = new FormView {model: myModel }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
it("should instance a new grid", () ->
expect(@myView.grid).toBeTruthy()
)
)
describe("after rendering", () ->
beforeEach ->
@myView.render()
it("should set the title correctly", () ->
expect(@myView.$el.find('.content-title').children()).not.toBe('')
)
it("should set the link for the button Back properly", () ->
expect(@myView.$el.find('.content-btn').children().attr("href")).toBeNonEmptyString()
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView, '_showPickers').and.callThrough()
spyOn(@myView, '_showSelects').and.callThrough()
spyOn(@myView.grid, 'showView').and.callThrough()
@myRegion.show(@myView)
it("shows the picker components", () ->
expect(@myView._showPickers).toHaveBeenCalled()
)
it("shows the grid component", () ->
expect(@myView.grid.showView).toHaveBeenCalled()
)
it("should show the elements when it exists on DOM", () ->
expect(@myView.$el.find('.table td').closest('tr').length).toBe(2)
)
describe("with a patient", () ->
it("shows the patient's information", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "<NAME>", address: "LoremLorem"}
patient_id: 5
services: @myServices
})
myView = new FormView {model: myModel}
@myRegion.show(myView)
expect(myView.$el.find('#patient-sel')).not.toBeInDOM()
expect(myView.$el).toContainText("<NAME>")
)
)
describe("without a patient", () ->
it("shows the select components", () ->
expect(@myView._showSelects).toHaveBeenCalled()
)
)
)
describe("Events", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpyObj('spy', ['save'])
@myView.render()
it("triggers the Save event", () ->
@myObject.listenTo(@myView, 'invoice:save', @spy.save)
@myView.$el.find('#save-btn').click()
expect(@spy.save).toHaveBeenCalled()
)
)
describe("handling services", () ->
addService = (value, myView) ->
myView.selects['#service-sel'].setValue(value)
myView.$el.find('#service-btn').click()
beforeEach ->
@myRegion.show(@myView)
it("should add a service to the invoice", () ->
addService(2, @myView)
expect(@myView.$el.find('#grid td').closest('tr').length).toBe(2)
expect(@myView.$el.find('#grid')).toContainText("Check in")
expect(@myView.$el.find('#total-td')).toHaveText('214.98')
)
it("should add services as many as possible", () ->
addService(2, @myView)
addService(2, @myView)
addService(3, @myView)
addService(2, @myView)
expect(@myView.$el.find('#grid td').closest('tr').length).toBe(5)
expect(@myView.$el.find('#grid td').closest('tr:contains("Check in")').length).toBe(3)
expect(@myView.$el.find('#grid td').closest('tr:contains("Exam Lab")').length).toBe(2)
expect(@myView.$el.find('#total-td')).toHaveText('534.95')
)
it("should remove a service from the invoice", () ->
@myView.$el.find('#grid td:first').closest('tr').find('a[data-remove="true"]').click()
expect(@myView.$el.find('#grid td:first').closest('tr')).toHaveClass('empty')
expect(@myView.$el.find('#total-td')).toHaveText('0.00')
)
)
)
| true | import FormView from 'javascripts/core/apps/invoice/form-view'
describe("Invoice Form View", () ->
MyRegion = Marionette.Region.extend({
el: '#main-region'
})
beforeEach ->
@myServices = [{id: 2, name: "Check in", value: 109.99}, {id: 3, name: "Exam Lab", value: 99.99}]
myModel = new Backbone.Model({
patients: [{id: 5, name: "PI:NAME:<NAME>END_PI"}, {id: 7, name: "PI:NAME:<NAME>END_PI"}]
services: @myServices
invoice_services: [{id: 1, name: "Exam Lab", value: 104.99, reference_id: 3}]
})
@myRegion = new MyRegion
@myView = new FormView {model: myModel }
describe("after initializing", () ->
it("should exist", () ->
expect(@myView).toBeTruthy()
)
it("should instance a new grid", () ->
expect(@myView.grid).toBeTruthy()
)
)
describe("after rendering", () ->
beforeEach ->
@myView.render()
it("should set the title correctly", () ->
expect(@myView.$el.find('.content-title').children()).not.toBe('')
)
it("should set the link for the button Back properly", () ->
expect(@myView.$el.find('.content-btn').children().attr("href")).toBeNonEmptyString()
)
)
describe("when attaching", () ->
beforeEach ->
spyOn(@myView, '_showPickers').and.callThrough()
spyOn(@myView, '_showSelects').and.callThrough()
spyOn(@myView.grid, 'showView').and.callThrough()
@myRegion.show(@myView)
it("shows the picker components", () ->
expect(@myView._showPickers).toHaveBeenCalled()
)
it("shows the grid component", () ->
expect(@myView.grid.showView).toHaveBeenCalled()
)
it("should show the elements when it exists on DOM", () ->
expect(@myView.$el.find('.table td').closest('tr').length).toBe(2)
)
describe("with a patient", () ->
it("shows the patient's information", () ->
myModel = new Backbone.Model({
id: 1
patient: {name: "PI:NAME:<NAME>END_PI", address: "LoremLorem"}
patient_id: 5
services: @myServices
})
myView = new FormView {model: myModel}
@myRegion.show(myView)
expect(myView.$el.find('#patient-sel')).not.toBeInDOM()
expect(myView.$el).toContainText("PI:NAME:<NAME>END_PI")
)
)
describe("without a patient", () ->
it("shows the select components", () ->
expect(@myView._showSelects).toHaveBeenCalled()
)
)
)
describe("Events", () ->
beforeEach ->
@myObject = new Marionette.MnObject
@spy = jasmine.createSpyObj('spy', ['save'])
@myView.render()
it("triggers the Save event", () ->
@myObject.listenTo(@myView, 'invoice:save', @spy.save)
@myView.$el.find('#save-btn').click()
expect(@spy.save).toHaveBeenCalled()
)
)
describe("handling services", () ->
addService = (value, myView) ->
myView.selects['#service-sel'].setValue(value)
myView.$el.find('#service-btn').click()
beforeEach ->
@myRegion.show(@myView)
it("should add a service to the invoice", () ->
addService(2, @myView)
expect(@myView.$el.find('#grid td').closest('tr').length).toBe(2)
expect(@myView.$el.find('#grid')).toContainText("Check in")
expect(@myView.$el.find('#total-td')).toHaveText('214.98')
)
it("should add services as many as possible", () ->
addService(2, @myView)
addService(2, @myView)
addService(3, @myView)
addService(2, @myView)
expect(@myView.$el.find('#grid td').closest('tr').length).toBe(5)
expect(@myView.$el.find('#grid td').closest('tr:contains("Check in")').length).toBe(3)
expect(@myView.$el.find('#grid td').closest('tr:contains("Exam Lab")').length).toBe(2)
expect(@myView.$el.find('#total-td')).toHaveText('534.95')
)
it("should remove a service from the invoice", () ->
@myView.$el.find('#grid td:first').closest('tr').find('a[data-remove="true"]').click()
expect(@myView.$el.find('#grid td:first').closest('tr')).toHaveClass('empty')
expect(@myView.$el.find('#total-td')).toHaveText('0.00')
)
)
)
|
[
{
"context": "et et sw=2 ts=2 sts=2 ff=unix fenc=utf8:\n# Author: Binux<i@binux.me>\n# http://binux.me\n# Created o",
"end": 64,
"score": 0.7408269643783569,
"start": 59,
"tag": "USERNAME",
"value": "Binux"
},
{
"context": "w=2 ts=2 sts=2 ff=unix fenc=utf8:\n# Author: Binux<i... | web/static/coffee/har/entry_list.coffee | glqf/qiandao | 0 | # vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
# http://binux.me
# Created on 2014-08-06 21:14:54
define (require, exports, module) ->
analysis = require '/static/har/analysis'
utils = require '/static/components/utils'
angular.module('entry_list', []).
controller('EntryList', ($scope, $rootScope, $http) ->
$scope.filter = {}
# on uploaded event
$rootScope.$on('har-loaded', (ev, data) ->
console.info(data)
$scope.data = data
window.global_har = $scope.data
$scope.filename = data.filename
$scope.har = data.har
$scope.init_env = data.env
$scope.env = utils.dict2list(data.env)
$scope.session = []
$scope.setting = data.setting
$scope.readonly = data.readonly or not HASUSER
$scope.is_check_all = false
$scope.update_checked_status()
$scope.recommend()
if (x for x in $scope.har.log.entries when x.recommend).length > 0
$scope.filter.recommend = true
if not $scope.readonly
utils.storage.set('har_filename', $scope.filename)
utils.storage.set('har_env', $scope.env)
if data.upload
utils.storage.set('har_har', $scope.har)
else
utils.storage.del('har_har')
)
$scope.$on('har-change', () ->
$scope.save_change()
)
$scope.save_change_storage = utils.debounce((() ->
if ($scope.filename and not $scope.readonly)
console.debug('local saved')
resortEntryList()
sortRequest($('#sortBtn')[0])
utils.storage.set('har_har', $scope.har)
), 1)
$scope.save_change = ()->
$scope.update_checked_status()
$scope.save_change_storage()
$scope.update_checked_status = utils.debounce((() ->
no_checked = (()->
for e in $scope.har.log.entries when !e.checked
return e
)()
$scope.is_check_all = no_checked == undefined
$scope.$apply();
), 1)
$scope.check_all = () ->
$scope.is_check_all = !$scope.is_check_all;
for entry in $scope.har.log.entries when entry.checked != $scope.is_check_all
entry.checked = $scope.is_check_all
$scope.save_change_storage()
$scope.inverse = ()->
for entry in $scope.har.log.entries
entry.checked = !entry.checked
$scope.save_change_storage()
$scope.status_label = (status) ->
if status // 100 == 2
'label-success'
else if status // 100 == 3
'label-info'
else if status == 0
'label-danger'
else
'label-warning'
$scope.variables_in_entry = analysis.variables_in_entry
$scope.badge_filter = (update) ->
filter = angular.copy($scope.filter)
for key, value of update
filter[key] = value
return filter
$scope.track_item = () ->
$scope.filted = []
(item) ->
$scope.filted.push(item)
return true
$scope.edit = (entry) ->
$scope.$broadcast('edit-entry', entry)
return false
$scope.recommend = () ->
analysis.recommend($scope.har)
$scope.download = () ->
$scope.pre_save()
# tpl = btoa(unescape(encodeURIComponent(angular.toJson(har2tpl($scope.har)))))
# angular.element('#download-har').attr('download', $scope.setting.sitename+'.har').attr('href', 'data:application/json;base64,'+tpl)
$scope.export_add($scope.setting.sitename+'.har',decodeURIComponent(encodeURIComponent(angular.toJson(har2tpl($scope.har)))))
return true
$scope.ev_click = (obj) ->
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
obj.dispatchEvent(ev)
$scope.export_add = (name, data) ->
urlObject = window.URL || window.webkitURL || window
export_blob = new Blob([data], {type: "application/json"})
save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
save_link.href = urlObject.createObjectURL(export_blob)
save_link.download = name
$scope.ev_click(save_link)
$scope.pre_save = () ->
alert_elem = angular.element('#save-har .alert-danger').hide()
alert_info_elem = angular.element('#save-har .alert-info').hide()
first_entry = (() ->
for entry in $scope.har.log.entries when (entry.checked and entry.request.url?.indexOf('://') != -1 and utils.url_parse(entry.request.url).protocol?.indexOf('api:') is -1)
variables = analysis.variables_in_entry(entry)
if ('cookies' in variables or 'cookie' in variables)
return entry
)()
if not first_entry
first_entry ?= (() ->
for entry in $scope.har.log.entries when (entry.checked and entry.request.url?.indexOf('://') != -1 and utils.url_parse(entry.request.url).protocol?.indexOf('api:') is -1)
return entry)()
try
$scope.setting ?= {}
$scope.setting.sitename ?= first_entry and utils.get_domain(first_entry.request.url).split('.')[0]
parsed_url = first_entry and utils.url_parse(first_entry.request.url)
$scope.setting.siteurl ?= parsed_url.protocol == 'https:' and "#{parsed_url.protocol}//#{parsed_url.host}" or parsed_url.host
catch error
console.error(error)
har2tpl = (har) ->
return ({
comment: entry.comment
request:
method: entry.request.method
url: entry.request.url
headers: ({name: h.name, value: h.value} for h in entry.request.headers when h.checked)
cookies: ({name: c.name, value: c.value} for c in entry.request.cookies when c.checked)
data: entry.request.postData?.text
mimeType: entry.request.postData?.mimeType
rule:
success_asserts: entry.success_asserts
failed_asserts: entry.failed_asserts
extract_variables: entry.extract_variables
} for entry in har.log.entries when entry.checked)
$scope.save = () ->
# 十六委托偷天修改,主要是HAR保存页面对自定义时间的支持
$scope.setting.interval = angular.element('#jiange_second').val();
# End
data = {
id: $scope.id,
har: $scope.har
tpl: har2tpl($scope.har)
setting: $scope.setting
}
save_btn = angular.element('#save-har .btn').button('loading')
alert_elem = angular.element('#save-har .alert-danger').hide()
alert_info_elem = angular.element('#save-har .alert-info').hide()
replace_text = 'save?reponame='+HARPATH+'&'+'name='+HARNAME
$http.post(location.pathname.replace('edit', replace_text), data)
.then((res) ->
data = res.data
status = res.status
headers = res.headers
config = res.config
utils.storage.del('har_filename')
utils.storage.del('har_har')
utils.storage.del('har_env')
save_btn.button('reset')
pathname = "/tpl/#{data.id}/edit"
if pathname != location.pathname
location.pathname = pathname
alert_info_elem.text('保存成功').show()
,(res) ->
data = res.data
status = res.status
headers = res.headers
config = res.config
alert_elem.text(data).show()
save_btn.button('reset')
)
$scope.test = () ->
data =
env:
variables: utils.list2dict($scope.env)
session: []
tpl: har2tpl($scope.har)
result = angular.element('#test-har .result').hide()
btn = angular.element('#test-har .btn').button('loading')
$http.post('/tpl/run', data)
.then((res) ->
result.html(res.data).show()
btn.button('reset')
,(res) ->
result.html('<h1 class="alert alert-danger text-center">签到失败</h1><div class="well"></div>').show().find('div').text(res.data)
btn.button('reset')
)
)
| 51970 | # vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8:
# Author: Binux<<EMAIL>>
# http://binux.me
# Created on 2014-08-06 21:14:54
define (require, exports, module) ->
analysis = require '/static/har/analysis'
utils = require '/static/components/utils'
angular.module('entry_list', []).
controller('EntryList', ($scope, $rootScope, $http) ->
$scope.filter = {}
# on uploaded event
$rootScope.$on('har-loaded', (ev, data) ->
console.info(data)
$scope.data = data
window.global_har = $scope.data
$scope.filename = data.filename
$scope.har = data.har
$scope.init_env = data.env
$scope.env = utils.dict2list(data.env)
$scope.session = []
$scope.setting = data.setting
$scope.readonly = data.readonly or not HASUSER
$scope.is_check_all = false
$scope.update_checked_status()
$scope.recommend()
if (x for x in $scope.har.log.entries when x.recommend).length > 0
$scope.filter.recommend = true
if not $scope.readonly
utils.storage.set('har_filename', $scope.filename)
utils.storage.set('har_env', $scope.env)
if data.upload
utils.storage.set('har_har', $scope.har)
else
utils.storage.del('har_har')
)
$scope.$on('har-change', () ->
$scope.save_change()
)
$scope.save_change_storage = utils.debounce((() ->
if ($scope.filename and not $scope.readonly)
console.debug('local saved')
resortEntryList()
sortRequest($('#sortBtn')[0])
utils.storage.set('har_har', $scope.har)
), 1)
$scope.save_change = ()->
$scope.update_checked_status()
$scope.save_change_storage()
$scope.update_checked_status = utils.debounce((() ->
no_checked = (()->
for e in $scope.har.log.entries when !e.checked
return e
)()
$scope.is_check_all = no_checked == undefined
$scope.$apply();
), 1)
$scope.check_all = () ->
$scope.is_check_all = !$scope.is_check_all;
for entry in $scope.har.log.entries when entry.checked != $scope.is_check_all
entry.checked = $scope.is_check_all
$scope.save_change_storage()
$scope.inverse = ()->
for entry in $scope.har.log.entries
entry.checked = !entry.checked
$scope.save_change_storage()
$scope.status_label = (status) ->
if status // 100 == 2
'label-success'
else if status // 100 == 3
'label-info'
else if status == 0
'label-danger'
else
'label-warning'
$scope.variables_in_entry = analysis.variables_in_entry
$scope.badge_filter = (update) ->
filter = angular.copy($scope.filter)
for key, value of update
filter[key] = value
return filter
$scope.track_item = () ->
$scope.filted = []
(item) ->
$scope.filted.push(item)
return true
$scope.edit = (entry) ->
$scope.$broadcast('edit-entry', entry)
return false
$scope.recommend = () ->
analysis.recommend($scope.har)
$scope.download = () ->
$scope.pre_save()
# tpl = btoa(unescape(encodeURIComponent(angular.toJson(har2tpl($scope.har)))))
# angular.element('#download-har').attr('download', $scope.setting.sitename+'.har').attr('href', 'data:application/json;base64,'+tpl)
$scope.export_add($scope.setting.sitename+'.har',decodeURIComponent(encodeURIComponent(angular.toJson(har2tpl($scope.har)))))
return true
$scope.ev_click = (obj) ->
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
obj.dispatchEvent(ev)
$scope.export_add = (name, data) ->
urlObject = window.URL || window.webkitURL || window
export_blob = new Blob([data], {type: "application/json"})
save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
save_link.href = urlObject.createObjectURL(export_blob)
save_link.download = name
$scope.ev_click(save_link)
$scope.pre_save = () ->
alert_elem = angular.element('#save-har .alert-danger').hide()
alert_info_elem = angular.element('#save-har .alert-info').hide()
first_entry = (() ->
for entry in $scope.har.log.entries when (entry.checked and entry.request.url?.indexOf('://') != -1 and utils.url_parse(entry.request.url).protocol?.indexOf('api:') is -1)
variables = analysis.variables_in_entry(entry)
if ('cookies' in variables or 'cookie' in variables)
return entry
)()
if not first_entry
first_entry ?= (() ->
for entry in $scope.har.log.entries when (entry.checked and entry.request.url?.indexOf('://') != -1 and utils.url_parse(entry.request.url).protocol?.indexOf('api:') is -1)
return entry)()
try
$scope.setting ?= {}
$scope.setting.sitename ?= first_entry and utils.get_domain(first_entry.request.url).split('.')[0]
parsed_url = first_entry and utils.url_parse(first_entry.request.url)
$scope.setting.siteurl ?= parsed_url.protocol == 'https:' and "#{parsed_url.protocol}//#{parsed_url.host}" or parsed_url.host
catch error
console.error(error)
har2tpl = (har) ->
return ({
comment: entry.comment
request:
method: entry.request.method
url: entry.request.url
headers: ({name: h.name, value: h.value} for h in entry.request.headers when h.checked)
cookies: ({name: c.name, value: c.value} for c in entry.request.cookies when c.checked)
data: entry.request.postData?.text
mimeType: entry.request.postData?.mimeType
rule:
success_asserts: entry.success_asserts
failed_asserts: entry.failed_asserts
extract_variables: entry.extract_variables
} for entry in har.log.entries when entry.checked)
$scope.save = () ->
# 十六委托偷天修改,主要是HAR保存页面对自定义时间的支持
$scope.setting.interval = angular.element('#jiange_second').val();
# End
data = {
id: $scope.id,
har: $scope.har
tpl: har2tpl($scope.har)
setting: $scope.setting
}
save_btn = angular.element('#save-har .btn').button('loading')
alert_elem = angular.element('#save-har .alert-danger').hide()
alert_info_elem = angular.element('#save-har .alert-info').hide()
replace_text = 'save?reponame='+HARPATH+'&'+'name='+HARNAME
$http.post(location.pathname.replace('edit', replace_text), data)
.then((res) ->
data = res.data
status = res.status
headers = res.headers
config = res.config
utils.storage.del('har_filename')
utils.storage.del('har_har')
utils.storage.del('har_env')
save_btn.button('reset')
pathname = "/tpl/#{data.id}/edit"
if pathname != location.pathname
location.pathname = pathname
alert_info_elem.text('保存成功').show()
,(res) ->
data = res.data
status = res.status
headers = res.headers
config = res.config
alert_elem.text(data).show()
save_btn.button('reset')
)
$scope.test = () ->
data =
env:
variables: utils.list2dict($scope.env)
session: []
tpl: har2tpl($scope.har)
result = angular.element('#test-har .result').hide()
btn = angular.element('#test-har .btn').button('loading')
$http.post('/tpl/run', data)
.then((res) ->
result.html(res.data).show()
btn.button('reset')
,(res) ->
result.html('<h1 class="alert alert-danger text-center">签到失败</h1><div class="well"></div>').show().find('div').text(res.data)
btn.button('reset')
)
)
| true | # vim: set et sw=2 ts=2 sts=2 ff=unix fenc=utf8:
# Author: Binux<PI:EMAIL:<EMAIL>END_PI>
# http://binux.me
# Created on 2014-08-06 21:14:54
define (require, exports, module) ->
analysis = require '/static/har/analysis'
utils = require '/static/components/utils'
angular.module('entry_list', []).
controller('EntryList', ($scope, $rootScope, $http) ->
$scope.filter = {}
# on uploaded event
$rootScope.$on('har-loaded', (ev, data) ->
console.info(data)
$scope.data = data
window.global_har = $scope.data
$scope.filename = data.filename
$scope.har = data.har
$scope.init_env = data.env
$scope.env = utils.dict2list(data.env)
$scope.session = []
$scope.setting = data.setting
$scope.readonly = data.readonly or not HASUSER
$scope.is_check_all = false
$scope.update_checked_status()
$scope.recommend()
if (x for x in $scope.har.log.entries when x.recommend).length > 0
$scope.filter.recommend = true
if not $scope.readonly
utils.storage.set('har_filename', $scope.filename)
utils.storage.set('har_env', $scope.env)
if data.upload
utils.storage.set('har_har', $scope.har)
else
utils.storage.del('har_har')
)
$scope.$on('har-change', () ->
$scope.save_change()
)
$scope.save_change_storage = utils.debounce((() ->
if ($scope.filename and not $scope.readonly)
console.debug('local saved')
resortEntryList()
sortRequest($('#sortBtn')[0])
utils.storage.set('har_har', $scope.har)
), 1)
$scope.save_change = ()->
$scope.update_checked_status()
$scope.save_change_storage()
$scope.update_checked_status = utils.debounce((() ->
no_checked = (()->
for e in $scope.har.log.entries when !e.checked
return e
)()
$scope.is_check_all = no_checked == undefined
$scope.$apply();
), 1)
$scope.check_all = () ->
$scope.is_check_all = !$scope.is_check_all;
for entry in $scope.har.log.entries when entry.checked != $scope.is_check_all
entry.checked = $scope.is_check_all
$scope.save_change_storage()
$scope.inverse = ()->
for entry in $scope.har.log.entries
entry.checked = !entry.checked
$scope.save_change_storage()
$scope.status_label = (status) ->
if status // 100 == 2
'label-success'
else if status // 100 == 3
'label-info'
else if status == 0
'label-danger'
else
'label-warning'
$scope.variables_in_entry = analysis.variables_in_entry
$scope.badge_filter = (update) ->
filter = angular.copy($scope.filter)
for key, value of update
filter[key] = value
return filter
$scope.track_item = () ->
$scope.filted = []
(item) ->
$scope.filted.push(item)
return true
$scope.edit = (entry) ->
$scope.$broadcast('edit-entry', entry)
return false
$scope.recommend = () ->
analysis.recommend($scope.har)
$scope.download = () ->
$scope.pre_save()
# tpl = btoa(unescape(encodeURIComponent(angular.toJson(har2tpl($scope.har)))))
# angular.element('#download-har').attr('download', $scope.setting.sitename+'.har').attr('href', 'data:application/json;base64,'+tpl)
$scope.export_add($scope.setting.sitename+'.har',decodeURIComponent(encodeURIComponent(angular.toJson(har2tpl($scope.har)))))
return true
$scope.ev_click = (obj) ->
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
obj.dispatchEvent(ev)
$scope.export_add = (name, data) ->
urlObject = window.URL || window.webkitURL || window
export_blob = new Blob([data], {type: "application/json"})
save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
save_link.href = urlObject.createObjectURL(export_blob)
save_link.download = name
$scope.ev_click(save_link)
$scope.pre_save = () ->
alert_elem = angular.element('#save-har .alert-danger').hide()
alert_info_elem = angular.element('#save-har .alert-info').hide()
first_entry = (() ->
for entry in $scope.har.log.entries when (entry.checked and entry.request.url?.indexOf('://') != -1 and utils.url_parse(entry.request.url).protocol?.indexOf('api:') is -1)
variables = analysis.variables_in_entry(entry)
if ('cookies' in variables or 'cookie' in variables)
return entry
)()
if not first_entry
first_entry ?= (() ->
for entry in $scope.har.log.entries when (entry.checked and entry.request.url?.indexOf('://') != -1 and utils.url_parse(entry.request.url).protocol?.indexOf('api:') is -1)
return entry)()
try
$scope.setting ?= {}
$scope.setting.sitename ?= first_entry and utils.get_domain(first_entry.request.url).split('.')[0]
parsed_url = first_entry and utils.url_parse(first_entry.request.url)
$scope.setting.siteurl ?= parsed_url.protocol == 'https:' and "#{parsed_url.protocol}//#{parsed_url.host}" or parsed_url.host
catch error
console.error(error)
har2tpl = (har) ->
return ({
comment: entry.comment
request:
method: entry.request.method
url: entry.request.url
headers: ({name: h.name, value: h.value} for h in entry.request.headers when h.checked)
cookies: ({name: c.name, value: c.value} for c in entry.request.cookies when c.checked)
data: entry.request.postData?.text
mimeType: entry.request.postData?.mimeType
rule:
success_asserts: entry.success_asserts
failed_asserts: entry.failed_asserts
extract_variables: entry.extract_variables
} for entry in har.log.entries when entry.checked)
$scope.save = () ->
# 十六委托偷天修改,主要是HAR保存页面对自定义时间的支持
$scope.setting.interval = angular.element('#jiange_second').val();
# End
data = {
id: $scope.id,
har: $scope.har
tpl: har2tpl($scope.har)
setting: $scope.setting
}
save_btn = angular.element('#save-har .btn').button('loading')
alert_elem = angular.element('#save-har .alert-danger').hide()
alert_info_elem = angular.element('#save-har .alert-info').hide()
replace_text = 'save?reponame='+HARPATH+'&'+'name='+HARNAME
$http.post(location.pathname.replace('edit', replace_text), data)
.then((res) ->
data = res.data
status = res.status
headers = res.headers
config = res.config
utils.storage.del('har_filename')
utils.storage.del('har_har')
utils.storage.del('har_env')
save_btn.button('reset')
pathname = "/tpl/#{data.id}/edit"
if pathname != location.pathname
location.pathname = pathname
alert_info_elem.text('保存成功').show()
,(res) ->
data = res.data
status = res.status
headers = res.headers
config = res.config
alert_elem.text(data).show()
save_btn.button('reset')
)
$scope.test = () ->
data =
env:
variables: utils.list2dict($scope.env)
session: []
tpl: har2tpl($scope.har)
result = angular.element('#test-har .result').hide()
btn = angular.element('#test-har .btn').button('loading')
$http.post('/tpl/run', data)
.then((res) ->
result.html(res.data).show()
btn.button('reset')
,(res) ->
result.html('<h1 class="alert alert-danger text-center">签到失败</h1><div class="well"></div>').show().find('div').text(res.data)
btn.button('reset')
)
)
|
[
{
"context": "\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch} = require './test'\nthe",
"end": 28,
"score": 0.6641077995300293,
"start": 23,
"tag": "USERNAME",
"value": "itajs"
},
{
"context": "ikita\n ssh: ssh\n .tools.dconf\n key: '/org/gnome/desktop/dateti... | packages/tools/test/dconf.coffee | chibanemourad/node-nikita | 0 |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require './test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'tools.dconf', ->
they 'testing some dconf settings', ({ssh}) ->
nikita
ssh: ssh
.tools.dconf
key: '/org/gnome/desktop/datetime/automatic-timezone'
value: "true"
.tools.dconf
key: '/org/gnome/desktop/peripherals/touchpad/click-method'
value: "fingers"
.tools.dconf
key: '/org/gnome/desktop/input-sources/xkb-options'
value: '[\'ctrl:swap_lalt_lctl\']'
.promise()
they 'checking if the settings were changed', ({ssh}) ->
nikita
ssh: ssh
.system.execute.assert
cmd: "dconf read /org/gnome/desktop/datetime/automatic-timezone"
assert: "true"
.system.execute.assert
cmd: "dconf read /org/gnome/desktop/peripherals/touchpad/click-method"
assert: "fingers"
.system.execute.assert
cmd: 'dconf read /org/gnome/desktop/input-sources/xkb-options'
assert: '[\'ctrl:swap_lalt_lctl\']'
.promise()
| 12204 |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require './test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'tools.dconf', ->
they 'testing some dconf settings', ({ssh}) ->
nikita
ssh: ssh
.tools.dconf
key: <KEY>'
value: "true"
.tools.dconf
key: <KEY>'
value: "f<KEY>"
.tools.dconf
key: <KEY>'
value: '[\'ctrl:swap_lalt_lctl\']'
.promise()
they 'checking if the settings were changed', ({ssh}) ->
nikita
ssh: ssh
.system.execute.assert
cmd: "dconf read /org/gnome/desktop/datetime/automatic-timezone"
assert: "true"
.system.execute.assert
cmd: "dconf read /org/gnome/desktop/peripherals/touchpad/click-method"
assert: "fingers"
.system.execute.assert
cmd: 'dconf read /org/gnome/desktop/input-sources/xkb-options'
assert: '[\'ctrl:swap_lalt_lctl\']'
.promise()
| true |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require './test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'tools.dconf', ->
they 'testing some dconf settings', ({ssh}) ->
nikita
ssh: ssh
.tools.dconf
key: PI:KEY:<KEY>END_PI'
value: "true"
.tools.dconf
key: PI:KEY:<KEY>END_PI'
value: "fPI:KEY:<KEY>END_PI"
.tools.dconf
key: PI:KEY:<KEY>END_PI'
value: '[\'ctrl:swap_lalt_lctl\']'
.promise()
they 'checking if the settings were changed', ({ssh}) ->
nikita
ssh: ssh
.system.execute.assert
cmd: "dconf read /org/gnome/desktop/datetime/automatic-timezone"
assert: "true"
.system.execute.assert
cmd: "dconf read /org/gnome/desktop/peripherals/touchpad/click-method"
assert: "fingers"
.system.execute.assert
cmd: 'dconf read /org/gnome/desktop/input-sources/xkb-options'
assert: '[\'ctrl:swap_lalt_lctl\']'
.promise()
|
[
{
"context": "eEach ->\n\t\t@adminUser_id = \"12321\"\n\t\t@newEmail = \"bob@smith.com\"\n\t\t@user = {_id:\"3121321\", email:@newEmail}\n\n\t\t@S",
"end": 331,
"score": 0.9999147653579712,
"start": 318,
"tag": "EMAIL",
"value": "bob@smith.com"
},
{
"context": "bscriptionUpdater.remo... | test/UnitTests/coffee/Subscription/SubscriptionGroupHandlerTests.coffee | mickaobrien/web-sharelatex | 0 | SandboxedModule = require('sandboxed-module')
should = require('chai').should()
sinon = require 'sinon'
assert = require("chai").assert
modulePath = "../../../../app/js/Features/Subscription/SubscriptionGroupHandler"
describe "Subscription Group Handler", ->
beforeEach ->
@adminUser_id = "12321"
@newEmail = "bob@smith.com"
@user = {_id:"3121321", email:@newEmail}
@SubscriptionLocator =
getUsersSubscription: sinon.stub()
@UserCreator =
getUserOrCreateHoldingAccount: sinon.stub().callsArgWith(1, null, @user)
@SubscriptionUpdater =
addUserToGroup: sinon.stub().callsArgWith(2)
removeUserFromGroup: sinon.stub().callsArgWith(2)
@UserLocator =
findById: sinon.stub()
@LimitationsManager =
hasGroupMembersLimitReached: sinon.stub()
@Handler = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"../User/UserCreator": @UserCreator
"./SubscriptionUpdater": @SubscriptionUpdater
"./SubscriptionLocator": @SubscriptionLocator
"../User/UserLocator": @UserLocator
"./LimitationsManager": @LimitationsManager
describe "addUserToGroup", ->
it "should find or create the user", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, false)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@UserCreator.getUserOrCreateHoldingAccount.calledWith(@newEmail).should.equal true
done()
it "should add the user to the group", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, false)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@SubscriptionUpdater.addUserToGroup.calledWith(@adminUser_id, @user._id).should.equal true
done()
it "should not add the user to the group if the limit has been reached", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, true)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@SubscriptionUpdater.addUserToGroup.called.should.equal false
done()
it "should return error that limit has been reached", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, true)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
err.limitReached.should.equal true
done()
describe "removeUserFromGroup", ->
it "should call the subscription updater to remove the user", (done)->
@Handler.removeUserFromGroup @adminUser_id, @user._id, (err)=>
@SubscriptionUpdater.removeUserFromGroup.calledWith(@adminUser_id, @user._id).should.equal true
done()
describe "getPopulatedListOfMembers", ->
beforeEach ->
@subscription = {}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
it "should locate the subscription", (done)->
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
@SubscriptionLocator.getUsersSubscription.calledWith(@adminUser_id).should.equal true
done()
it "should get the users by id", (done)->
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
@subscription.member_ids = ["1234", "342432", "312312"]
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
@UserLocator.findById.calledWith(@subscription.member_ids[0]).should.equal true
@UserLocator.findById.calledWith(@subscription.member_ids[1]).should.equal true
@UserLocator.findById.calledWith(@subscription.member_ids[2]).should.equal true
users.length.should.equal @subscription.member_ids.length
done()
it "should just return the id if the user can not be found as they may have deleted their account", (done)->
@UserLocator.findById.callsArgWith(1)
@subscription.member_ids = ["1234", "342432", "312312"]
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
assert.deepEqual users[0], {_id:@subscription.member_ids[0]}
assert.deepEqual users[1], {_id:@subscription.member_ids[1]}
assert.deepEqual users[2], {_id:@subscription.member_ids[2]}
done()
| 223948 | SandboxedModule = require('sandboxed-module')
should = require('chai').should()
sinon = require 'sinon'
assert = require("chai").assert
modulePath = "../../../../app/js/Features/Subscription/SubscriptionGroupHandler"
describe "Subscription Group Handler", ->
beforeEach ->
@adminUser_id = "12321"
@newEmail = "<EMAIL>"
@user = {_id:"3121321", email:@newEmail}
@SubscriptionLocator =
getUsersSubscription: sinon.stub()
@UserCreator =
getUserOrCreateHoldingAccount: sinon.stub().callsArgWith(1, null, @user)
@SubscriptionUpdater =
addUserToGroup: sinon.stub().callsArgWith(2)
removeUserFromGroup: sinon.stub().callsArgWith(2)
@UserLocator =
findById: sinon.stub()
@LimitationsManager =
hasGroupMembersLimitReached: sinon.stub()
@Handler = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"../User/UserCreator": @UserCreator
"./SubscriptionUpdater": @SubscriptionUpdater
"./SubscriptionLocator": @SubscriptionLocator
"../User/UserLocator": @UserLocator
"./LimitationsManager": @LimitationsManager
describe "addUserToGroup", ->
it "should find or create the user", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, false)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@UserCreator.getUserOrCreateHoldingAccount.calledWith(@newEmail).should.equal true
done()
it "should add the user to the group", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, false)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@SubscriptionUpdater.addUserToGroup.calledWith(@adminUser_id, @user._id).should.equal true
done()
it "should not add the user to the group if the limit has been reached", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, true)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@SubscriptionUpdater.addUserToGroup.called.should.equal false
done()
it "should return error that limit has been reached", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, true)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
err.limitReached.should.equal true
done()
describe "removeUserFromGroup", ->
it "should call the subscription updater to remove the user", (done)->
@Handler.removeUserFromGroup @adminUser_id, @user._id, (err)=>
@SubscriptionUpdater.removeUserFromGroup.calledWith(@adminUser_id, @user._id).should.equal true
done()
describe "getPopulatedListOfMembers", ->
beforeEach ->
@subscription = {}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
it "should locate the subscription", (done)->
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
@SubscriptionLocator.getUsersSubscription.calledWith(@adminUser_id).should.equal true
done()
it "should get the users by id", (done)->
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
@subscription.member_ids = ["1234", "342432", "312312"]
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
@UserLocator.findById.calledWith(@subscription.member_ids[0]).should.equal true
@UserLocator.findById.calledWith(@subscription.member_ids[1]).should.equal true
@UserLocator.findById.calledWith(@subscription.member_ids[2]).should.equal true
users.length.should.equal @subscription.member_ids.length
done()
it "should just return the id if the user can not be found as they may have deleted their account", (done)->
@UserLocator.findById.callsArgWith(1)
@subscription.member_ids = ["1234", "342432", "312312"]
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
assert.deepEqual users[0], {_id:@subscription.member_ids[0]}
assert.deepEqual users[1], {_id:@subscription.member_ids[1]}
assert.deepEqual users[2], {_id:@subscription.member_ids[2]}
done()
| true | SandboxedModule = require('sandboxed-module')
should = require('chai').should()
sinon = require 'sinon'
assert = require("chai").assert
modulePath = "../../../../app/js/Features/Subscription/SubscriptionGroupHandler"
describe "Subscription Group Handler", ->
beforeEach ->
@adminUser_id = "12321"
@newEmail = "PI:EMAIL:<EMAIL>END_PI"
@user = {_id:"3121321", email:@newEmail}
@SubscriptionLocator =
getUsersSubscription: sinon.stub()
@UserCreator =
getUserOrCreateHoldingAccount: sinon.stub().callsArgWith(1, null, @user)
@SubscriptionUpdater =
addUserToGroup: sinon.stub().callsArgWith(2)
removeUserFromGroup: sinon.stub().callsArgWith(2)
@UserLocator =
findById: sinon.stub()
@LimitationsManager =
hasGroupMembersLimitReached: sinon.stub()
@Handler = SandboxedModule.require modulePath, requires:
"logger-sharelatex": log:->
"../User/UserCreator": @UserCreator
"./SubscriptionUpdater": @SubscriptionUpdater
"./SubscriptionLocator": @SubscriptionLocator
"../User/UserLocator": @UserLocator
"./LimitationsManager": @LimitationsManager
describe "addUserToGroup", ->
it "should find or create the user", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, false)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@UserCreator.getUserOrCreateHoldingAccount.calledWith(@newEmail).should.equal true
done()
it "should add the user to the group", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, false)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@SubscriptionUpdater.addUserToGroup.calledWith(@adminUser_id, @user._id).should.equal true
done()
it "should not add the user to the group if the limit has been reached", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, true)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
@SubscriptionUpdater.addUserToGroup.called.should.equal false
done()
it "should return error that limit has been reached", (done)->
@LimitationsManager.hasGroupMembersLimitReached.callsArgWith(1, null, true)
@Handler.addUserToGroup @adminUser_id, @newEmail, (err)=>
err.limitReached.should.equal true
done()
describe "removeUserFromGroup", ->
it "should call the subscription updater to remove the user", (done)->
@Handler.removeUserFromGroup @adminUser_id, @user._id, (err)=>
@SubscriptionUpdater.removeUserFromGroup.calledWith(@adminUser_id, @user._id).should.equal true
done()
describe "getPopulatedListOfMembers", ->
beforeEach ->
@subscription = {}
@SubscriptionLocator.getUsersSubscription.callsArgWith(1, null, @subscription)
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
it "should locate the subscription", (done)->
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
@SubscriptionLocator.getUsersSubscription.calledWith(@adminUser_id).should.equal true
done()
it "should get the users by id", (done)->
@UserLocator.findById.callsArgWith(1, null, {_id:"31232"})
@subscription.member_ids = ["1234", "342432", "312312"]
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
@UserLocator.findById.calledWith(@subscription.member_ids[0]).should.equal true
@UserLocator.findById.calledWith(@subscription.member_ids[1]).should.equal true
@UserLocator.findById.calledWith(@subscription.member_ids[2]).should.equal true
users.length.should.equal @subscription.member_ids.length
done()
it "should just return the id if the user can not be found as they may have deleted their account", (done)->
@UserLocator.findById.callsArgWith(1)
@subscription.member_ids = ["1234", "342432", "312312"]
@Handler.getPopulatedListOfMembers @adminUser_id, (err, users)=>
assert.deepEqual users[0], {_id:@subscription.member_ids[0]}
assert.deepEqual users[1], {_id:@subscription.member_ids[1]}
assert.deepEqual users[2], {_id:@subscription.member_ids[2]}
done()
|
[
{
"context": "I_CONFIG'])\n else\n sandbox:\n key: 'xa6rd0x8wsuk9hc'\n secret: 'y6nw1t64rcppd8a'\n full:\n ",
"end": 2429,
"score": 0.99798184633255,
"start": 2414,
"tag": "KEY",
"value": "xa6rd0x8wsuk9hc"
},
{
"context": ":\n key: 'xa6rd0x8wsuk9hc'... | test/src/helpers/token_stash.coffee | expo/dropbox-js | 64 | # Stashes Dropbox access credentials.
class TokenStash
# @param {Object} options one or more of the options below
# @option options {Object} tls tls.createServer() options for the node.js
# HTTPS server that intercepts the OAuth 2 authorization redirect
constructor: (options) ->
@_tlsOptions = options?.tls or {}
@_fs = require 'fs'
# Node 0.6 hack.
unless @_fs.existsSync
path = require 'path'
@_fs.existsSync = (filePath) -> path.existsSync filePath
@_getCache = null
@setupFs()
# Calls the supplied method with the Dropbox access credentials.
#
# @param {function(Object<String, Object>)} callback called with an object
# whose 'full' and 'sandbox' properties point to two set of Oauth
# credentials
# @return null
get: (callback) ->
@_getCache or= @readStash()
if @_getCache
callback @_getCache
return null
@liveLogin (fullCredentials, sandboxCredentials) =>
unless fullCredentials and sandboxCredentials
throw new Error('Dropbox API authorization failed')
@writeStash fullCredentials, sandboxCredentials
@_getCache = @readStash()
callback @_getCache
null
# Obtains credentials by doing a login on the live site.
#
# @private
# Used internally by get.
#
# @param {function(Object, Object)} callback called with two sets of
# crendentials; the first set has Full Dropbox access, the second set has
# App folder access
# @return null
liveLogin: (callback) ->
Dropbox = require '../../../lib/dropbox'
sandboxClient = new Dropbox.Client @clientOptions().sandbox
fullClient = new Dropbox.Client @clientOptions().full
@setupAuth()
sandboxClient.authDriver @_authDriver
sandboxClient.authenticate (error, data) =>
if error
@killAuth()
console.error error
callback null
return
fullClient.authDriver @_authDriver
fullClient.authenticate (error, data) =>
@killAuth()
if error
console.error error
callback null
return
credentials = @clientOptions()
callback fullClient.credentials(), sandboxClient.credentials()
null
# Returns the options used to create a Dropbox Client.
clientOptions: ->
if process.env['API_CONFIG']
JSON.parse @_fs.readFileSync(process.env['API_CONFIG'])
else
sandbox:
key: 'xa6rd0x8wsuk9hc'
secret: 'y6nw1t64rcppd8a'
full:
key: 'c9x6i3k2zlwz21g'
secret: '82nxm80jz231rpn'
# Reads the file containing the access credentials, if it is available.
#
# @return {Object?} parsed access credentials, or null if they haven't been
# stashed
readStash: ->
unless @_fs.existsSync @_jsonPath
return null
JSON.parse @_fs.readFileSync @_jsonPath
# Stashes the access credentials for future test use.
#
# @return null
writeStash: (fullCredentials, sandboxCredentials) ->
json = JSON.stringify full: fullCredentials, sandbox: sandboxCredentials
@_fs.writeFileSync @_jsonPath, json
browserJs = "window.testKeys = #{JSON.stringify sandboxCredentials};" +
"window.testFullDropboxKeys = #{JSON.stringify fullCredentials};"
@_fs.writeFileSync @_browserJsPath, browserJs
workerJs = "self.testKeys = #{JSON.stringify sandboxCredentials};" +
"self.testFullDropboxKeys = #{JSON.stringify fullCredentials};"
@_fs.writeFileSync @_workerJsPath, workerJs
null
# Sets up a node.js server-based authentication driver.
setupAuth: ->
return if @_authDriver
Dropbox = require '../../../lib/dropbox'
@_authDriver = new Dropbox.AuthDriver.NodeServer tls: @_tlsOptions
# Shuts down the node.js server behind the authentication server.
killAuth: ->
return unless @_authDriver
@_authDriver.closeServer()
@_authDriver = null
# Sets up the directory structure for the credential stash.
setupFs: ->
@_dirPath = 'test/token'
@_jsonPath = 'test/token/token.json'
@_browserJsPath = 'test/token/token.browser.js'
@_workerJsPath = 'test/token/token.worker.js'
unless @_fs.existsSync @_dirPath
@_fs.mkdirSync @_dirPath
module.exports = TokenStash
| 121416 | # Stashes Dropbox access credentials.
class TokenStash
# @param {Object} options one or more of the options below
# @option options {Object} tls tls.createServer() options for the node.js
# HTTPS server that intercepts the OAuth 2 authorization redirect
constructor: (options) ->
@_tlsOptions = options?.tls or {}
@_fs = require 'fs'
# Node 0.6 hack.
unless @_fs.existsSync
path = require 'path'
@_fs.existsSync = (filePath) -> path.existsSync filePath
@_getCache = null
@setupFs()
# Calls the supplied method with the Dropbox access credentials.
#
# @param {function(Object<String, Object>)} callback called with an object
# whose 'full' and 'sandbox' properties point to two set of Oauth
# credentials
# @return null
get: (callback) ->
@_getCache or= @readStash()
if @_getCache
callback @_getCache
return null
@liveLogin (fullCredentials, sandboxCredentials) =>
unless fullCredentials and sandboxCredentials
throw new Error('Dropbox API authorization failed')
@writeStash fullCredentials, sandboxCredentials
@_getCache = @readStash()
callback @_getCache
null
# Obtains credentials by doing a login on the live site.
#
# @private
# Used internally by get.
#
# @param {function(Object, Object)} callback called with two sets of
# crendentials; the first set has Full Dropbox access, the second set has
# App folder access
# @return null
liveLogin: (callback) ->
Dropbox = require '../../../lib/dropbox'
sandboxClient = new Dropbox.Client @clientOptions().sandbox
fullClient = new Dropbox.Client @clientOptions().full
@setupAuth()
sandboxClient.authDriver @_authDriver
sandboxClient.authenticate (error, data) =>
if error
@killAuth()
console.error error
callback null
return
fullClient.authDriver @_authDriver
fullClient.authenticate (error, data) =>
@killAuth()
if error
console.error error
callback null
return
credentials = @clientOptions()
callback fullClient.credentials(), sandboxClient.credentials()
null
# Returns the options used to create a Dropbox Client.
clientOptions: ->
if process.env['API_CONFIG']
JSON.parse @_fs.readFileSync(process.env['API_CONFIG'])
else
sandbox:
key: '<KEY>'
secret: '<KEY>'
full:
key: '<KEY>'
secret: '<KEY>'
# Reads the file containing the access credentials, if it is available.
#
# @return {Object?} parsed access credentials, or null if they haven't been
# stashed
readStash: ->
unless @_fs.existsSync @_jsonPath
return null
JSON.parse @_fs.readFileSync @_jsonPath
# Stashes the access credentials for future test use.
#
# @return null
writeStash: (fullCredentials, sandboxCredentials) ->
json = JSON.stringify full: fullCredentials, sandbox: sandboxCredentials
@_fs.writeFileSync @_jsonPath, json
browserJs = "window.testKeys = #{JSON.stringify sandboxCredentials};" +
"window.testFullDropboxKeys = #{JSON.stringify fullCredentials};"
@_fs.writeFileSync @_browserJsPath, browserJs
workerJs = "self.testKeys = #{JSON.stringify sandboxCredentials};" +
"self.testFullDropboxKeys = #{JSON.stringify fullCredentials};"
@_fs.writeFileSync @_workerJsPath, workerJs
null
# Sets up a node.js server-based authentication driver.
setupAuth: ->
return if @_authDriver
Dropbox = require '../../../lib/dropbox'
@_authDriver = new Dropbox.AuthDriver.NodeServer tls: @_tlsOptions
# Shuts down the node.js server behind the authentication server.
killAuth: ->
return unless @_authDriver
@_authDriver.closeServer()
@_authDriver = null
# Sets up the directory structure for the credential stash.
setupFs: ->
@_dirPath = 'test/token'
@_jsonPath = 'test/token/token.json'
@_browserJsPath = 'test/token/token.browser.js'
@_workerJsPath = 'test/token/token.worker.js'
unless @_fs.existsSync @_dirPath
@_fs.mkdirSync @_dirPath
module.exports = TokenStash
| true | # Stashes Dropbox access credentials.
class TokenStash
# @param {Object} options one or more of the options below
# @option options {Object} tls tls.createServer() options for the node.js
# HTTPS server that intercepts the OAuth 2 authorization redirect
constructor: (options) ->
@_tlsOptions = options?.tls or {}
@_fs = require 'fs'
# Node 0.6 hack.
unless @_fs.existsSync
path = require 'path'
@_fs.existsSync = (filePath) -> path.existsSync filePath
@_getCache = null
@setupFs()
# Calls the supplied method with the Dropbox access credentials.
#
# @param {function(Object<String, Object>)} callback called with an object
# whose 'full' and 'sandbox' properties point to two set of Oauth
# credentials
# @return null
get: (callback) ->
@_getCache or= @readStash()
if @_getCache
callback @_getCache
return null
@liveLogin (fullCredentials, sandboxCredentials) =>
unless fullCredentials and sandboxCredentials
throw new Error('Dropbox API authorization failed')
@writeStash fullCredentials, sandboxCredentials
@_getCache = @readStash()
callback @_getCache
null
# Obtains credentials by doing a login on the live site.
#
# @private
# Used internally by get.
#
# @param {function(Object, Object)} callback called with two sets of
# crendentials; the first set has Full Dropbox access, the second set has
# App folder access
# @return null
liveLogin: (callback) ->
Dropbox = require '../../../lib/dropbox'
sandboxClient = new Dropbox.Client @clientOptions().sandbox
fullClient = new Dropbox.Client @clientOptions().full
@setupAuth()
sandboxClient.authDriver @_authDriver
sandboxClient.authenticate (error, data) =>
if error
@killAuth()
console.error error
callback null
return
fullClient.authDriver @_authDriver
fullClient.authenticate (error, data) =>
@killAuth()
if error
console.error error
callback null
return
credentials = @clientOptions()
callback fullClient.credentials(), sandboxClient.credentials()
null
# Returns the options used to create a Dropbox Client.
clientOptions: ->
if process.env['API_CONFIG']
JSON.parse @_fs.readFileSync(process.env['API_CONFIG'])
else
sandbox:
key: 'PI:KEY:<KEY>END_PI'
secret: 'PI:KEY:<KEY>END_PI'
full:
key: 'PI:KEY:<KEY>END_PI'
secret: 'PI:KEY:<KEY>END_PI'
# Reads the file containing the access credentials, if it is available.
#
# @return {Object?} parsed access credentials, or null if they haven't been
# stashed
readStash: ->
unless @_fs.existsSync @_jsonPath
return null
JSON.parse @_fs.readFileSync @_jsonPath
# Stashes the access credentials for future test use.
#
# @return null
writeStash: (fullCredentials, sandboxCredentials) ->
json = JSON.stringify full: fullCredentials, sandbox: sandboxCredentials
@_fs.writeFileSync @_jsonPath, json
browserJs = "window.testKeys = #{JSON.stringify sandboxCredentials};" +
"window.testFullDropboxKeys = #{JSON.stringify fullCredentials};"
@_fs.writeFileSync @_browserJsPath, browserJs
workerJs = "self.testKeys = #{JSON.stringify sandboxCredentials};" +
"self.testFullDropboxKeys = #{JSON.stringify fullCredentials};"
@_fs.writeFileSync @_workerJsPath, workerJs
null
# Sets up a node.js server-based authentication driver.
setupAuth: ->
return if @_authDriver
Dropbox = require '../../../lib/dropbox'
@_authDriver = new Dropbox.AuthDriver.NodeServer tls: @_tlsOptions
# Shuts down the node.js server behind the authentication server.
killAuth: ->
return unless @_authDriver
@_authDriver.closeServer()
@_authDriver = null
# Sets up the directory structure for the credential stash.
setupFs: ->
@_dirPath = 'test/token'
@_jsonPath = 'test/token/token.json'
@_browserJsPath = 'test/token/token.browser.js'
@_workerJsPath = 'test/token/token.worker.js'
unless @_fs.existsSync @_dirPath
@_fs.mkdirSync @_dirPath
module.exports = TokenStash
|
[
{
"context": " super(owner, name, options)\n\n @foreignKey = \"#{name}Id\"\n owner.field @foreignKey, type: \"Id\"\n \n ",
"end": 173,
"score": 0.9656890034675598,
"start": 163,
"tag": "KEY",
"value": "\"#{name}Id"
}
] | src/tower/model/relation/belongsTo.coffee | vjsingh/tower | 1 | class Tower.Model.Relation.BelongsTo extends Tower.Model.Relation
constructor: (owner, name, options = {}) ->
super(owner, name, options)
@foreignKey = "#{name}Id"
owner.field @foreignKey, type: "Id"
if @polymorphic
@foreignType = "#{name}Type"
owner.field @foreignType, type: "String"
owner.prototype[name] = ->
@relation(name)
owner.prototype["build#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@buildRelation(name, attributes, callback)
owner.prototype["create#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@createRelation(name, attributes, callback)
class @Criteria extends @Criteria
isBelongsTo: true
# need to do something here about Reflection
toCriteria: ->
criteria = super
relation = @relation
# @todo shouldn't have to do $in here...
criteria.where(id: $in: [@owner.get(relation.foreignKey)])
criteria
module.exports = Tower.Model.Relation.BelongsTo
| 210035 | class Tower.Model.Relation.BelongsTo extends Tower.Model.Relation
constructor: (owner, name, options = {}) ->
super(owner, name, options)
@foreignKey = <KEY>"
owner.field @foreignKey, type: "Id"
if @polymorphic
@foreignType = "#{name}Type"
owner.field @foreignType, type: "String"
owner.prototype[name] = ->
@relation(name)
owner.prototype["build#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@buildRelation(name, attributes, callback)
owner.prototype["create#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@createRelation(name, attributes, callback)
class @Criteria extends @Criteria
isBelongsTo: true
# need to do something here about Reflection
toCriteria: ->
criteria = super
relation = @relation
# @todo shouldn't have to do $in here...
criteria.where(id: $in: [@owner.get(relation.foreignKey)])
criteria
module.exports = Tower.Model.Relation.BelongsTo
| true | class Tower.Model.Relation.BelongsTo extends Tower.Model.Relation
constructor: (owner, name, options = {}) ->
super(owner, name, options)
@foreignKey = PI:KEY:<KEY>END_PI"
owner.field @foreignKey, type: "Id"
if @polymorphic
@foreignType = "#{name}Type"
owner.field @foreignType, type: "String"
owner.prototype[name] = ->
@relation(name)
owner.prototype["build#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@buildRelation(name, attributes, callback)
owner.prototype["create#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@createRelation(name, attributes, callback)
class @Criteria extends @Criteria
isBelongsTo: true
# need to do something here about Reflection
toCriteria: ->
criteria = super
relation = @relation
# @todo shouldn't have to do $in here...
criteria.where(id: $in: [@owner.get(relation.foreignKey)])
criteria
module.exports = Tower.Model.Relation.BelongsTo
|
[
{
"context": "ult: { innerObject: { key1: 'value1', key2: 'value2' } }\n# }\n#\n# data = { innerObject: { pr",
"end": 1921,
"score": 0.816594123840332,
"start": 1920,
"tag": "KEY",
"value": "2"
}
] | test/utils.spec.coffee | lgr7/codecombattreema | 66 | describe 'utilities', ->
backupJQuery = $
beforeEach ->
window.jQuery = undefined
window.$ = undefined
afterEach ->
window.jQuery = backupJQuery
window.$ = backupJQuery
describe 'tests', ->
it 'run in an environment without jQuery', ->
hadError = false
try
$('body')
catch
hadError = true
expect(hadError).toBe(true)
describe 'populateDefaults', ->
it 'walks through data and applies schema defaults to data', ->
schema = {
type: 'object'
default: { innerObject: {}, someProp: 1 }
properties:
innerObject: { default: { key1: 'value1', key2: 'value2' }}
}
data = null
result = TreemaNode.utils.populateDefaults(data, schema)
expect(result).toBeDefined()
expect(result.innerObject).toBeDefined()
expect(result.innerObject.key1).toBe('value1')
expect(result.innerObject.key2).toBe('value2')
it 'merges in default objects that are adjacent to extant data', ->
schema = {
type: 'object'
properties:
innerObject: { default: { key1: 'value1', key2: 'value2' }}
}
data = { innerObject: { key1: 'extantData' }}
result = TreemaNode.utils.populateDefaults(data, schema)
expect(result).toBeDefined()
expect(result.innerObject).toBeDefined()
expect(result.innerObject.key1).toBe('extantData')
expect(result.innerObject.key2).toBe('value2')
# In order to support the default structure below, would need to
# make populateData a bit more complicated, with some custom merging logic.
# Going to see if we can get away without it first.
# it 'merges default objects from parent schemas down to child extant data', ->
# schema = {
# type: 'object'
# default: { innerObject: { key1: 'value1', key2: 'value2' } }
# }
#
# data = { innerObject: { prop1: 'extantData' } }
#
# result = TreemaNode.utils.populateDefaults(data, schema)
#
# expect(result.innerObject).toBeDefined()
# expect(result.innerObject.prop1).toBe('extantData')
# expect(result.innerObject.prop2).toBe('2')
describe 'walk', ->
it 'calls a callback on every piece of data in a JSON object, providing path, data and working schema', ->
schema = {
type: 'object'
properties:
key1: { title: 'Number 1' }
key2: { title: 'Number 2' }
}
data = { key1: 1, key2: 2 }
paths = []
values = []
TreemaNode.utils.walk data, schema, null, (path, data, schema) ->
paths.push(path)
values.push(data)
expect(paths.length).toBe(3)
expect('' in paths).toBe(true)
expect('key1' in paths).toBe(true)
expect('key2' in paths).toBe(true)
expect(data in values).toBe(true)
expect(data.key1 in values).toBe(true)
expect(data.key2 in values).toBe(true)
it 'traverses arrays', ->
schema = {
type: 'array'
items: {
type: 'object'
marker: true
}
}
data = [{}]
foundIt = false
TreemaNode.utils.walk data, schema, null, (path, data, schema) ->
if path is '0'
expect(schema.marker).toBe(true)
foundIt = true
expect(foundIt).toBe(true)
describe 'getChildSchema', ->
it 'returns child schemas from properties', ->
schema = { properties: { key1: { title: 'some title' } }}
childSchema = TreemaNode.utils.getChildSchema('key1', schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from additionalProperties', ->
schema = { additionalProperties: { title: 'some title' } }
childSchema = TreemaNode.utils.getChildSchema('key1', schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from patternProperties', ->
schema = { patternProperties: { '^[a-z]+$': { title: 'some title' } }}
childSchema = TreemaNode.utils.getChildSchema('key', schema)
expect(childSchema.title).toBe('some title')
childSchema = TreemaNode.utils.getChildSchema('123', schema)
expect(childSchema.title).toBeUndefined()
it 'returns child schemas from an items schema', ->
schema = { items: { title: 'some title' } }
childSchema = TreemaNode.utils.getChildSchema(0, schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from an items array of schemas', ->
schema = { items: [{ title: 'some title' }] }
childSchema = TreemaNode.utils.getChildSchema(0, schema)
expect(childSchema.title).toBe('some title')
childSchema = TreemaNode.utils.getChildSchema(1, schema)
expect(childSchema.title).toBeUndefined()
it 'returns child schemas from additionalItems', ->
schema = { items: [{ title: 'some title' }], additionalItems: { title: 'another title'} }
childSchema = TreemaNode.utils.getChildSchema(1, schema)
expect(childSchema.title).toBe('another title')
describe 'buildWorkingSchemas', ->
it 'returns the same single schema if there are no combinatorials or references', ->
schema = {}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas[0] is schema).toBeTruthy()
it 'combines allOf into a single schema', ->
schema = { title: 'title', allOf: [ { description: 'description' }, { type: 'number' } ]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(1)
workingSchema = workingSchemas[0]
expect(workingSchema.title).toBe('title')
expect(workingSchema.description).toBe('description')
expect(workingSchema.type).toBe('number')
it 'creates a separate working schema for each anyOf', ->
schema = { title: 'title', anyOf: [{ type: 'string' }, { type: 'number' }]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(2)
types = (schema.type for schema in workingSchemas)
expect('string' in types).toBe(true)
expect('number' in types).toBe(true)
it 'creates a separate working schema for each oneOf', ->
schema = { title: 'title', oneOf: [{ type: 'string' }, { type: 'number' }]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(2)
types = (schema.type for schema in workingSchemas)
expect('string' in types).toBe(true)
expect('number' in types).toBe(true)
# Eventually might want more advanced behaviors, like smartly combining types from "allOf" or "oneOf" schemas.
# But for now this more naive combination behavior will do.
| 194104 | describe 'utilities', ->
backupJQuery = $
beforeEach ->
window.jQuery = undefined
window.$ = undefined
afterEach ->
window.jQuery = backupJQuery
window.$ = backupJQuery
describe 'tests', ->
it 'run in an environment without jQuery', ->
hadError = false
try
$('body')
catch
hadError = true
expect(hadError).toBe(true)
describe 'populateDefaults', ->
it 'walks through data and applies schema defaults to data', ->
schema = {
type: 'object'
default: { innerObject: {}, someProp: 1 }
properties:
innerObject: { default: { key1: 'value1', key2: 'value2' }}
}
data = null
result = TreemaNode.utils.populateDefaults(data, schema)
expect(result).toBeDefined()
expect(result.innerObject).toBeDefined()
expect(result.innerObject.key1).toBe('value1')
expect(result.innerObject.key2).toBe('value2')
it 'merges in default objects that are adjacent to extant data', ->
schema = {
type: 'object'
properties:
innerObject: { default: { key1: 'value1', key2: 'value2' }}
}
data = { innerObject: { key1: 'extantData' }}
result = TreemaNode.utils.populateDefaults(data, schema)
expect(result).toBeDefined()
expect(result.innerObject).toBeDefined()
expect(result.innerObject.key1).toBe('extantData')
expect(result.innerObject.key2).toBe('value2')
# In order to support the default structure below, would need to
# make populateData a bit more complicated, with some custom merging logic.
# Going to see if we can get away without it first.
# it 'merges default objects from parent schemas down to child extant data', ->
# schema = {
# type: 'object'
# default: { innerObject: { key1: 'value1', key2: 'value<KEY>' } }
# }
#
# data = { innerObject: { prop1: 'extantData' } }
#
# result = TreemaNode.utils.populateDefaults(data, schema)
#
# expect(result.innerObject).toBeDefined()
# expect(result.innerObject.prop1).toBe('extantData')
# expect(result.innerObject.prop2).toBe('2')
describe 'walk', ->
it 'calls a callback on every piece of data in a JSON object, providing path, data and working schema', ->
schema = {
type: 'object'
properties:
key1: { title: 'Number 1' }
key2: { title: 'Number 2' }
}
data = { key1: 1, key2: 2 }
paths = []
values = []
TreemaNode.utils.walk data, schema, null, (path, data, schema) ->
paths.push(path)
values.push(data)
expect(paths.length).toBe(3)
expect('' in paths).toBe(true)
expect('key1' in paths).toBe(true)
expect('key2' in paths).toBe(true)
expect(data in values).toBe(true)
expect(data.key1 in values).toBe(true)
expect(data.key2 in values).toBe(true)
it 'traverses arrays', ->
schema = {
type: 'array'
items: {
type: 'object'
marker: true
}
}
data = [{}]
foundIt = false
TreemaNode.utils.walk data, schema, null, (path, data, schema) ->
if path is '0'
expect(schema.marker).toBe(true)
foundIt = true
expect(foundIt).toBe(true)
describe 'getChildSchema', ->
it 'returns child schemas from properties', ->
schema = { properties: { key1: { title: 'some title' } }}
childSchema = TreemaNode.utils.getChildSchema('key1', schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from additionalProperties', ->
schema = { additionalProperties: { title: 'some title' } }
childSchema = TreemaNode.utils.getChildSchema('key1', schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from patternProperties', ->
schema = { patternProperties: { '^[a-z]+$': { title: 'some title' } }}
childSchema = TreemaNode.utils.getChildSchema('key', schema)
expect(childSchema.title).toBe('some title')
childSchema = TreemaNode.utils.getChildSchema('123', schema)
expect(childSchema.title).toBeUndefined()
it 'returns child schemas from an items schema', ->
schema = { items: { title: 'some title' } }
childSchema = TreemaNode.utils.getChildSchema(0, schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from an items array of schemas', ->
schema = { items: [{ title: 'some title' }] }
childSchema = TreemaNode.utils.getChildSchema(0, schema)
expect(childSchema.title).toBe('some title')
childSchema = TreemaNode.utils.getChildSchema(1, schema)
expect(childSchema.title).toBeUndefined()
it 'returns child schemas from additionalItems', ->
schema = { items: [{ title: 'some title' }], additionalItems: { title: 'another title'} }
childSchema = TreemaNode.utils.getChildSchema(1, schema)
expect(childSchema.title).toBe('another title')
describe 'buildWorkingSchemas', ->
it 'returns the same single schema if there are no combinatorials or references', ->
schema = {}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas[0] is schema).toBeTruthy()
it 'combines allOf into a single schema', ->
schema = { title: 'title', allOf: [ { description: 'description' }, { type: 'number' } ]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(1)
workingSchema = workingSchemas[0]
expect(workingSchema.title).toBe('title')
expect(workingSchema.description).toBe('description')
expect(workingSchema.type).toBe('number')
it 'creates a separate working schema for each anyOf', ->
schema = { title: 'title', anyOf: [{ type: 'string' }, { type: 'number' }]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(2)
types = (schema.type for schema in workingSchemas)
expect('string' in types).toBe(true)
expect('number' in types).toBe(true)
it 'creates a separate working schema for each oneOf', ->
schema = { title: 'title', oneOf: [{ type: 'string' }, { type: 'number' }]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(2)
types = (schema.type for schema in workingSchemas)
expect('string' in types).toBe(true)
expect('number' in types).toBe(true)
# Eventually might want more advanced behaviors, like smartly combining types from "allOf" or "oneOf" schemas.
# But for now this more naive combination behavior will do.
| true | describe 'utilities', ->
backupJQuery = $
beforeEach ->
window.jQuery = undefined
window.$ = undefined
afterEach ->
window.jQuery = backupJQuery
window.$ = backupJQuery
describe 'tests', ->
it 'run in an environment without jQuery', ->
hadError = false
try
$('body')
catch
hadError = true
expect(hadError).toBe(true)
describe 'populateDefaults', ->
it 'walks through data and applies schema defaults to data', ->
schema = {
type: 'object'
default: { innerObject: {}, someProp: 1 }
properties:
innerObject: { default: { key1: 'value1', key2: 'value2' }}
}
data = null
result = TreemaNode.utils.populateDefaults(data, schema)
expect(result).toBeDefined()
expect(result.innerObject).toBeDefined()
expect(result.innerObject.key1).toBe('value1')
expect(result.innerObject.key2).toBe('value2')
it 'merges in default objects that are adjacent to extant data', ->
schema = {
type: 'object'
properties:
innerObject: { default: { key1: 'value1', key2: 'value2' }}
}
data = { innerObject: { key1: 'extantData' }}
result = TreemaNode.utils.populateDefaults(data, schema)
expect(result).toBeDefined()
expect(result.innerObject).toBeDefined()
expect(result.innerObject.key1).toBe('extantData')
expect(result.innerObject.key2).toBe('value2')
# In order to support the default structure below, would need to
# make populateData a bit more complicated, with some custom merging logic.
# Going to see if we can get away without it first.
# it 'merges default objects from parent schemas down to child extant data', ->
# schema = {
# type: 'object'
# default: { innerObject: { key1: 'value1', key2: 'valuePI:KEY:<KEY>END_PI' } }
# }
#
# data = { innerObject: { prop1: 'extantData' } }
#
# result = TreemaNode.utils.populateDefaults(data, schema)
#
# expect(result.innerObject).toBeDefined()
# expect(result.innerObject.prop1).toBe('extantData')
# expect(result.innerObject.prop2).toBe('2')
describe 'walk', ->
it 'calls a callback on every piece of data in a JSON object, providing path, data and working schema', ->
schema = {
type: 'object'
properties:
key1: { title: 'Number 1' }
key2: { title: 'Number 2' }
}
data = { key1: 1, key2: 2 }
paths = []
values = []
TreemaNode.utils.walk data, schema, null, (path, data, schema) ->
paths.push(path)
values.push(data)
expect(paths.length).toBe(3)
expect('' in paths).toBe(true)
expect('key1' in paths).toBe(true)
expect('key2' in paths).toBe(true)
expect(data in values).toBe(true)
expect(data.key1 in values).toBe(true)
expect(data.key2 in values).toBe(true)
it 'traverses arrays', ->
schema = {
type: 'array'
items: {
type: 'object'
marker: true
}
}
data = [{}]
foundIt = false
TreemaNode.utils.walk data, schema, null, (path, data, schema) ->
if path is '0'
expect(schema.marker).toBe(true)
foundIt = true
expect(foundIt).toBe(true)
describe 'getChildSchema', ->
it 'returns child schemas from properties', ->
schema = { properties: { key1: { title: 'some title' } }}
childSchema = TreemaNode.utils.getChildSchema('key1', schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from additionalProperties', ->
schema = { additionalProperties: { title: 'some title' } }
childSchema = TreemaNode.utils.getChildSchema('key1', schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from patternProperties', ->
schema = { patternProperties: { '^[a-z]+$': { title: 'some title' } }}
childSchema = TreemaNode.utils.getChildSchema('key', schema)
expect(childSchema.title).toBe('some title')
childSchema = TreemaNode.utils.getChildSchema('123', schema)
expect(childSchema.title).toBeUndefined()
it 'returns child schemas from an items schema', ->
schema = { items: { title: 'some title' } }
childSchema = TreemaNode.utils.getChildSchema(0, schema)
expect(childSchema.title).toBe('some title')
it 'returns child schemas from an items array of schemas', ->
schema = { items: [{ title: 'some title' }] }
childSchema = TreemaNode.utils.getChildSchema(0, schema)
expect(childSchema.title).toBe('some title')
childSchema = TreemaNode.utils.getChildSchema(1, schema)
expect(childSchema.title).toBeUndefined()
it 'returns child schemas from additionalItems', ->
schema = { items: [{ title: 'some title' }], additionalItems: { title: 'another title'} }
childSchema = TreemaNode.utils.getChildSchema(1, schema)
expect(childSchema.title).toBe('another title')
describe 'buildWorkingSchemas', ->
it 'returns the same single schema if there are no combinatorials or references', ->
schema = {}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas[0] is schema).toBeTruthy()
it 'combines allOf into a single schema', ->
schema = { title: 'title', allOf: [ { description: 'description' }, { type: 'number' } ]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(1)
workingSchema = workingSchemas[0]
expect(workingSchema.title).toBe('title')
expect(workingSchema.description).toBe('description')
expect(workingSchema.type).toBe('number')
it 'creates a separate working schema for each anyOf', ->
schema = { title: 'title', anyOf: [{ type: 'string' }, { type: 'number' }]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(2)
types = (schema.type for schema in workingSchemas)
expect('string' in types).toBe(true)
expect('number' in types).toBe(true)
it 'creates a separate working schema for each oneOf', ->
schema = { title: 'title', oneOf: [{ type: 'string' }, { type: 'number' }]}
workingSchemas = TreemaNode.utils.buildWorkingSchemas(schema)
expect(workingSchemas.length).toBe(2)
types = (schema.type for schema in workingSchemas)
expect('string' in types).toBe(true)
expect('number' in types).toBe(true)
# Eventually might want more advanced behaviors, like smartly combining types from "allOf" or "oneOf" schemas.
# But for now this more naive combination behavior will do.
|
[
{
"context": "omepage', (done) ->\n\t\tbrowser\n\t\t\t.fill('#email', 'test@test.test') # TODO: generate unique emails + server-side em",
"end": 395,
"score": 0.9998599290847778,
"start": 381,
"tag": "EMAIL",
"value": "test@test.test"
},
{
"context": "ver-side email validations\n\t\t... | test/test.coffee | adrienschuler/Battle-Arena | 0 | assert = require('assert')
Browser = require('zombie')
browser = new Browser()
# SIGNUP
describe '/user/signup', ->
it 'should access signup page', (done) ->
browser.visit 'http://localhost:5000/user/signup', ->
assert.equal browser.location.pathname, '/user/signup'
done()
it 'should signup and redirect to game homepage', (done) ->
browser
.fill('#email', 'test@test.test') # TODO: generate unique emails + server-side email validations
.fill('#username', 'test')
.fill('#password', 'test')
.pressButton '.submit', ->
assert.equal browser.location.pathname, '/game'
done()
# TCHAT
# describe '/game', ->
# it 'should send a public message', (done) ->
# browser
# .fill('#tchat-input', 'hello !')
# .clickLink '#tchat-send', ->
# browser.wait 1000, ->
# assert.equal browser.text('.user-msg:last-child'), 'hello !' # TODO: get last tchat msg
# done()
# LOGOUT
describe '/session/destroy', ->
it 'should logout from the game', (done) ->
browser
.clickLink '.nav-logout', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should not be able to access the game page anymore', (done) ->
browser.visit 'http://localhost:5000/game', ->
assert.equal browser.location.pathname, '/user/login'
done()
# LOGIN
describe '/user/login', ->
it 'should access login page', (done) ->
browser.visit 'http://localhost:5000/user/login', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should login and redirect to game homepage', (done) ->
browser
.fill('#username', 'test')
.fill('#password', 'test')
.pressButton '.submit', ->
assert.equal browser.location.pathname, '/game'
done()
# LOGOUT
describe '/session/destroy', ->
it 'should logout from the game', (done) ->
browser
.clickLink '.nav-logout', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should not be able to access the game page anymore', (done) ->
browser.visit 'http://localhost:5000/game', ->
assert.equal browser.location.pathname, '/user/login'
done() | 44476 | assert = require('assert')
Browser = require('zombie')
browser = new Browser()
# SIGNUP
describe '/user/signup', ->
it 'should access signup page', (done) ->
browser.visit 'http://localhost:5000/user/signup', ->
assert.equal browser.location.pathname, '/user/signup'
done()
it 'should signup and redirect to game homepage', (done) ->
browser
.fill('#email', '<EMAIL>') # TODO: generate unique emails + server-side email validations
.fill('#username', 'test')
.fill('#password', '<PASSWORD>')
.pressButton '.submit', ->
assert.equal browser.location.pathname, '/game'
done()
# TCHAT
# describe '/game', ->
# it 'should send a public message', (done) ->
# browser
# .fill('#tchat-input', 'hello !')
# .clickLink '#tchat-send', ->
# browser.wait 1000, ->
# assert.equal browser.text('.user-msg:last-child'), 'hello !' # TODO: get last tchat msg
# done()
# LOGOUT
describe '/session/destroy', ->
it 'should logout from the game', (done) ->
browser
.clickLink '.nav-logout', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should not be able to access the game page anymore', (done) ->
browser.visit 'http://localhost:5000/game', ->
assert.equal browser.location.pathname, '/user/login'
done()
# LOGIN
describe '/user/login', ->
it 'should access login page', (done) ->
browser.visit 'http://localhost:5000/user/login', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should login and redirect to game homepage', (done) ->
browser
.fill('#username', 'test')
.fill('#password', '<PASSWORD>')
.pressButton '.submit', ->
assert.equal browser.location.pathname, '/game'
done()
# LOGOUT
describe '/session/destroy', ->
it 'should logout from the game', (done) ->
browser
.clickLink '.nav-logout', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should not be able to access the game page anymore', (done) ->
browser.visit 'http://localhost:5000/game', ->
assert.equal browser.location.pathname, '/user/login'
done() | true | assert = require('assert')
Browser = require('zombie')
browser = new Browser()
# SIGNUP
describe '/user/signup', ->
it 'should access signup page', (done) ->
browser.visit 'http://localhost:5000/user/signup', ->
assert.equal browser.location.pathname, '/user/signup'
done()
it 'should signup and redirect to game homepage', (done) ->
browser
.fill('#email', 'PI:EMAIL:<EMAIL>END_PI') # TODO: generate unique emails + server-side email validations
.fill('#username', 'test')
.fill('#password', 'PI:PASSWORD:<PASSWORD>END_PI')
.pressButton '.submit', ->
assert.equal browser.location.pathname, '/game'
done()
# TCHAT
# describe '/game', ->
# it 'should send a public message', (done) ->
# browser
# .fill('#tchat-input', 'hello !')
# .clickLink '#tchat-send', ->
# browser.wait 1000, ->
# assert.equal browser.text('.user-msg:last-child'), 'hello !' # TODO: get last tchat msg
# done()
# LOGOUT
describe '/session/destroy', ->
it 'should logout from the game', (done) ->
browser
.clickLink '.nav-logout', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should not be able to access the game page anymore', (done) ->
browser.visit 'http://localhost:5000/game', ->
assert.equal browser.location.pathname, '/user/login'
done()
# LOGIN
describe '/user/login', ->
it 'should access login page', (done) ->
browser.visit 'http://localhost:5000/user/login', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should login and redirect to game homepage', (done) ->
browser
.fill('#username', 'test')
.fill('#password', 'PI:PASSWORD:<PASSWORD>END_PI')
.pressButton '.submit', ->
assert.equal browser.location.pathname, '/game'
done()
# LOGOUT
describe '/session/destroy', ->
it 'should logout from the game', (done) ->
browser
.clickLink '.nav-logout', ->
assert.equal browser.location.pathname, '/user/login'
done()
it 'should not be able to access the game page anymore', (done) ->
browser.visit 'http://localhost:5000/game', ->
assert.equal browser.location.pathname, '/user/login'
done() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.